instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Schema getSchema() {
return Public.PUBLIC;
}
@Override
public UniqueKey<ArticleRecord> getPrimaryKey() {
return Keys.ARTICLE_PKEY;
}
@Override
public List<UniqueKey<ArticleRecord>> getKeys() {
return Arrays.<UniqueKey<ArticleRecord>>asList(Keys.ARTICLE_PKEY);
}
@Override
public List<ForeignKey<ArticleRecord, ?>> getReferences() {
return Arrays.<ForeignKey<ArticleRecord, ?>>asList(Keys.ARTICLE__XXX);
}
public Author author() {
return new Author(this, Keys.ARTICLE__XXX);
}
@Override
public Article as(String alias) {
return new Article(DSL.name(alias), this);
}
@Override
public Article as(Name alias) {
return new Article(alias, this);
}
/**
* Rename this table
*/
@Override | public Article rename(String name) {
return new Article(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Article rename(Name name) {
return new Article(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Article.java | 1 |
请完成以下Java代码 | public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInUOM (final @Nullable BigDecimal QtyInUOM)
{
set_Value (COLUMNNAME_QtyInUOM, QtyInUOM);
}
@Override
public BigDecimal getQtyInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=541716
* Reference name: M_MatchInv_Type
*/ | public static final int TYPE_AD_Reference_ID=541716;
/** Material = M */
public static final String TYPE_Material = "M";
/** Cost = C */
public static final String TYPE_Cost = "C";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchInv.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<SysTenantPack> getPackListByTenantId(String tenantId) {
return sysTenantPackUserMapper.getPackListByTenantId(oConvertUtils.getInt(tenantId));
}
/**
* 根据套餐包的code 新增其他关联默认产品包下的角色与菜单的关系
*
* @param packCode
* @param permission
*/
private void addDefaultPackPermission(String packCode, String permission) {
if (oConvertUtils.isEmpty(packCode)) {
return;
}
//查询当前匹配非默认套餐包的其他默认套餐包
LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>();
query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT);
query.eq(SysTenantPack::getPackCode, packCode);
List<SysTenantPack> otherDefaultPacks = sysTenantPackMapper.selectList(query);
for (SysTenantPack pack : otherDefaultPacks) {
//新增套餐包用户菜单权限
this.addPermission(pack.getId(), permission);
}
}
/**
* 根据套餐包的code 删除其他关联默认套餐包下的角色与菜单的关系
*
* @param packCode
* @param permissionId
*/
private void deleteDefaultPackPermission(String packCode, String permissionId) {
if (oConvertUtils.isEmpty(packCode)) {
return;
}
//查询当前匹配非默认套餐包的其他默认套餐包
LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>();
query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT);
query.eq(SysTenantPack::getPackCode, packCode);
List<SysTenantPack> defaultPacks = sysTenantPackMapper.selectList(query);
for (SysTenantPack pack : defaultPacks) {
//删除套餐权限
deletePackPermission(pack.getId(), permissionId); | }
}
/**
* 同步同 packCode 下的相关套餐包数据
*
* @param sysTenantPack
*/
private void syncRelatedPackDataByDefaultPack(SysTenantPack sysTenantPack) {
//查询与默认套餐相同code的套餐
LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>();
query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT);
query.eq(SysTenantPack::getPackCode, sysTenantPack.getPackCode());
List<SysTenantPack> relatedPacks = sysTenantPackMapper.selectList(query);
for (SysTenantPack pack : relatedPacks) {
//更新自定义套餐
pack.setPackName(sysTenantPack.getPackName());
pack.setStatus(sysTenantPack.getStatus());
pack.setRemarks(sysTenantPack.getRemarks());
pack.setIzSysn(sysTenantPack.getIzSysn());
sysTenantPackMapper.updateById(pack);
//同步默认套餐报下的所有用户已
if (oConvertUtils.isNotEmpty(sysTenantPack.getIzSysn()) && CommonConstant.STATUS_1.equals(sysTenantPack.getIzSysn())) {
this.addPackUserByPackTenantId(pack.getTenantId(), pack.getId());
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTenantPackServiceImpl.java | 2 |
请完成以下Java代码 | public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
} | public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", deploymentId=" + deploymentId
+ ", tenantId=" + tenantId
+ ", type=" + type
+ ", createTime=" + createTime
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java | 1 |
请完成以下Java代码 | public void setClassname (final java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
@Override
public java.lang.String getClassname()
{
return get_ValueAsString(COLUMNNAME_Classname);
}
@Override
public void setM_IolCandHandler_ID (final int M_IolCandHandler_ID)
{
if (M_IolCandHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, M_IolCandHandler_ID);
}
@Override
public int getM_IolCandHandler_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_ID);
}
@Override
public void setTableName (final java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
@Override
public java.lang.String getTableName()
{
return get_ValueAsString(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_IolCandHandler.java | 1 |
请完成以下Java代码 | protected static boolean isNumber(Object obj) {
return obj instanceof Number;
}
protected Map<String, Object> createDefensiveCopyInputVariables(Map<String, Object> inputVariables) {
Map<String, Object> defensiveCopyMap = new HashMap<>();
if (inputVariables != null) {
for (Map.Entry<String, Object> entry : inputVariables.entrySet()) {
Object newValue = null;
if (entry.getValue() == null) {
// do nothing
} else if (entry.getValue() instanceof Long) {
newValue = Long.valueOf(((Long) entry.getValue()).longValue()); | } else if (entry.getValue() instanceof Double) {
newValue = Double.valueOf(((Double) entry.getValue()).doubleValue());
} else if (entry.getValue() instanceof Integer) {
newValue = Integer.valueOf(((Integer) entry.getValue()).intValue());
} else if (entry.getValue() instanceof Date) {
newValue = new Date(((Date) entry.getValue()).getTime());
} else if (entry.getValue() instanceof Boolean) {
newValue = Boolean.valueOf(((Boolean) entry.getValue()).booleanValue());
} else {
newValue = new String(entry.getValue().toString());
}
defensiveCopyMap.put(entry.getKey(), newValue);
}
}
return defensiveCopyMap;
}
} | repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionExecutionAuditContainer.java | 1 |
请完成以下Java代码 | public void setChildElements(Map<String, List<ExtensionElement>> childElements) {
this.childElements = childElements;
}
public ExtensionElement clone() {
ExtensionElement clone = new ExtensionElement();
clone.setValues(this);
return clone;
}
public void setValues(ExtensionElement otherElement) {
setName(otherElement.getName());
setNamespacePrefix(otherElement.getNamespacePrefix());
setNamespace(otherElement.getNamespace());
setElementText(otherElement.getElementText());
setAttributes(otherElement.getAttributes()); | childElements = new LinkedHashMap<String, List<ExtensionElement>>();
if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) {
for (String key : otherElement.getChildElements().keySet()) {
List<ExtensionElement> otherElementList = otherElement.getChildElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<ExtensionElement> elementList = new ArrayList<ExtensionElement>();
for (ExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
childElements.put(key, elementList);
}
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ExtensionElement.java | 1 |
请完成以下Java代码 | private HTTPIngressRuleValue buildHttpRule(DeptrackResource primary) {
return new HTTPIngressRuleValueBuilder()
// Backend route
.addNewPath()
.withPath("/api")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getApiServerServiceName())
.withNewPort()
.withName("http")
.endPort()
.endService()
.endBackend()
.endPath()
// Frontend route | .addNewPath()
.withPath("/")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getFrontendServiceName())
.withNewPort()
.withName("http")
.endPort()
.endService()
.endBackend()
.endPath()
.build();
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackIngressResource.java | 1 |
请完成以下Java代码 | public static <T> T getInstance(final String classname, final Class<T> interfaceClazz)
{
if (classname == null)
{
throw new IllegalArgumentException("classname is null");
}
if (interfaceClazz == null)
{
throw new IllegalArgumentException("interfaceClazz is null");
}
try
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
{
classLoader = Util.class.getClassLoader();
}
final Class<?> clazz = classLoader.loadClass(classname);
if (!interfaceClazz.isAssignableFrom(clazz))
{
throw new RuntimeException("Class " + classname + " doesn't implement " + interfaceClazz);
}
return clazz.asSubclass(interfaceClazz).newInstance();
}
catch (final ClassNotFoundException e)
{
throw new RuntimeException("Unable to instantiate '" + classname + "'", e);
}
catch (final InstantiationException e)
{
throw new RuntimeException("Unable to instantiate '" + classname + "'", e);
}
catch (final IllegalAccessException e)
{
throw new RuntimeException("Unable to instantiate '" + classname + "'", e);
}
}
public static String changeFileExtension(final String filename, final String extension)
{
final int idx = filename.lastIndexOf(".");
final StringBuilder sb = new StringBuilder();
if (idx > 0)
{
sb.append(filename.substring(0, idx));
}
else
{
sb.append(filename);
}
if (extension == null || extension.trim().length() == 0)
{
return sb.toString();
}
sb.append(".").append(extension.trim()); | return sb.toString();
}
/**
*
* @param filename
* @return file extension or null
*/
public static String getFileExtension(final String filename)
{
final int idx = filename.lastIndexOf(".");
if (idx > 0)
{
return filename.substring(idx + 1);
}
return null;
}
public static void close(final Closeable closeable)
{
if (closeable == null)
{
return;
}
try
{
closeable.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
public static String toString(final InputStream in)
{
return new String(toByteArray(in), StandardCharsets.UTF_8);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\util\Util.java | 1 |
请完成以下Java代码 | public void addChangedRowIds(final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
}
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds);
}
public void addChangedRowId(@NonNull final DocumentId rowId)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.add(rowId);
} | public DocumentIdsSelection getChangedRowIds()
{
final boolean fullyChanged = this.fullyChanged;
final Set<DocumentId> changedRowIds = this.changedRowIds;
if (fullyChanged)
{
return DocumentIdsSelection.ALL;
}
else if (changedRowIds == null || changedRowIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
else
{
return DocumentIdsSelection.of(changedRowIds);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java | 1 |
请完成以下Java代码 | public void setParameterName (String ParameterName)
{
set_Value (COLUMNNAME_ParameterName, ParameterName);
}
/** Get Parameter Name.
@return Parameter Name */
public String getParameterName ()
{
return (String)get_Value(COLUMNNAME_ParameterName);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getParameterName());
}
/** Set Process Date.
@param P_Date
Process Parameter
*/
public void setP_Date (Timestamp P_Date)
{
set_Value (COLUMNNAME_P_Date, P_Date);
}
/** Get Process Date.
@return Process Parameter
*/
public Timestamp getP_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_P_Date);
}
/** Set Process Date To.
@param P_Date_To
Process Parameter
*/
public void setP_Date_To (Timestamp P_Date_To)
{
set_Value (COLUMNNAME_P_Date_To, P_Date_To);
}
/** Get Process Date To.
@return Process Parameter
*/
public Timestamp getP_Date_To ()
{
return (Timestamp)get_Value(COLUMNNAME_P_Date_To);
}
/** Set Process Number.
@param P_Number
Process Parameter
*/
public void setP_Number (BigDecimal P_Number)
{
set_Value (COLUMNNAME_P_Number, P_Number);
}
/** Get Process Number.
@return Process Parameter
*/
public BigDecimal getP_Number ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Process Number To.
@param P_Number_To
Process Parameter
*/
public void setP_Number_To (BigDecimal P_Number_To)
{ | set_Value (COLUMNNAME_P_Number_To, P_Number_To);
}
/** Get Process Number To.
@return Process Parameter
*/
public BigDecimal getP_Number_To ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number_To);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Process String.
@param P_String
Process Parameter
*/
public void setP_String (String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Process Parameter
*/
public String getP_String ()
{
return (String)get_Value(COLUMNNAME_P_String);
}
/** Set Process String To.
@param P_String_To
Process Parameter
*/
public void setP_String_To (String P_String_To)
{
set_Value (COLUMNNAME_P_String_To, P_String_To);
}
/** Get Process String To.
@return Process Parameter
*/
public String getP_String_To ()
{
return (String)get_Value(COLUMNNAME_P_String_To);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (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_AD_PInstance_Para.java | 1 |
请完成以下Java代码 | public void updateIsAutoFlag(final I_ExternalSystem_Config_GRSSignum grsConfig)
{
if (!grsConfig.isSyncBPartnersToRestEndpoint())
{
grsConfig.setIsAutoSendVendors(false);
grsConfig.setIsAutoSendCustomers(false);
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = {
I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsCreateBPartnerFolders,
I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BasePathForExportDirectories,
I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BPartnerExportDirectories })
public void checkIsCreateBPartnerFoldersFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) | {
if (!grsConfig.isCreateBPartnerFolders())
{
return;
}
if (Check.isBlank(grsConfig.getBPartnerExportDirectories())
|| Check.isBlank(grsConfig.getBasePathForExportDirectories()))
{
throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!")
.appendParametersToMessage()
.setParameter("ExternalSystem_Config_GRSSignum_ID", grsConfig.getExternalSystem_Config_GRSSignum_ID());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\interceptor\ExternalSystem_Config_GRSSignum.java | 1 |
请完成以下Java代码 | public class WorkerNodeEntity {
/**
* Entity unique id (table unique)
*/
private long id;
/**
* Type of CONTAINER: HostName, ACTUAL : IP.
*/
private String hostName;
/**
* Type of CONTAINER: Port, ACTUAL : Timestamp + Random(0-10000)
*/
private String port;
/**
* type of {@link WorkerNodeType}
*/
private int type;
/**
* Worker launch date, default now
*/
private Date launchDate = new Date();
/**
* Created time
*/
private Date created;
/**
* Last modified
*/
private Date modified;
/**
* Getters & Setters
*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getHostName() {
return hostName;
} | public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Date getLaunchDate() {
return launchDate;
}
public void setLaunchDateDate(Date launchDate) {
this.launchDate = launchDate;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\worker\entity\WorkerNodeEntity.java | 1 |
请完成以下Java代码 | protected SecurityExpressionOperations createSecurityExpressionRoot(@Nullable Authentication authentication,
FilterInvocation fi) {
FilterInvocationExpressionRoot root = new FilterInvocationExpressionRoot(() -> authentication, fi);
root.setAuthorizationManagerFactory(getAuthorizationManagerFactory());
root.setPermissionEvaluator(getPermissionEvaluator());
if (!DEFAULT_ROLE_PREFIX.equals(this.defaultRolePrefix)) {
// Ensure SecurityExpressionRoot can strip the custom role prefix
root.setDefaultRolePrefix(this.defaultRolePrefix);
}
return root;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
getDefaultAuthorizationManagerFactory().setTrustResolver(trustResolver);
}
/**
* <p>
* Sets the default prefix to be added to
* {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)}
* or | * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}.
* For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the
* role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default).
* </p>
*
* <p>
* If null or empty, then no default role prefix is used.
* </p>
* @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_".
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setDefaultRolePrefix(@Nullable String defaultRolePrefix) {
if (defaultRolePrefix == null) {
defaultRolePrefix = "";
}
getDefaultAuthorizationManagerFactory().setRolePrefix(defaultRolePrefix);
this.defaultRolePrefix = defaultRolePrefix;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\DefaultWebSecurityExpressionHandler.java | 1 |
请完成以下Java代码 | public class CleanableHistoricDecisionInstanceReportDto extends AbstractQueryDto<CleanableHistoricDecisionInstanceReport>{
protected String[] decisionDefinitionIdIn;
protected String[] decisionDefinitionKeyIn;
protected String[] tenantIdIn;
protected Boolean withoutTenantId;
protected Boolean compact;
protected static final String SORT_BY_FINISHED_VALUE = "finished";
public static final List<String> VALID_SORT_BY_VALUES;
static {
VALID_SORT_BY_VALUES = new ArrayList<String>();
VALID_SORT_BY_VALUES.add(SORT_BY_FINISHED_VALUE);
}
public CleanableHistoricDecisionInstanceReportDto() {
}
public CleanableHistoricDecisionInstanceReportDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) {
super(objectMapper, queryParameters);
}
@CamundaQueryParam(value = "decisionDefinitionIdIn", converter = StringArrayConverter.class)
public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) {
this.decisionDefinitionIdIn = decisionDefinitionIdIn;
}
@CamundaQueryParam(value = "decisionDefinitionKeyIn", converter = StringArrayConverter.class)
public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) {
this.decisionDefinitionKeyIn = decisionDefinitionKeyIn;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class)
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value = "compact", converter = BooleanConverter.class)
public void setCompact(Boolean compact) {
this.compact = compact;
} | @Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport();
}
@Override
protected void applyFilters(CleanableHistoricDecisionInstanceReport query) {
if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) {
query.decisionDefinitionIdIn(decisionDefinitionIdIn);
}
if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) {
query.decisionDefinitionKeyIn(decisionDefinitionKeyIn);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIdIn != null && tenantIdIn.length > 0) {
query.tenantIdIn(tenantIdIn);
}
if (Boolean.TRUE.equals(compact)) {
query.compact();
}
}
@Override
protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_FINISHED_VALUE)) {
query.orderByFinished();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportDto.java | 1 |
请完成以下Java代码 | private void deactivateBPartnersAndRelatedEntries()
{
final Instant now = SystemTime.asInstant();
final List<BPartnerId> partnerIdsToDeactivate = queryBL.createQueryBuilder(I_AD_OrgChange_History.class)
.addCompareFilter(I_AD_OrgChange_History.COLUMNNAME_Date_OrgChange, CompareQueryFilter.Operator.LESS_OR_EQUAL, now)
.andCollect(I_AD_OrgChange_History.COLUMNNAME_C_BPartner_From_ID, I_C_BPartner.class)
.create()
.idsAsSet(BPartnerId::ofRepoId)
.asList();
partnerIdsToDeactivate.stream()
.forEach(
partnerId -> addLog("Business Partner {} was deactivated because it was moved to another organization.",
partnerId));
if (Check.isEmpty(partnerIdsToDeactivate))
{
// nothing to do
return;
}
deactivateBankAccounts(partnerIdsToDeactivate, now);
deactivateUsers(partnerIdsToDeactivate, now);
deactivateLocations(partnerIdsToDeactivate, now);
deactivatePartners(partnerIdsToDeactivate, now);
}
private void deactivateBankAccounts(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_C_BP_BankAccount> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BP_BankAccount.class)
.addSetColumnValue(I_C_BP_BankAccount.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_C_BP_BankAccount.class)
.addInArrayFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
private void deactivateUsers(final List<BPartnerId> partnerIds, final Instant date) | {
final ICompositeQueryUpdater<I_AD_User> queryUpdater = queryBL.createCompositeQueryUpdater(I_AD_User.class)
.addSetColumnValue(I_AD_User.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_AD_User.class)
.addInArrayFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
private void deactivateLocations(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_C_BPartner_Location> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner_Location.class)
.addSetColumnValue(I_C_BPartner_Location.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addInArrayFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
private void deactivatePartners(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_C_BPartner> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner.class)
.addSetColumnValue(I_C_BPartner.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_DeactivateAfterOrgChange.java | 1 |
请完成以下Java代码 | /* package */void setLookupValuesStale(final Boolean lookupValuesStale, final ReasonSupplier reason)
{
this.lookupValuesStale = lookupValuesStale;
lookupValuesStaleReason = reason;
logger.trace("collect {} lookupValuesStale: {} -- {}", fieldName, lookupValuesStale, lookupValuesStaleReason);
}
public DocumentValidStatus getValidStatus()
{
return validStatus;
}
/* package */void setValidStatus(final DocumentValidStatus validStatus)
{
this.validStatus = validStatus;
logger.trace("collect {} validStatus: {}", fieldName, validStatus);
}
/* package */ void mergeFrom(final DocumentFieldChange fromEvent)
{
if (fromEvent.valueSet)
{
valueSet = true;
value = fromEvent.value;
valueReason = fromEvent.valueReason;
}
//
if (fromEvent.readonly != null)
{
readonly = fromEvent.readonly;
readonlyReason = fromEvent.readonlyReason;
}
//
if (fromEvent.mandatory != null)
{
mandatory = fromEvent.mandatory;
mandatoryReason = fromEvent.mandatoryReason;
}
//
if (fromEvent.displayed != null)
{
displayed = fromEvent.displayed;
displayedReason = fromEvent.displayedReason;
}
//
if (fromEvent.lookupValuesStale != null)
{
lookupValuesStale = fromEvent.lookupValuesStale;
lookupValuesStaleReason = fromEvent.lookupValuesStaleReason;
}
if (fromEvent.validStatus != null)
{
validStatus = fromEvent.validStatus;
}
if(fromEvent.fieldWarning != null)
{
fieldWarning = fromEvent.fieldWarning;
}
putDebugProperties(fromEvent.debugProperties);
}
/* package */ void mergeFrom(final IDocumentFieldChangedEvent fromEvent)
{
if (fromEvent.isValueSet())
{
valueSet = true;
value = fromEvent.getValue();
valueReason = null; // N/A | }
}
public void putDebugProperty(final String name, final Object value)
{
if (debugProperties == null)
{
debugProperties = new LinkedHashMap<>();
}
debugProperties.put(name, value);
}
public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
if (this.debugProperties == null)
{
this.debugProperties = new LinkedHashMap<>();
}
this.debugProperties.putAll(debugProperties);
}
public Map<String, Object> getDebugProperties()
{
return debugProperties == null ? ImmutableMap.of() : debugProperties;
}
public void setFieldWarning(@NonNull final DocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public DocumentFieldWarning getFieldWarning()
{
return fieldWarning;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldChange.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long findVariableInstanceCountByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) {
return dataManager.findVariableInstanceCountByQueryCriteria(variableInstanceQuery);
}
@Override
public List<VariableInstance> findVariableInstancesByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) {
return dataManager.findVariableInstancesByQueryCriteria(variableInstanceQuery);
}
@Override
public List<VariableInstance> findVariableInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findVariableInstancesByNativeQuery(parameterMap);
}
@Override
public long findVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findVariableInstanceCountByNativeQuery(parameterMap);
}
@Override
public void delete(VariableInstanceEntity entity, boolean fireDeleteEvent) {
super.delete(entity, false);
ByteArrayRef byteArrayRef = entity.getByteArrayRef();
if (byteArrayRef != null) {
byteArrayRef.delete(serviceConfiguration.getEngineName());
}
entity.setDeleted(true); | }
@Override
public void deleteVariablesByTaskId(String taskId) {
dataManager.deleteVariablesByTaskId(taskId);
}
@Override
public void deleteVariablesByExecutionId(String executionId) {
dataManager.deleteVariablesByExecutionId(executionId);
}
@Override
public void deleteByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public void deleteByScopeIdAndScopeTypes(String scopeId, Collection<String> scopeTypes) {
dataManager.deleteByScopeIdAndScopeTypes(scopeId, scopeTypes);
}
@Override
public void deleteBySubScopeIdAndScopeTypes(String subScopeId, Collection<String> scopeTypes) {
dataManager.deleteBySubScopeIdAndScopeTypes(subScopeId, scopeTypes);
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInstanceEntityManagerImpl.java | 2 |
请完成以下Java代码 | public String getCauseIncidentProcessInstanceId() {
return causeIncidentProcessInstanceId;
}
public void setCauseIncidentProcessInstanceId(String causeIncidentProcessInstanceId) {
this.causeIncidentProcessInstanceId = causeIncidentProcessInstanceId;
}
public String getCauseIncidentProcessDefinitionId() {
return causeIncidentProcessDefinitionId;
}
public String getCauseIncidentActivityId() {
return causeIncidentActivityId;
}
public void setCauseIncidentActivityId(String causeIncidentActivityId) {
this.causeIncidentActivityId = causeIncidentActivityId;
}
public String getCauseIncidentFailedActivityId() {
return causeIncidentFailedActivityId;
}
public void setCauseIncidentFailedActivityId(String causeIncidentFailedActivityId) {
this.causeIncidentFailedActivityId = causeIncidentFailedActivityId;
}
public void setCauseIncidentProcessDefinitionId(String causeIncidentProcessDefinitionId) {
this.causeIncidentProcessDefinitionId = causeIncidentProcessDefinitionId;
}
public String getRootCauseIncidentProcessInstanceId() {
return rootCauseIncidentProcessInstanceId;
}
public void setRootCauseIncidentProcessInstanceId(String rootCauseIncidentProcessInstanceId) {
this.rootCauseIncidentProcessInstanceId = rootCauseIncidentProcessInstanceId;
}
public String getRootCauseIncidentProcessDefinitionId() {
return rootCauseIncidentProcessDefinitionId;
}
public void setRootCauseIncidentProcessDefinitionId(String rootCauseIncidentProcessDefinitionId) {
this.rootCauseIncidentProcessDefinitionId = rootCauseIncidentProcessDefinitionId;
}
public String getRootCauseIncidentActivityId() {
return rootCauseIncidentActivityId;
}
public void setRootCauseIncidentActivityId(String rootCauseIncidentActivityId) {
this.rootCauseIncidentActivityId = rootCauseIncidentActivityId; | }
public String getRootCauseIncidentFailedActivityId() {
return rootCauseIncidentFailedActivityId;
}
public void setRootCauseIncidentFailedActivityId(String rootCauseIncidentFailedActivityId) {
this.rootCauseIncidentFailedActivityId = rootCauseIncidentFailedActivityId;
}
public String getRootCauseIncidentConfiguration() {
return rootCauseIncidentConfiguration;
}
public void setRootCauseIncidentConfiguration(String rootCauseIncidentConfiguration) {
this.rootCauseIncidentConfiguration = rootCauseIncidentConfiguration;
}
public String getRootCauseIncidentMessage() {
return rootCauseIncidentMessage;
}
public void setRootCauseIncidentMessage(String rootCauseIncidentMessage) {
this.rootCauseIncidentMessage = rootCauseIncidentMessage;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\IncidentDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
public String appendIdentitySelectToInsert(String insertString) {
return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
append(insertString).
append("; ").append(getIdentitySelectString()).
toString();
}
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length() + 20).
append(query).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column"; | }
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
} | repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\config\SQLiteDialect.java | 2 |
请完成以下Java代码 | public DetailsBuilder processEngineName(String processEngineName) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.add(processEngineName);
return this;
}
public DetailsBuilder processEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.addAll(processEngineNames);
return this;
}
public DetailsBuilder clearProcessEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames != null) {
this.processEngineNames.clear();
}
return this;
}
public Details build() {
return new Details(this);
}
}
public String getName() {
return name;
}
public String getLockOwner() {
return lockOwner;
}
public int getLockTimeInMillis() {
return lockTimeInMillis;
} | public int getMaxJobsPerAcquisition() {
return maxJobsPerAcquisition;
}
public int getWaitTimeInMillis() {
return waitTimeInMillis;
}
public Set<String> getProcessEngineNames() {
return processEngineNames;
}
@Override
public String toString() {
return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis="
+ lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition
+ ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames
+ "]";
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\actuator\JobExecutorHealthIndicator.java | 1 |
请完成以下Java代码 | public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
private void addExecutionListener(final ActivityImpl activity) {
if (executionListener != null) {
for (String event : EXECUTION_EVENTS) {
addListenerOnCoreModelElement(activity, executionListener, event);
}
}
}
private void addExecutionListener(final TransitionImpl transition) {
if (executionListener != null) {
addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE);
}
}
private void addListenerOnCoreModelElement(CoreModelElement element, | DelegateListener<?> listener, String event) {
if (skippable) {
element.addListener(event, listener);
} else {
element.addBuiltInListener(event, listener);
}
}
private void addTaskListener(TaskDefinition taskDefinition) {
if (taskListener != null) {
for (String event : TASK_EVENTS) {
if (skippable) {
taskDefinition.addTaskListener(event, taskListener);
} else {
taskDefinition.addBuiltInTaskListener(event, taskListener);
}
}
}
}
/**
* Retrieves task definition.
*
* @param activity the taskActivity
* @return taskDefinition for activity
*/
private TaskDefinition taskDefinition(final ActivityImpl activity) {
final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
return activityBehavior.getTaskDefinition();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java | 1 |
请完成以下Java代码 | public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
private final String refreshToken;
private final Set<String> scopes;
/**
* Constructs an {@code OAuth2RefreshTokenAuthenticationToken} using the provided
* parameters.
* @param refreshToken the refresh token
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param additionalParameters the additional parameters
*/
public OAuth2RefreshTokenAuthenticationToken(String refreshToken, Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
Assert.hasText(refreshToken, "refreshToken cannot be empty");
this.refreshToken = refreshToken; | this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
}
/**
* Returns the refresh token.
* @return the refresh token
*/
public String getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the requested scope(s).
* @return the requested scope(s), or an empty {@code Set} if not available
*/
public Set<String> getScopes() {
return this.scopes;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2RefreshTokenAuthenticationToken.java | 1 |
请完成以下Java代码 | public void updateByQuery(@NonNull final DDOrderCandidateQuery query, @NonNull final UnaryOperator<DDOrderCandidate> updater)
{
final List<I_DD_Order_Candidate> records = toSqlQuery(query).create().list();
for (final I_DD_Order_Candidate record : records)
{
final DDOrderCandidate candidate = fromRecord(record);
final DDOrderCandidate changedCandidate = updater.apply(candidate);
if (Objects.equals(candidate, changedCandidate))
{
continue;
}
updateRecord(record, changedCandidate);
InterfaceWrapperHelper.save(record);
}
}
public PInstanceId createSelection(@NonNull final Collection<DDOrderCandidateId> ids)
{
if (ids.isEmpty())
{
throw new AdempiereException("no IDs provided"); | }
return queryBL.createQueryBuilder(I_DD_Order_Candidate.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_DD_Order_Candidate.COLUMNNAME_DD_Order_Candidate_ID, ids)
.create()
.createSelection();
}
public List<DDOrderCandidate> getBySelectionId(@NonNull final PInstanceId selectionId)
{
return queryBL.createQueryBuilder(I_DD_Order_Candidate.class)
.orderBy(I_DD_Order_Candidate.COLUMNNAME_DD_Order_Candidate_ID) // just to have a predictable order
.setOnlySelection(selectionId)
.create()
.stream()
.map(DDOrderCandidateRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidateRepository.java | 1 |
请完成以下Java代码 | public class UnionFind {
private int[] parents;
private int[] ranks;
public UnionFind(int n) {
parents = new int[n];
ranks = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
ranks[i] = 0;
}
}
public int find(int u) {
while (u != parents[u]) {
u = parents[u];
}
return u;
}
public void union(int u, int v) {
int uParent = find(u); | int vParent = find(v);
if (uParent == vParent) {
return;
}
if (ranks[uParent] < ranks[vParent]) {
parents[uParent] = vParent;
} else if (ranks[uParent] > ranks[vParent]) {
parents[vParent] = uParent;
} else {
parents[vParent] = uParent;
ranks[uParent]++;
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\boruvka\UnionFind.java | 1 |
请完成以下Java代码 | public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
}
@Override
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
List<HistoricVariableInstanceEntity> historicProcessVariables =
historicVariableInstanceDataManager.findHistoricVariableInstancesByTaskId(taskId);
for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
delete((HistoricVariableInstanceEntity) historicProcessVariable);
}
}
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicVariableInstanceDataManager.findHistoricVariableInstancesByNativeQuery(
parameterMap,
firstResult,
maxResults
); | }
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
}
public HistoricVariableInstanceDataManager getHistoricVariableInstanceDataManager() {
return historicVariableInstanceDataManager;
}
public void setHistoricVariableInstanceDataManager(
HistoricVariableInstanceDataManager historicVariableInstanceDataManager
) {
this.historicVariableInstanceDataManager = historicVariableInstanceDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java | 1 |
请完成以下Java代码 | static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
}
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
} | }
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\matrixtozero\SetMatrixToZero.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) { | this.withoutTenantId = withoutTenantId;
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
}
public void setIncludeLocalVariables(Boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public class RemittanceLocation4 {
@XmlElement(name = "RmtId")
protected String rmtId;
@XmlElement(name = "RmtLctnDtls")
protected List<RemittanceLocationDetails1> rmtLctnDtls;
/**
* Gets the value of the rmtId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRmtId() {
return rmtId;
}
/**
* Sets the value of the rmtId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRmtId(String value) {
this.rmtId = value;
}
/** | * Gets the value of the rmtLctnDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rmtLctnDtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRmtLctnDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RemittanceLocationDetails1 }
*
*
*/
public List<RemittanceLocationDetails1> getRmtLctnDtls() {
if (rmtLctnDtls == null) {
rmtLctnDtls = new ArrayList<RemittanceLocationDetails1>();
}
return this.rmtLctnDtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\RemittanceLocation4.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getBIC() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
/**
* Gets the value of the bankAccountNr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountNr() {
return bankAccountNr;
}
/**
* Sets the value of the bankAccountNr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountNr(String value) {
this.bankAccountNr = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIBAN() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setIBAN(String value) {
this.iban = value;
}
/**
* Gets the value of the bankAccountOwner property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountOwner() {
return bankAccountOwner;
}
/**
* Sets the value of the bankAccountOwner property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountOwner(String value) {
this.bankAccountOwner = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdditionalBankAccountType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PostController extends BladeController {
private IPostService postService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入post")
public R<PostVO> detail(Post post) {
Post detail = postService.getOne(Condition.getQueryWrapper(post));
return R.data(PostWrapper.build().entityVO(detail));
}
/**
* 分页 岗位表
*/
@GetMapping("/list")
@ApiOperationSupport(order = 2)
@Operation(summary = "分页", description = "传入post")
public R<IPage<PostVO>> list(Post post, Query query) {
IPage<Post> pages = postService.page(Condition.getPage(query), Condition.getQueryWrapper(post));
return R.data(PostWrapper.build().pageVO(pages));
}
/**
* 自定义分页 岗位表
*/
@GetMapping("/page")
@ApiOperationSupport(order = 3)
@Operation(summary = "分页", description = "传入post")
public R<IPage<PostVO>> page(PostVO post, Query query) {
IPage<PostVO> pages = postService.selectPostPage(Condition.getPage(query), post);
return R.data(pages);
}
/**
* 新增 岗位表
*/
@PostMapping("/save")
@ApiOperationSupport(order = 4)
@Operation(summary = "新增", description = "传入post")
public R save(@Valid @RequestBody Post post) {
return R.status(postService.save(post));
} | /**
* 修改 岗位表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改", description = "传入post")
public R update(@Valid @RequestBody Post post) {
return R.status(postService.updateById(post));
}
/**
* 新增或修改 岗位表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 6)
@Operation(summary = "新增或修改", description = "传入post")
public R submit(@Valid @RequestBody Post post) {
post.setTenantId(SecureUtil.getTenantId());
return R.status(postService.saveOrUpdate(post));
}
/**
* 删除 岗位表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 7)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(postService.deleteLogic(Func.toLongList(ids)));
}
/**
* 下拉数据源
*/
@GetMapping("/select")
@ApiOperationSupport(order = 8)
@Operation(summary = "下拉数据源", description = "传入post")
public R<List<Post>> select(String tenantId, BladeUser bladeUser) {
List<Post> list = postService.list(Wrappers.<Post>query().lambda().eq(Post::getTenantId, Func.toStr(tenantId, bladeUser.getTenantId())));
return R.data(list);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\PostController.java | 2 |
请完成以下Java代码 | public class EchoServer {
private static final String POISON_PILL = "POISON_PILL";
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", 5454));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(256);
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
register(selector, serverSocket);
}
if (key.isReadable()) {
answerWithEcho(buffer, key);
}
iter.remove();
}
}
}
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
int r = client.read(buffer);
if (r == -1 || new String(buffer.array()).trim()
.equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
buffer.flip();
client.write(buffer); | buffer.clear();
}
}
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = EchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
} | repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\selector\EchoServer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public int getSocketBufferSize() {
return this.socketBufferSize;
}
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getSubscriptionCapacity() {
return this.subscriptionCapacity;
}
public void setSubscriptionCapacity(int subscriptionCapacity) {
this.subscriptionCapacity = subscriptionCapacity;
}
public String getSubscriptionDiskStoreName() {
return this.subscriptionDiskStoreName;
} | public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) {
this.subscriptionDiskStoreName = subscriptionDiskStoreName;
}
public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() {
return this.subscriptionEvictionPolicy;
}
public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) {
this.subscriptionEvictionPolicy = subscriptionEvictionPolicy;
}
public boolean isTcpNoDelay() {
return this.tcpNoDelay;
}
public void setTcpNoDelay(boolean tcpNoDelay) {
this.tcpNoDelay = tcpNoDelay;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java | 2 |
请完成以下Java代码 | private static boolean hasLoop(final RoleId roleId, final List<RoleId> trace)
{
final List<RoleId> trace2;
if (trace == null)
{
trace2 = new ArrayList<>();
}
else
{
trace2 = new ArrayList<>(trace);
}
trace2.add(roleId);
//
final String sql = "SELECT "
+ I_AD_Role_Included.COLUMNNAME_Included_Role_ID
+ "," + I_AD_Role_Included.COLUMNNAME_AD_Role_ID
+ " FROM " + I_AD_Role_Included.Table_Name
+ " WHERE " + I_AD_Role_Included.COLUMNNAME_AD_Role_ID + "=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, roleId);
rs = pstmt.executeQuery();
while (rs.next())
{
final RoleId childId = RoleId.ofRepoId(rs.getInt(1));
if (trace2.contains(childId))
{
trace.clear();
trace.addAll(trace2);
trace.add(childId);
return true;
} | if (hasLoop(childId, trace2))
{
trace.clear();
trace.addAll(trace2);
return true;
}
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
//
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Role_Included.java | 1 |
请完成以下Java代码 | public String getDescription()
{
return m_description;
}
/**
* Set Description
* @param newDescription description
*/
public void setDescription(String newDescription)
{
m_description = newDescription;
} // setDescription
/**
* Extension
* @param newExtension ext
*/
public void setExtension(String newExtension)
{
m_extension = newExtension;
}
/**
* Get Extension
* @return extension
*/
public String getExtension()
{
return m_extension;
}
/**
* Accept File
* @param file file to be tested
* @return true if OK
*/
public boolean accept(File file)
{
// Need to accept directories
if (file.isDirectory())
return true;
String ext = file.getName();
int pos = ext.lastIndexOf('.');
// No extension
if (pos == -1)
return false;
ext = ext.substring(pos+1);
if (m_extension.equalsIgnoreCase(ext))
return true;
return false;
} // accept
/**
* Verify file name with filer
* @param file file
* @param filter filter
* @return file name
*/
public static String getFileName(File file, FileFilter filter)
{ | return getFile(file, filter).getAbsolutePath();
} // getFileName
/**
* Verify file with filter
* @param file file
* @param filter filter
* @return file
*/
public static File getFile(File file, FileFilter filter)
{
String fName = file.getAbsolutePath();
if (fName == null || fName.equals(""))
fName = "Adempiere";
//
ExtensionFileFilter eff = null;
if (filter instanceof ExtensionFileFilter)
eff = (ExtensionFileFilter)filter;
else
return file;
//
int pos = fName.lastIndexOf('.');
// No extension
if (pos == -1)
{
fName += '.' + eff.getExtension();
return new File(fName);
}
String ext = fName.substring(pos+1);
// correct extension
if (ext.equalsIgnoreCase(eff.getExtension()))
return file;
fName += '.' + eff.getExtension();
return new File(fName);
} // getFile
} // ExtensionFileFilter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java | 1 |
请完成以下Java代码 | private CreateReceiptCandidateRequestBuilder createReceiptCandidateRequestBuilder(final AggregationKey key)
{
return CreateReceiptCandidateRequest.builder()
.orderId(orderId)
.orderBOMLineId(coByProductOrderBOMLineId)
.orgId(orgId)
.date(date)
.locatorId(key.getLocatorId())
.topLevelHUId(key.getTopLevelHUId())
.productId(key.getProductId())
.pickingCandidateId(pickingCandidateId);
}
@Builder
@Value
private static class AggregationKey
{
@NonNull
LocatorId locatorId;
@NonNull
HuId topLevelHUId;
@NonNull
ProductId productId;
}
}
//
//
//
//
//
private interface LUTUSpec
{
}
@Value
private static class HUPIItemProductLUTUSpec implements LUTUSpec
{
public static final HUPIItemProductLUTUSpec VIRTUAL = new HUPIItemProductLUTUSpec(HUPIItemProductId.VIRTUAL_HU, null);
@NonNull HUPIItemProductId tuPIItemProductId;
@Nullable HuPackingInstructionsItemId luPIItemId;
public static HUPIItemProductLUTUSpec topLevelTU(@NonNull HUPIItemProductId tuPIItemProductId) | {
return tuPIItemProductId.isVirtualHU()
? VIRTUAL
: new HUPIItemProductLUTUSpec(tuPIItemProductId, null);
}
public static HUPIItemProductLUTUSpec lu(@NonNull HUPIItemProductId tuPIItemProductId, @NonNull HuPackingInstructionsItemId luPIItemId)
{
return new HUPIItemProductLUTUSpec(tuPIItemProductId, luPIItemId);
}
public boolean isTopLevelVHU()
{
return tuPIItemProductId.isVirtualHU() && luPIItemId == null;
}
}
@Value(staticConstructor = "of")
private static class PreciseTUSpec implements LUTUSpec
{
@NonNull HuPackingInstructionsId tuPackingInstructionsId;
@NonNull Quantity qtyCUsPerTU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\AbstractPPOrderReceiptHUProducer.java | 1 |
请完成以下Java代码 | public class HibernateUtil {
private static final String DEFAULT_RESOURCE = "manytomany.cfg.xml";
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
private static SessionFactory buildSessionFactory(String resource) {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Question.class);
configuration.addPackage(Question.class.getPackageName());
configuration.configure(resource);
LOGGER.debug("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build(); | LOGGER.debug("Hibernate Annotation serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return buildSessionFactory(DEFAULT_RESOURCE);
}
public static SessionFactory getSessionFactory(String resource) {
return buildSessionFactory(resource);
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\booleanconverters\HibernateUtil.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final List<I_C_Invoice_Candidate> ics = getSelectedInvoiceCandidates();
final MaterialTrackingId materialTrackingId = MaterialTrackingId.ofRepoIdOrNull(p_M_Material_Tracking_ID);
if (materialTrackingId == null)
{
invoiceCandService.unlinkMaterialTrackings(ics, p_isClearAggregationKeyOverride);
}
else
{
invoiceCandService.linkMaterialTrackings(ics, materialTrackingId);
} | return MSG_OK;
}
private List<I_C_Invoice_Candidate> getSelectedInvoiceCandidates()
{
final IQueryFilter<I_C_Invoice_Candidate> selectedPartners = getProcessInfo().getQueryFilterOrElseFalse();
return queryBL.createQueryBuilder(I_C_Invoice_Candidate.class, getCtx(), ITrx.TRXNAME_ThreadInherited)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false)
.addFilter(selectedPartners)
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\C_Invoice_Candidate_Assign_MaterialTracking.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-admin-server # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
service: ${spring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。
mail: # 配置发送告警的邮箱
host: smtp.126.com
username: wwbmlhh@126.com
password: ' | ******'
default-encoding: UTF-8
boot:
admin:
notify:
mail:
from: ${spring.mail.username} # 告警发件人
to: 7685413@qq.com # 告警收件人 | repos\SpringBoot-Labs-master\labx-15\labx-15-admin-04-adminserver-mail\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public BigDecimal getQtyTU()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_QtyPacks);
return qty;
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_QtyPacks, rowIndexModel, qtyPacks);
}
@Override
public int getC_UOM_ID()
{
return Services.get(IProductBL.class).getStockUOMId(getM_Product_ID()).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
throw new UnsupportedOperationException();
}
@Override | public void setC_BPartner_ID(final int partnerId)
{
throw new UnsupportedOperationException();
}
@Override
public int getC_BPartner_ID()
{
final KeyNamePair bpartnerKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_C_BPartner_ID);
return bpartnerKNP != null ? bpartnerKNP.getKey() : -1;
}
@Override
public boolean isInDispute()
{
// there is no InDispute flag to be considered
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareInfoWindowAdapter.java | 1 |
请完成以下Java代码 | public Map<String, Map<String, List<GraphicInfo>>> getDecisionServiceDividerLocationByDiagramIdMap() {
return decisionServiceDividerLocationByDiagramIdMap;
}
public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMapByDiagramId(String diagramId) {
return decisionServiceDividerLocationByDiagramIdMap.get(diagramId);
}
public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMap() {
return decisionServiceDividerLocationMap;
}
public List<GraphicInfo> getDecisionServiceDividerGraphicInfo(String key) {
return decisionServiceDividerLocationMap.get(key);
}
public void addDecisionServiceDividerGraphicInfoList(String key, List<GraphicInfo> graphicInfoList) {
decisionServiceDividerLocationMap.put(key, graphicInfoList);
}
public void addDecisionServiceDividerGraphicInfoListByDiagramId(String diagramId, String key, List<GraphicInfo> graphicInfoList) {
decisionServiceDividerLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>());
decisionServiceDividerLocationByDiagramIdMap.get(diagramId).put(key, graphicInfoList);
decisionServiceDividerLocationMap.put(key, graphicInfoList);
}
public String getExporter() {
return exporter; | }
public void setExporter(String exporter) {
this.exporter = exporter;
}
public String getExporterVersion() {
return exporterVersion;
}
public void setExporterVersion(String exporterVersion) {
this.exporterVersion = exporterVersion;
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public void addNamespace(String prefix, String uri) {
namespaceMap.put(prefix, uri);
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnDefinition.java | 1 |
请完成以下Java代码 | public void insertBatch(BatchEntity batch) {
batch.setCreateUserId(getCommandContext().getAuthenticatedUserId());
getDbEntityManager().insert(batch);
}
public BatchEntity findBatchById(String id) {
return getDbEntityManager().selectById(BatchEntity.class, id);
}
public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) {
configureQuery(batchQuery);
return (Long) getDbEntityManager().selectOne("selectBatchCountByQueryCriteria", batchQuery);
}
@SuppressWarnings("unchecked")
public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery, Page page) {
configureQuery(batchQuery);
return getDbEntityManager().selectList("selectBatchesByQueryCriteria", batchQuery, page);
}
public void updateBatchSuspensionStateById(String batchId, SuspensionState suspensionState) { | Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("batchId", batchId);
parameters.put("suspensionState", suspensionState.getStateCode());
ListQueryParameterObject queryParameter = new ListQueryParameterObject();
queryParameter.setParameter(parameters);
getDbEntityManager().update(BatchEntity.class, "updateBatchSuspensionStateByParameters", queryParameter);
}
protected void configureQuery(BatchQueryImpl batchQuery) {
getAuthorizationManager().configureBatchQuery(batchQuery);
getTenantManager().configureQuery(batchQuery);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\BatchManager.java | 1 |
请完成以下Java代码 | public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请完成以下Java代码 | public List<FlowableListener> getTaskListeners() {
return taskListeners;
}
public void setTaskListeners(List<FlowableListener> taskListeners) {
this.taskListeners = taskListeners;
}
@Override
public HumanTask clone() {
HumanTask clone = new HumanTask();
clone.setValues(this);
return clone;
}
public void setValues(HumanTask otherElement) {
super.setValues(otherElement); | setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setValidateFormFields(otherElement.getValidateFormFields());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java | 1 |
请完成以下Java代码 | public boolean isPending() {return this == POSPaymentProcessingStatus.PENDING;}
public boolean isPendingOrSuccessful() {return isPending() || isSuccessful();}
public boolean isSuccessful() {return this == POSPaymentProcessingStatus.SUCCESSFUL;}
public boolean isFailed() {return this == POSPaymentProcessingStatus.FAILED;}
public boolean isCanceled() {return this == POSPaymentProcessingStatus.CANCELLED;}
public boolean isDeleted() {return this == POSPaymentProcessingStatus.DELETED;}
public boolean isAllowCheckout()
{
return isNew() || isCanceled() || isFailed();
}
public void assertAllowCheckout()
{
if (!isAllowCheckout())
{
throw new AdempiereException("Payments with status " + this + " cannot be checked out");
}
}
public BooleanWithReason checkAllowDeleteFromDB()
{
return isNew() ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted from DB");
}
public BooleanWithReason checkAllowDelete(final POSPaymentMethod paymentMethod)
{
if (checkAllowDeleteFromDB().isTrue())
{
return BooleanWithReason.TRUE;
} | else if (paymentMethod.isCash() && isPending())
{
return BooleanWithReason.TRUE;
}
else if (isCanceled() || isFailed())
{
return BooleanWithReason.TRUE;
}
else
{
return BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted");
}
}
public boolean isAllowRefund()
{
return isSuccessful();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentProcessingStatus.java | 1 |
请完成以下Java代码 | private Deployment withProjectVersion1Based(Deployment deployment) {
String projectReleaseVersion = deployment.getProjectReleaseVersion();
if (StringUtils.isNumeric(projectReleaseVersion)) {
//The project version in the database is 0 based while in the devops section is 1 based
DeploymentImpl result = new DeploymentImpl();
result.setVersion(deployment.getVersion());
result.setId(deployment.getId());
result.setName(deployment.getName());
int projectReleaseVersionInt = Integer.valueOf(projectReleaseVersion) + 1;
result.setProjectReleaseVersion(String.valueOf(projectReleaseVersionInt));
return result;
} else {
return deployment;
}
}
private ApplicationEvents getEventType() {
ApplicationEvents eventType; | if (afterRollback) {
LOGGER.info("This pod has been marked as created after a rollback.");
eventType = ApplicationEvents.APPLICATION_ROLLBACK;
} else {
eventType = ApplicationEvents.APPLICATION_DEPLOYED;
}
return eventType;
}
public void setAfterRollback(boolean afterRollback) {
this.afterRollback = afterRollback;
}
@Override
public void doStop() {
//nothing
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\ApplicationDeployedEventProducer.java | 1 |
请完成以下Java代码 | public void onBeforeSave_assertTrlColumnExists(final I_AD_Column adColumn)
{
if (!adColumn.isTranslated())
{
return;
}
if (!DisplayType.isText(adColumn.getAD_Reference_ID()))
{
throw new AdempiereException("Only text columns are translatable");
}
if (tableDAO.isVirtualColumn(adColumn))
{
throw new AdempiereException("Virtual columns are not translatable");
}
final String tableName = getTableName(adColumn);
final String trlTableName = POTrlRepository.toTrlTableName(tableName);
final String columnName = adColumn.getColumnName();
if (!DB.isDBColumnPresent(trlTableName, columnName))
{
throw new AdempiereException("Before marking the column as translatable make sure " + trlTableName + "." + columnName + " exists."
+ "\n If not, please manually create the table and/or column.");
}
}
private String getTableName(final I_AD_Column adColumn)
{
return tableDAO.retrieveTableName(AdTableId.ofRepoId(adColumn.getAD_Table_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_AD_Column.COLUMNNAME_ColumnName, I_AD_Column.COLUMNNAME_AD_Reference_ID })
public void onBeforeSave_assertColumnNameValid(final I_AD_Column adColumn)
{
assertColumnNameValid(adColumn.getColumnName(), adColumn.getAD_Reference_ID());
}
private void assertColumnNameValid(@NonNull final String columnName, final int displayType)
{
if (DisplayType.isID(displayType) && displayType != DisplayType.Account)
{
if (!columnName.endsWith("_ID")
&& !columnName.equals("CreatedBy")
&& !columnName.equals("UpdatedBy") | && !columnName.equals("AD_Language")
&& !columnName.equals("EntityType"))
{
throw new AdempiereException("Lookup or ID columns shall have the name ending with `_ID`");
}
if (displayType == DisplayType.Locator && !columnName.contains("Locator"))
{
throw new AdempiereException("A Locator column name must contain the term `Locator`.");
}
}
else if (displayType == DisplayType.Account)
{
if (!columnName.endsWith("_Acct"))
{
throw new AdempiereException("Account columns shall have the name ending with `_Acct`");
}
}
else
{
if (columnName.endsWith("_ID") && displayType != DisplayType.Button)
{
throw new AdempiereException("Ending a non lookup column with `_ID` might be misleading");
}
if (columnName.endsWith("_Acct"))
{
throw new AdempiereException("Ending a non Account column with `_Acct` might be misleading");
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\model\interceptor\AD_Column.java | 1 |
请完成以下Java代码 | public String getComputerName() {
return computerName;
}
public void setComputerName(String computerName) {
this.computerName = computerName;
}
public String getComputerIp() {
return computerIp;
}
public void setComputerIp(String computerIp) {
this.computerIp = computerIp;
}
public String getUserDir() {
return userDir;
}
public void setUserDir(String userDir) {
this.userDir = userDir;
} | public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public String getOsArch() {
return osArch;
}
public void setOsArch(String osArch) {
this.osArch = osArch;
}
} | repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Sys.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
HashMap<String, Object> state = new HashMap<>();
state.put("processDefinitionId", processDefinitionId);
state.put("processDefinitionKey", processDefinitionKey);
state.put("activityId", activityId);
state.put("jobType", jobType);
state.put("jobConfiguration", jobConfiguration);
state.put("suspensionState", suspensionState);
state.put("jobPriority", jobPriority);
state.put("tenantId", tenantId);
state.put("deploymentId", deploymentId);
return state;
}
// getters / setters /////////////////////////////////
public int getRevisionNext() {
return revision + 1;
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public boolean isSuspended() {
return SuspensionState.SUSPENDED.getStateCode() == suspensionState;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
@Override
public String getJobConfiguration() {
return jobConfiguration;
}
public void setJobConfiguration(String jobConfiguration) {
this.jobConfiguration = jobConfiguration;
}
@Override
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public int getSuspensionState() {
return suspensionState; | }
public void setSuspensionState(int state) {
this.suspensionState = state;
}
public Long getOverridingJobPriority() {
return jobPriority;
}
public void setJobPriority(Long jobPriority) {
this.jobPriority = jobPriority;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
return referenceIdAndClass;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionEntity.java | 1 |
请完成以下Java代码 | public Criteria andMenuIdIn(List<Long> values) {
addCriterion("menu_id in", values, "menuId");
return (Criteria) this;
}
public Criteria andMenuIdNotIn(List<Long> values) {
addCriterion("menu_id not in", values, "menuId");
return (Criteria) this;
}
public Criteria andMenuIdBetween(Long value1, Long value2) {
addCriterion("menu_id between", value1, value2, "menuId");
return (Criteria) this;
}
public Criteria andMenuIdNotBetween(Long value1, Long value2) {
addCriterion("menu_id not between", value1, value2, "menuId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue; | }
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRoleMenuRelationExample.java | 1 |
请完成以下Java代码 | public class GroupQueryDto extends AbstractQueryDto<GroupQuery> {
private static final String SORT_BY_GROUP_ID_VALUE = "id";
private static final String SORT_BY_GROUP_NAME_VALUE = "name";
private static final String SORT_BY_GROUP_TYPE_VALUE = "type";
private static final List<String> VALID_SORT_BY_VALUES;
static {
VALID_SORT_BY_VALUES = new ArrayList<String>();
VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_ID_VALUE);
VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_NAME_VALUE);
VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_TYPE_VALUE);
}
protected String id;
protected String[] ids;
protected String name;
protected String nameLike;
protected String type;
protected String member;
protected String tenantId;
public GroupQueryDto() {
}
public GroupQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) {
super(objectMapper, queryParameters);
}
@CamundaQueryParam("id")
public void setId(String groupId) {
this.id = groupId;
}
@CamundaQueryParam(value = "idIn", converter = StringArrayConverter.class)
public void setIdIn(String[] groupIds) {
this.ids = groupIds;
}
@CamundaQueryParam("name")
public void setName(String groupName) {
this.name = groupName;
}
@CamundaQueryParam("nameLike")
public void setNameLike(String groupNameLike) {
this.nameLike = groupNameLike;
}
@CamundaQueryParam("type")
public void setType(String groupType) {
this.type = groupType;
}
@CamundaQueryParam("member")
public void setMember(String member) {
this.member = member; | }
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected GroupQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createGroupQuery();
}
@Override
protected void applyFilters(GroupQuery query) {
if (id != null) {
query.groupId(id);
}
if (ids != null) {
query.groupIdIn(ids);
}
if (name != null) {
query.groupName(name);
}
if (nameLike != null) {
query.groupNameLike(nameLike);
}
if (type != null) {
query.groupType(type);
}
if (member != null) {
query.groupMember(member);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) {
query.orderByGroupId();
} else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) {
query.orderByGroupName();
} else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) {
query.orderByGroupType();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java | 1 |
请完成以下Java代码 | public boolean isXYPosition ()
{
Object oo = get_Value(COLUMNNAME_IsXYPosition);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), getName());
}
/** Set XY Separator.
@param XYSeparator
The separator between the X and Y function.
*/
public void setXYSeparator (String XYSeparator)
{
set_Value (COLUMNNAME_XYSeparator, XYSeparator);
}
/** Get XY Separator.
@return The separator between the X and Y function.
*/
public String getXYSeparator ()
{
return (String)get_Value(COLUMNNAME_XYSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java | 1 |
请完成以下Java代码 | public void setCountEnqueued (final int CountEnqueued)
{
set_ValueNoCheck (COLUMNNAME_CountEnqueued, CountEnqueued);
}
@Override
public int getCountEnqueued()
{
return get_ValueAsInt(COLUMNNAME_CountEnqueued);
}
@Override
public void setCountProcessed (final int CountProcessed)
{
set_ValueNoCheck (COLUMNNAME_CountProcessed, CountProcessed);
}
@Override
public int getCountProcessed()
{
return get_ValueAsInt(COLUMNNAME_CountProcessed);
}
@Override
public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class);
}
@Override
public void setC_Queue_PackageProcessor(final de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor)
{
set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor);
} | @Override
public void setC_Queue_PackageProcessor_ID (final int C_Queue_PackageProcessor_ID)
{
if (C_Queue_PackageProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, C_Queue_PackageProcessor_ID);
}
@Override
public int getC_Queue_PackageProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_PackageProcessor_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_RV_Async_batch_statistics.java | 1 |
请完成以下Java代码 | public java.lang.String getQuoteType ()
{
return (java.lang.String)get_Value(COLUMNNAME_QuoteType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID) | {
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQ_UnAnswered.java | 1 |
请完成以下Java代码 | final class WebSocketCodecDelegate {
private static final ResolvableType MESSAGE_TYPE = ResolvableType.forClass(GraphQlWebSocketMessage.class);
private final Decoder<?> decoder;
private final Encoder<?> encoder;
private boolean messagesEncoded;
WebSocketCodecDelegate(CodecConfigurer codecConfigurer) {
Assert.notNull(codecConfigurer, "CodecConfigurer is required");
this.decoder = findJsonDecoder(codecConfigurer);
this.encoder = findJsonEncoder(codecConfigurer);
}
private static Decoder<?> findJsonDecoder(CodecConfigurer configurer) {
return configurer.getReaders().stream()
.filter((reader) -> reader.canRead(MESSAGE_TYPE, MediaType.APPLICATION_JSON))
.map((reader) -> ((DecoderHttpMessageReader<?>) reader).getDecoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Decoder"));
}
private static Encoder<?> findJsonEncoder(CodecConfigurer configurer) {
return configurer.getWriters().stream()
.filter((writer) -> writer.canWrite(MESSAGE_TYPE, MediaType.APPLICATION_JSON))
.map((writer) -> ((EncoderHttpMessageWriter<?>) writer).getEncoder())
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Encoder"));
}
@SuppressWarnings("unchecked")
<T> WebSocketMessage encode(WebSocketSession session, GraphQlWebSocketMessage message) {
DataBuffer buffer = ((Encoder<T>) this.encoder).encodeValue(
(T) message, session.bufferFactory(), MESSAGE_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
this.messagesEncoded = true;
return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer);
}
@SuppressWarnings("ConstantConditions")
@Nullable GraphQlWebSocketMessage decode(WebSocketMessage webSocketMessage) {
DataBuffer buffer = DataBufferUtils.retain(webSocketMessage.getPayload());
return (GraphQlWebSocketMessage) this.decoder.decode(buffer, MESSAGE_TYPE, null, null);
} | WebSocketMessage encodeConnectionAck(WebSocketSession session, Object ackPayload) {
return encode(session, GraphQlWebSocketMessage.connectionAck(ackPayload));
}
WebSocketMessage encodeNext(WebSocketSession session, String id, Map<String, Object> responseMap) {
return encode(session, GraphQlWebSocketMessage.next(id, responseMap));
}
WebSocketMessage encodeError(WebSocketSession session, String id, List<GraphQLError> errors) {
return encode(session, GraphQlWebSocketMessage.error(id, errors));
}
WebSocketMessage encodeComplete(WebSocketSession session, String id) {
return encode(session, GraphQlWebSocketMessage.complete(id));
}
boolean checkMessagesEncodedAndClear() {
boolean result = this.messagesEncoded;
this.messagesEncoded = false;
return result;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\WebSocketCodecDelegate.java | 1 |
请完成以下Java代码 | public class FoldingHash {
/**
* Calculate the hash value of a given string.
*
* @param str Assume it is not null
* @param groupSize the group size in the folding technique
* @param maxValue defines a max value that the hash may acquire (exclusive)
* @return integer value from 0 (inclusive) to maxValue (exclusive)
*/
public int hash(String str, int groupSize, int maxValue) {
final int[] codes = this.toAsciiCodes(str);
return IntStream.range(0, str.length())
.filter(i -> i % groupSize == 0)
.mapToObj(i -> extract(codes, i, groupSize))
.map(block -> concatenate(block))
.reduce(0, (a, b) -> (a + b) % maxValue);
}
/**
* Returns a new array of given length whose elements are take from
* the original one starting from the offset.
*
* If the original array has not enough elements, the returning array will contain
* element from the offset till the end of the original array.
*
* @param numbers original array. Assume it is not null.
* @param offset index of the element to start from. Assume it is less than the size of the array
* @param length max size of the resulting array
* @return
*/
public int[] extract(int[] numbers, int offset, int length) {
final int defect = numbers.length - (offset + length);
final int s = defect < 0 ? length + defect : length;
int[] result = new int[s];
for (int index = 0; index < s; index++) {
result[index] = numbers[index + offset];
}
return result; | }
/**
* Concatenate the numbers into a single number as if they were strings.
* Assume that the procedure does not suffer from the overflow.
* @param numbers integers to concatenate
* @return
*/
public int concatenate(int[] numbers) {
final String merged = IntStream.of(numbers)
.mapToObj(number -> "" + number)
.collect(Collectors.joining());
return Integer.parseInt(merged, 10);
}
/**
* Convert the string into its characters' ASCII codes.
* @param str input string
* @return
*/
private int[] toAsciiCodes(String str) {
return str.chars()
.toArray();
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\folding\FoldingHash.java | 1 |
请完成以下Java代码 | private String convert (int number)
{
if (number == 0)
return "zero";
String prefix = "";
if (number < 0)
{
number = -number;
prefix = "moins";
}
String soFar = "";
int place = 0;
boolean pluralPossible = true;
boolean pluralForm = false;
do
{
int n = number % 1000;
// par tranche de 1000
if (n != 0)
{
String s = convertLessThanOneThousand (n);
if (s.trim ().equals ("un") && place == 1)
{
// on donne pas le un pour mille
soFar = majorNames[place] + soFar;
}
else
{
if (place == 0)
{
if (s.trim ().endsWith ("cent")
&& !s.trim ().startsWith ("cent"))
{
// nnn200 ... nnn900 avec "s"
pluralForm = true;
}
else
{
// pas de "s" jamais
pluralPossible = false;
}
}
if (place > 0 && pluralPossible)
{
if (!s.trim ().startsWith ("un"))
{
// avec "s"
pluralForm = true;
}
else
{
// jamis de "s"
pluralPossible = false;
}
}
soFar = s + majorNames[place] + soFar;
}
}
place++;
number /= 1000;
}
while (number > 0);
String result = (prefix + soFar).trim ();
return (pluralForm ? result + "s" : result);
} // convert
/**************************************************************************
* Get Amount in Words
* @param amount numeric amount (352.80)
* @return amount in words (three*five*two 80/100)
* @throws Exception
*/
public String getAmtInWords (String amount) throws Exception
{
if (amount == null)
return amount; | //
StringBuffer sb = new StringBuffer ();
int pos = amount.lastIndexOf ('.');
int pos2 = amount.lastIndexOf (',');
if (pos2 > pos)
pos = pos2;
String oldamt = amount;
amount = amount.replaceAll (",", "");
String amttobetranslate = amount.substring (0, (pos));
// Here we clean unexpected space in the amount
String finalamount = new String();
char[] mychararray = amttobetranslate.toCharArray();
for (int i = 0; i < amttobetranslate.length (); i++)
{
if ( !Character.isSpaceChar(mychararray[i]))
{
finalamount = finalamount.concat(String.valueOf(mychararray[i]));
}
}
int pesos = Integer.parseInt (finalamount);
sb.append (convert (pesos));
for (int i = 0; i < oldamt.length (); i++)
{
if (pos == i) // we are done
{
String cents = oldamt.substring (i + 1);
sb.append (' ').append (cents).append ("/100");
break;
}
}
return sb.toString ();
} // getAmtInWords
} // AmtInWords_FR | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_FR.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HFINI1 getHFINI1() {
return hfini1;
}
/**
* Sets the value of the hfini1 property.
*
* @param value
* allowed object is
* {@link HFINI1 }
*
*/
public void setHFINI1(HFINI1 value) {
this.hfini1 = value;
}
/**
* Gets the value of the hrfad1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the hrfad1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getHRFAD1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link HRFAD1 }
*
*
*/
public List<HRFAD1> getHRFAD1() {
if (hrfad1 == null) {
hrfad1 = new ArrayList<HRFAD1>();
} | return this.hrfad1;
}
/**
* Gets the value of the hctad1 property.
*
* @return
* possible object is
* {@link HCTAD1 }
*
*/
public HCTAD1 getHCTAD1() {
return hctad1;
}
/**
* Sets the value of the hctad1 property.
*
* @param value
* allowed object is
* {@link HCTAD1 }
*
*/
public void setHCTAD1(HCTAD1 value) {
this.hctad1 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\HADRE1.java | 2 |
请完成以下Java代码 | public class DeployDto extends BaseDTO implements Serializable {
@ApiModelProperty(value = "ID")
private String id;
@ApiModelProperty(value = "应用")
private AppDto app;
@ApiModelProperty(value = "服务器")
private Set<ServerDeployDto> deploys;
@ApiModelProperty(value = "服务器名称")
private String servers;
@ApiModelProperty(value = "服务状态")
private String status;
public String getServers() {
if(CollectionUtil.isNotEmpty(deploys)){
return deploys.stream().map(ServerDeployDto::getName).collect(Collectors.joining(","));
}
return servers; | }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeployDto deployDto = (DeployDto) o;
return Objects.equals(id, deployDto.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\dto\DeployDto.java | 1 |
请完成以下Java代码 | public void setIsCollapsible (boolean IsCollapsible)
{
set_Value (COLUMNNAME_IsCollapsible, Boolean.valueOf(IsCollapsible));
}
/** Get Collapsible.
@return Flag to indicate the state of the dashboard panel
*/
public boolean isCollapsible ()
{
Object oo = get_Value(COLUMNNAME_IsCollapsible);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Line No.
@param Line
Unique line for this document
*/
public void setLine (BigDecimal Line)
{
set_Value (COLUMNNAME_Line, Line);
}
/** Get Line No.
@return Unique line for this document
*/
public BigDecimal getLine ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Line);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
} | /** Set PA_DashboardContent_ID.
@param PA_DashboardContent_ID PA_DashboardContent_ID */
public void setPA_DashboardContent_ID (int PA_DashboardContent_ID)
{
if (PA_DashboardContent_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID));
}
/** Get PA_DashboardContent_ID.
@return PA_DashboardContent_ID */
public int getPA_DashboardContent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Goal getPA_Goal() throws RuntimeException
{
return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name)
.getPO(getPA_Goal_ID(), get_TrxName()); }
/** Set Goal.
@param PA_Goal_ID
Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null);
else
set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set ZUL File Path.
@param ZulFilePath
Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath)
{
set_Value (COLUMNNAME_ZulFilePath, ZulFilePath);
}
/** Get ZUL File Path.
@return Absolute path to zul file
*/
public String getZulFilePath ()
{
return (String)get_Value(COLUMNNAME_ZulFilePath);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java | 1 |
请完成以下Java代码 | protected void updateStaticData() {
InternalsImpl internals = staticData.getProduct().getInternals();
if (internals.getApplicationServer() == null) {
ApplicationServerImpl applicationServer = diagnosticsRegistry.getApplicationServer();
internals.setApplicationServer(applicationServer);
}
// license key and Webapps data is fed from the outside to the registry but needs to be constantly updated
internals.setLicenseKey(diagnosticsRegistry.getLicenseKey());
internals.setWebapps(diagnosticsRegistry.getWebapps());
}
protected InternalsImpl resolveDynamicData() {
InternalsImpl result = new InternalsImpl();
Map<String, Metric> metrics = calculateMetrics();
result.setMetrics(metrics);
// command counts are modified after the metrics are retrieved, because
// metric retrieval can fail and resetting the command count is a side effect
// that we would otherwise have to undo
Map<String, Command> commands = fetchAndResetCommandCounts();
result.setCommands(commands);
return result;
}
protected Map<String, Command> fetchAndResetCommandCounts() {
Map<String, Command> commandsToReport = new HashMap<>();
Map<String, CommandCounter> originalCounts = diagnosticsRegistry.getCommands();
synchronized (originalCounts) {
for (Map.Entry<String, CommandCounter> counter : originalCounts.entrySet()) {
long occurrences = counter.getValue().get();
commandsToReport.put(counter.getKey(), new CommandImpl(occurrences));
}
}
return commandsToReport; | }
protected Map<String, Metric> calculateMetrics() {
Map<String, Metric> metrics = new HashMap<>();
if (metricsRegistry != null) {
Map<String, Meter> telemetryMeters = metricsRegistry.getDiagnosticsMeters();
for (String metricToReport : METRICS_TO_REPORT) {
long value = telemetryMeters.get(metricToReport).get();
// add public names
metrics.put(MetricsUtil.resolvePublicName(metricToReport), new MetricImpl(value));
}
}
return metrics;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsCollector.java | 1 |
请完成以下Java代码 | public final void setObject(final int parameterIndex, final Object x, final int targetSqlType, final int scaleOrLength) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
@Override
public final void setAsciiStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x, length);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x, length);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader, length);
}
@Override
public final void setAsciiStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader);
}
@Override
public final void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, value); | getStatementImpl().setNCharacterStream(parameterIndex, value);
}
@Override
public final void setClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setClob(parameterIndex, reader);
}
@Override
public final void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, inputStream);
getStatementImpl().setBlob(parameterIndex, inputStream);
}
@Override
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setNClob(parameterIndex, reader);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CPreparedStatementProxy.java | 1 |
请完成以下Java代码 | public class CmsHelpCategory implements Serializable {
private Long id;
private String name;
@ApiModelProperty(value = "分类图标")
private String icon;
@ApiModelProperty(value = "专题数量")
private Integer helpCount;
private Integer showStatus;
private Integer sort;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getHelpCount() {
return helpCount;
}
public void setHelpCount(Integer helpCount) {
this.helpCount = helpCount;
} | public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", helpCount=").append(helpCount);
sb.append(", showStatus=").append(showStatus);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpCategory.java | 1 |
请完成以下Java代码 | public class AclPermissionCacheOptimizer implements PermissionCacheOptimizer {
private final Log logger = LogFactory.getLog(getClass());
private final AclService aclService;
private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
private ObjectIdentityRetrievalStrategy oidRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
public AclPermissionCacheOptimizer(AclService aclService) {
this.aclService = aclService;
}
@Override
public void cachePermissionsFor(Authentication authentication, Collection<?> objects) {
if (objects.isEmpty()) {
return;
}
List<ObjectIdentity> oidsToCache = new ArrayList<>(objects.size()); | for (Object domainObject : objects) {
if (domainObject != null) {
ObjectIdentity oid = this.oidRetrievalStrategy.getObjectIdentity(domainObject);
oidsToCache.add(oid);
}
}
List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
this.logger.debug(LogMessage.of(() -> "Eagerly loading Acls for " + oidsToCache.size() + " objects"));
this.aclService.readAclsById(oidsToCache, sids);
}
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) {
this.oidRetrievalStrategy = objectIdentityRetrievalStrategy;
}
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) {
this.sidRetrievalStrategy = sidRetrievalStrategy;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\AclPermissionCacheOptimizer.java | 1 |
请完成以下Java代码 | private CacheInvalidationGroup getCacheInvalidationGroupByTableName(final String tableName)
{
return cacheInvalidationGroupsByTableName.computeIfAbsent(tableName, CacheInvalidationGroup::new);
}
public void cacheInvalidateOnRecordsChanged(final Set<String> tableNames)
{
tableNames.stream()
.map(cacheInvalidationGroupsByTableName::get)
.filter(Objects::nonNull)
.forEach(CacheInvalidationGroup::cacheInvalidate);
}
public List<CCacheStats> getCacheStats()
{
return lookupDataSourcesCache
.values()
.stream()
.flatMap(dataSource -> dataSource.getCacheStats().stream())
.distinct()
.sorted(Comparator.comparing(CCacheStats::getName))
.collect(GuavaCollectors.toImmutableList());
}
@ToString(exclude = "lookupDataSources")
private static final class CacheInvalidationGroup
{
private final String tableName;
private final List<WeakReference<LookupDataSource>> lookupDataSources = new ArrayList<>();
public CacheInvalidationGroup(final String tableName)
{
this.tableName = tableName;
}
public void addLookupDataSource(@NonNull final LookupDataSource lookupDataSource)
{
synchronized (lookupDataSources)
{
lookupDataSources.add(new WeakReference<>(lookupDataSource));
}
} | private List<LookupDataSource> purgeAndGet()
{
synchronized (lookupDataSources)
{
final List<LookupDataSource> result = new ArrayList<>(lookupDataSources.size());
for (final Iterator<WeakReference<LookupDataSource>> it = lookupDataSources.iterator(); it.hasNext(); )
{
final LookupDataSource lookupDataSource = it.next().get();
if (lookupDataSource == null)
{
it.remove();
continue;
}
result.add(lookupDataSource);
}
return result;
}
}
public void cacheInvalidate()
{
for (final LookupDataSource lookupDataSource : purgeAndGet())
{
try
{
lookupDataSource.cacheInvalidate();
logger.debug("Cache invalidated {} on {} record changed", lookupDataSource, tableName);
}
catch (final Exception ex)
{
logger.warn("Failed invalidating {}. Skipped", lookupDataSource, ex);
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceFactory.java | 1 |
请完成以下Java代码 | public class CookieList {
/**
* Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated from the values by '='. The pairs are separated by ';'. The names and the values
* will be unescaped, possibly converting '+' and '%' sequences.
*
* To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), cookieJSONObject.getString("value"));
*
* @param string
* A cookie list string
* @return A JSONObject
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
JSONTokener x = new JSONTokener(string);
while (x.more()) {
String name = Cookie.unescape(x.nextTo('='));
x.next('=');
o.put(name, Cookie.unescape(x.nextTo(';')));
x.next();
}
return o;
}
/**
* Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated from the values by '='. The pairs are separated by ';'. The characters '%', '+',
* '=', and ';' in the names and values are replaced by "%hh".
*
* @param o
* A JSONObject
* @return A cookie list string
* @throws JSONException | */
@SuppressWarnings("unchecked")
public static String toString(JSONObject o) throws JSONException {
boolean b = false;
Iterator keys = o.keys();
String s;
StringBuilder sb = new StringBuilder();
while (keys.hasNext()) {
s = keys.next().toString();
if (!o.isNull(s)) {
if (b) {
sb.append(';');
}
sb.append(Cookie.escape(s));
sb.append("=");
sb.append(Cookie.escape(o.getString(s)));
b = true;
}
}
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\CookieList.java | 1 |
请完成以下Java代码 | public static PPOrderRoutingActivityId ofRepoId(@NonNull final PPOrderId orderId, final int repoId)
{
return new PPOrderRoutingActivityId(orderId, repoId);
}
public static PPOrderRoutingActivityId ofRepoId(@NonNull final PPOrderId orderId, @NonNull final String repoIdString)
{
try
{
return new PPOrderRoutingActivityId(orderId, NumberUtils.asInt(repoIdString));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid PPOrderRoutingActivityId for " + orderId + ", `" + repoIdString + "`", ex);
}
}
@Nullable
public static PPOrderRoutingActivityId ofRepoIdOrNull(@NonNull final PPOrderId orderId, final int repoId)
{
return repoId > 0 ? new PPOrderRoutingActivityId(orderId, repoId) : null;
}
public static int toRepoId(@Nullable final PPOrderRoutingActivityId id)
{
return id != null ? id.getRepoId() : -1;
}
PPOrderId orderId; | int repoId;
private PPOrderRoutingActivityId(@NonNull final PPOrderId orderId, final int repoId)
{
this.orderId = orderId;
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Node_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final PPOrderRoutingActivityId id1, @Nullable final PPOrderRoutingActivityId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingActivityId.java | 1 |
请完成以下Java代码 | public class AgreementMethodType {
@XmlElementRefs({
@XmlElementRef(name = "KA-Nonce", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false),
@XmlElementRef(name = "OriginatorKeyInfo", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false),
@XmlElementRef(name = "RecipientKeyInfo", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false)
})
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute(name = "Algorithm", required = true)
@XmlSchemaType(name = "anyURI")
protected String algorithm;
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link byte[]}{@code >}
* {@link JAXBElement }{@code <}{@link KeyInfoType }{@code >}
* {@link JAXBElement }{@code <}{@link KeyInfoType }{@code >}
* {@link Object }
* {@link String }
*
*
*/
public List<Object> getContent() { | if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the algorithm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Sets the value of the algorithm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlgorithm(String value) {
this.algorithm = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\AgreementMethodType.java | 1 |
请完成以下Java代码 | public static PPOrderLineRowId fromDocumentId(final DocumentId documentId)
{
final List<String> parts = PARTS_SPLITTER.splitToList(documentId.toJson());
return fromStringPartsList(parts);
}
private static PPOrderLineRowId fromStringPartsList(final List<String> parts)
{
final int partsCount = parts.size();
if (partsCount < 1)
{
throw new IllegalArgumentException("Invalid id: " + parts);
}
final PPOrderLineRowType type = PPOrderLineRowType.forCode(parts.get(0));
final DocumentId parentRowId = !Check.isEmpty(parts.get(1), true) ? DocumentId.of(parts.get(1)) : null;
final int recordId = Integer.parseInt(parts.get(2));
return new PPOrderLineRowId(type, parentRowId, recordId);
}
public static PPOrderLineRowId ofPPOrderBomLineId(int ppOrderBomLineId)
{
Preconditions.checkArgument(ppOrderBomLineId > 0, "ppOrderBomLineId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_OrderBomLine, null, ppOrderBomLineId);
}
public static PPOrderLineRowId ofPPOrderId(int ppOrderId)
{
Preconditions.checkArgument(ppOrderId > 0, "ppOrderId > 0");
return new PPOrderLineRowId(PPOrderLineRowType.PP_Order, null, ppOrderId);
} | public static PPOrderLineRowId ofIssuedOrReceivedHU(@Nullable DocumentId parentRowId, @NonNull final HuId huId)
{
return new PPOrderLineRowId(PPOrderLineRowType.IssuedOrReceivedHU, parentRowId, huId.getRepoId());
}
public static PPOrderLineRowId ofSourceHU(@NonNull DocumentId parentRowId, @NonNull final HuId sourceHuId)
{
return new PPOrderLineRowId(PPOrderLineRowType.Source_HU, parentRowId, sourceHuId.getRepoId());
}
public Optional<PPOrderBOMLineId> getPPOrderBOMLineIdIfApplies()
{
return type.isPP_OrderBomLine() ? PPOrderBOMLineId.optionalOfRepoId(recordId) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRowId.java | 1 |
请完成以下Java代码 | public void setTutId(String tutId) {
this.tutId = tutId;
}
public String getType() {
return type;
}
@XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description; | }
@XmlElement
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
@XmlElement
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
@XmlElement
public void setAuthor(String author) {
this.author = author;
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\binding\Tutorial.java | 1 |
请完成以下Java代码 | private void switchState(TbContext ctx, EntityId entityId, EntityGeofencingState entityState, boolean matches, long ts) {
entityState.setInside(matches);
entityState.setStateSwitchTime(ts);
entityState.setStayed(false);
persist(ctx, entityId, entityState);
}
private void setStaid(TbContext ctx, EntityId entityId, EntityGeofencingState entityState) {
entityState.setStayed(true);
persist(ctx, entityId, entityState);
}
private void persist(TbContext ctx, EntityId entityId, EntityGeofencingState entityState) {
JsonObject object = new JsonObject();
object.addProperty("inside", entityState.isInside());
object.addProperty("stateSwitchTime", entityState.getStateSwitchTime());
object.addProperty("stayed", entityState.isStayed());
AttributeKvEntry entry = new BaseAttributeKvEntry(new StringDataEntry(ctx.getServiceId(), gson.toJson(object)), System.currentTimeMillis());
List<AttributeKvEntry> attributeKvEntryList = Collections.singletonList(entry);
ctx.getAttributesService().save(ctx.getTenantId(), entityId, AttributeScope.SERVER_SCOPE, attributeKvEntryList);
} | @Override
protected Class<TbGpsGeofencingActionNodeConfiguration> getConfigClazz() {
return TbGpsGeofencingActionNodeConfiguration.class;
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
if (fromVersion == 0) {
if (!oldConfiguration.has(REPORT_PRESENCE_STATUS_ON_EACH_MESSAGE)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(REPORT_PRESENCE_STATUS_ON_EACH_MESSAGE, false);
}
}
return new TbPair<>(hasChanges, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\geo\TbGpsGeofencingActionNode.java | 1 |
请完成以下Java代码 | private DeviceProfileInfo toDeviceProfileInfo(DeviceProfile profile) {
return profile == null ? null : new DeviceProfileInfo(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(),
profile.getDefaultDashboardId(), profile.getType(), profile.getTransportType());
}
private void formatDeviceProfileCertificate(DeviceProfile deviceProfile, X509CertificateChainProvisionConfiguration x509Configuration) {
String formattedCertificateValue = formatCertificateValue(x509Configuration.getProvisionDeviceSecret());
String cert = fetchLeafCertificateFromChain(formattedCertificateValue);
String sha3Hash = EncryptionUtil.getSha3Hash(cert);
DeviceProfileData deviceProfileData = deviceProfile.getProfileData();
x509Configuration.setProvisionDeviceSecret(formattedCertificateValue);
deviceProfileData.setProvisionConfiguration(x509Configuration);
deviceProfile.setProfileData(deviceProfileData);
deviceProfile.setProvisionDeviceKey(sha3Hash);
}
private String fetchLeafCertificateFromChain(String value) {
String regex = "-----BEGIN CERTIFICATE-----\\s*.*?\\s*-----END CERTIFICATE-----";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
// if the method receives a chain it fetches the leaf (end-entity) certificate, else if it gets a single certificate, it returns the single certificate
return matcher.group(0);
} | return value;
}
private String formatCertificateValue(String certificateValue) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream inputStream = new ByteArrayInputStream(certificateValue.getBytes());
Certificate[] certificates = cf.generateCertificates(inputStream).toArray(new Certificate[0]);
if (certificates.length > 1) {
return EncryptionUtil.certTrimNewLinesForChainInDeviceProfile(certificateValue);
}
} catch (CertificateException ignored) {}
return EncryptionUtil.certTrimNewLines(certificateValue);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\device\DeviceProfileServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderLineData
{
@Nullable String description;
int productBomLineId;
/**
* Specifies whether this line is about a receipt (co-product or by-product) or about an issue.
*/
boolean receipt;
@NonNull Instant issueOrReceiveDate;
@NonNull ProductDescriptor productDescriptor;
@Nullable MinMaxDescriptor minMaxDescriptor;
/**
* qty in stocking UOM
*/
@NonNull BigDecimal qtyRequired;
/**
* qty in stocking UOM
*/
@NonNull BigDecimal qtyDelivered;
@JsonCreator
@Builder(toBuilder = true)
public PPOrderLineData(
@JsonProperty("description") @Nullable final String description,
@JsonProperty("productBomLineId") final int productBomLineId,
@JsonProperty("receipt") @NonNull final Boolean receipt,
@JsonProperty("issueOrReceiveDate") @NonNull final Instant issueOrReceiveDate,
@JsonProperty("productDescriptor") @NonNull final ProductDescriptor productDescriptor, | @JsonProperty("minMaxDescriptor") @Nullable final MinMaxDescriptor minMaxDescriptor,
@JsonProperty("qtyRequired") @NonNull final BigDecimal qtyRequired,
@JsonProperty("qtyDelivered") @Nullable final BigDecimal qtyDelivered)
{
this.description = description;
// don't assert that the ID is greater that zero, because this might not be the case with "handmade" PPOrders
this.productBomLineId = productBomLineId;
this.receipt = receipt;
this.issueOrReceiveDate = issueOrReceiveDate;
this.productDescriptor = productDescriptor;
this.minMaxDescriptor = minMaxDescriptor;
this.qtyRequired = qtyRequired;
this.qtyDelivered = CoalesceUtil.coalesceNotNull(qtyDelivered, BigDecimal.ZERO);
}
public BigDecimal getQtyOpen()
{
return getQtyRequired().subtract(getQtyDelivered());
}
public BigDecimal getQtyOpenNegateIfReceipt()
{
if (isReceipt())
{
return getQtyOpen().negate();
}
else
{
return getQtyOpen();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderLineData.java | 2 |
请完成以下Java代码 | public void setC_Order(final org.compiere.model.I_C_Order C_Order)
{
set_ValueFromPO(COLUMNNAME_C_Order_ID, org.compiere.model.I_C_Order.class, C_Order);
}
@Override
public void setC_Order_ID (final int C_Order_ID)
{
if (C_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Order_ID, C_Order_ID);
}
@Override
public int getC_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_ID);
}
@Override
public void setC_OrderLine_Detail_ID (final int C_OrderLine_Detail_ID)
{
if (C_OrderLine_Detail_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_Detail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_Detail_ID, C_OrderLine_Detail_ID);
}
@Override
public int getC_OrderLine_Detail_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_Detail_ID);
}
@Override
public org.compiere.model.I_C_OrderLine getC_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class);
}
@Override
public void setC_OrderLine(final org.compiere.model.I_C_OrderLine C_OrderLine)
{
set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{ | return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderLine_Detail.java | 1 |
请完成以下Java代码 | public Map<String, Object> getReturnVarMap() {
return returnVarMap;
}
public void setReturnVarMap(Map<String, Object> returnVarMap) {
this.returnVarMap = returnVarMap;
}
public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName;
}
public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName;
} | @Override
public boolean isLenientProperties() {
return true;
}
public long getTimeout() {
return timeout;
}
public int getTimeResolution() {
return timeResolution;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java | 1 |
请完成以下Java代码 | public Long getPersonNumber() {
return personNumber;
}
public void setPersonNumber(Long personNumber) {
this.personNumber = personNumber;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public String getScode() {
return securityNumber;
}
public void setScode(String scode) { | this.securityNumber = scode;
}
public String getDcode() {
return departmentCode;
}
public void setDcode(String dcode) {
this.departmentCode = dcode;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\uniqueconstraints\Person.java | 1 |
请完成以下Java代码 | public boolean isAsynchronous() {
return asynchronous;
}
public void setAsynchronous(boolean asynchronous) {
this.asynchronous = asynchronous;
}
public boolean isAsynchronousLeave() {
return asynchronousLeave;
}
public void setAsynchronousLeave(boolean asynchronousLeave) {
this.asynchronousLeave = asynchronousLeave;
}
public boolean isExclusive() {
return !notExclusive;
}
public void setExclusive(boolean exclusive) {
this.notExclusive = !exclusive;
}
public boolean isNotExclusive() {
return notExclusive;
}
public void setNotExclusive(boolean notExclusive) {
this.notExclusive = notExclusive;
}
public boolean isAsynchronousLeaveExclusive() {
return !asynchronousLeaveNotExclusive;
}
public void setAsynchronousLeaveExclusive(boolean exclusive) {
this.asynchronousLeaveNotExclusive = !exclusive;
}
public boolean isAsynchronousLeaveNotExclusive() {
return asynchronousLeaveNotExclusive;
}
public void setAsynchronousLeaveNotExclusive(boolean asynchronousLeaveNotExclusive) {
this.asynchronousLeaveNotExclusive = asynchronousLeaveNotExclusive;
}
public Object getBehavior() {
return behavior;
}
public void setBehavior(Object behavior) {
this.behavior = behavior;
}
public List<SequenceFlow> getIncomingFlows() {
return incomingFlows;
} | public void setIncomingFlows(List<SequenceFlow> incomingFlows) {
this.incomingFlows = incomingFlows;
}
public List<SequenceFlow> getOutgoingFlows() {
return outgoingFlows;
}
public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) {
this.outgoingFlows = outgoingFlows;
}
public void setValues(FlowNode otherNode) {
super.setValues(otherNode);
setAsynchronous(otherNode.isAsynchronous());
setNotExclusive(otherNode.isNotExclusive());
setAsynchronousLeave(otherNode.isAsynchronousLeave());
setAsynchronousLeaveNotExclusive(otherNode.isAsynchronousLeaveNotExclusive());
if (otherNode.getIncomingFlows() != null) {
setIncomingFlows(otherNode.getIncomingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
if (otherNode.getOutgoingFlows() != null) {
setOutgoingFlows(otherNode.getOutgoingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowNode.java | 1 |
请完成以下Java代码 | public void startConsumer() {
executor.submit(() -> {
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093");
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "groupId");
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
// 请求超时时间
properties.setProperty(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, "60000");
Deserializer<String> keyDeserializer = new StringDeserializer();
Deserializer<String> valueDeserializer = new StringDeserializer();
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties, keyDeserializer, valueDeserializer);
consumer.subscribe(Arrays.asList("test_cluster_topic"));
// KafkaConsumer的assignment()方法来判定是否分配到了相应的分区,如果为空表示没有分配到分区
Set<TopicPartition> assignment = consumer.assignment();
while (assignment.isEmpty()) {
// 阻塞1秒
consumer.poll(1000);
assignment = consumer.assignment();
}
// KafkaConsumer 分配到了分区,开始消费
while (true) {
// 拉取记录,如果没有记录则柱塞1000ms。
ConsumerRecords<String, String> records = consumer.poll(1000);
for (ConsumerRecord<String, String> record : records) {
String traceId = new String(record.headers().lastHeader("traceId").value());
System.out.printf("traceId = %s, offset = %d, key = %s, value = %s%n", traceId, record.offset(), record.key(), record.value()); | }
// 异步确认提交
consumer.commitAsync((offsets, exception) -> {
if (Objects.isNull(exception)) {
// TODO 告警、落盘、重试
}
});
}
});
}
} | repos\spring-boot-student-master\spring-boot-student-kafka\src\main\java\com\xiaolyuh\consumer\KafkaConsumerDemo.java | 1 |
请完成以下Java代码 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isTrue(authentication instanceof BearerTokenAuthenticationToken,
"Authentication must be of type BearerTokenAuthenticationToken");
BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) authentication;
String issuer = this.issuerConverter.convert(token);
AuthenticationManager authenticationManager = this.issuerAuthenticationManagerResolver.resolve(issuer);
if (authenticationManager == null) {
AuthenticationException ex = new InvalidBearerTokenException("Invalid issuer");
ex.setAuthenticationRequest(authentication);
throw ex;
}
try {
return authenticationManager.authenticate(authentication);
}
catch (AuthenticationException ex) {
ex.setAuthenticationRequest(authentication);
throw ex;
}
}
}
private static class JwtClaimIssuerConverter implements Converter<BearerTokenAuthenticationToken, String> {
@Override
public String convert(@NonNull BearerTokenAuthenticationToken authentication) {
String token = authentication.getToken();
try {
String issuer = JWTParser.parse(token).getJWTClaimsSet().getIssuer();
if (issuer != null) {
return issuer;
}
}
catch (Exception cause) {
AuthenticationException ex = new InvalidBearerTokenException(cause.getMessage(), cause);
ex.setAuthenticationRequest(authentication);
throw ex;
}
AuthenticationException ex = new InvalidBearerTokenException("Missing issuer");
ex.setAuthenticationRequest(authentication);
throw ex;
}
}
static class TrustedIssuerJwtAuthenticationManagerResolver implements AuthenticationManagerResolver<String> { | private final Log logger = LogFactory.getLog(getClass());
private final Map<String, AuthenticationManager> authenticationManagers = new ConcurrentHashMap<>();
private final Predicate<String> trustedIssuer;
TrustedIssuerJwtAuthenticationManagerResolver(Predicate<String> trustedIssuer) {
this.trustedIssuer = trustedIssuer;
}
@Override
public AuthenticationManager resolve(String issuer) {
if (this.trustedIssuer.test(issuer)) {
AuthenticationManager authenticationManager = this.authenticationManagers.computeIfAbsent(issuer,
(k) -> {
this.logger.debug("Constructing AuthenticationManager");
JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(issuer);
return new JwtAuthenticationProvider(jwtDecoder)::authenticate;
});
this.logger.debug(LogMessage.format("Resolved AuthenticationManager for issuer '%s'", issuer));
return authenticationManager;
}
else {
this.logger.debug("Did not resolve AuthenticationManager since issuer is not trusted");
}
return null;
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerAuthenticationManagerResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataSource getNonJtaDataSource() {
return nonJtaDataSource;
}
public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonJtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
} | @Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java | 2 |
请完成以下Java代码 | public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRegistry (final @Nullable java.lang.String Registry)
{
set_Value (COLUMNNAME_Registry, Registry);
}
@Override
public java.lang.String getRegistry()
{
return get_ValueAsString(COLUMNNAME_Registry);
}
@Override
public void setSecretKey_2FA (final @Nullable java.lang.String SecretKey_2FA)
{
set_Value (COLUMNNAME_SecretKey_2FA, SecretKey_2FA);
}
@Override
public java.lang.String getSecretKey_2FA()
{
return get_ValueAsString(COLUMNNAME_SecretKey_2FA);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp)
{
throw new IllegalArgumentException ("Timestamp is virtual column"); }
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
} | @Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount)
{
set_Value (COLUMNNAME_UnlockAccount, UnlockAccount);
}
@Override
public java.lang.String getUnlockAccount()
{
return get_ValueAsString(COLUMNNAME_UnlockAccount);
}
@Override
public void setUserPIN (final @Nullable java.lang.String UserPIN)
{
set_Value (COLUMNNAME_UserPIN, UserPIN);
}
@Override
public java.lang.String getUserPIN()
{
return get_ValueAsString(COLUMNNAME_UserPIN);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java | 1 |
请完成以下Java代码 | public class GL_Journal
{
private final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class);
@CalloutMethod(columnNames = I_GL_Journal.COLUMNNAME_C_DocType_ID)
public void onC_DocType_ID(final I_GL_Journal glJournal)
{
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(getDocType(glJournal).orElse(null))
.setOldDocumentNo(glJournal.getDocumentNo())
.setDocumentModel(glJournal)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
glJournal.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
private Optional<I_C_DocType> getDocType(final I_GL_Journal glJournal)
{
return DocTypeId.optionalOfRepoId(glJournal.getC_DocType_ID())
.map(docTypeBL::getById);
}
@CalloutMethod(columnNames = I_GL_Journal.COLUMNNAME_DateDoc)
public void onDateDoc(final I_GL_Journal glJournal)
{
final Timestamp dateDoc = glJournal.getDateDoc();
if (dateDoc == null)
{
return;
}
glJournal.setDateAcct(dateDoc);
}
@CalloutMethod(columnNames = {
I_GL_Journal.COLUMNNAME_DateAcct,
I_GL_Journal.COLUMNNAME_C_Currency_ID,
I_GL_Journal.COLUMNNAME_C_ConversionType_ID })
public void updateCurrencyRate(final I_GL_Journal glJournal)
{
//
// Extract data from source Journal
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID());
if (currencyId == null)
{
// not set yet
return;
}
final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID());
final Instant dateAcct = glJournal.getDateAcct() != null ? glJournal.getDateAcct().toInstant() : SystemTime.asInstant();
final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID());
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(glJournal.getC_AcctSchema_ID());
final AcctSchema acctSchema = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId); | //
// Calculate currency rate
final BigDecimal currencyRate;
if (acctSchema != null)
{
currencyRate = Services.get(ICurrencyBL.class).getCurrencyRateIfExists(
currencyId,
acctSchema.getCurrencyId(),
dateAcct,
conversionTypeId,
adClientId,
adOrgId)
.map(CurrencyRate::getConversionRate)
.orElse(BigDecimal.ZERO);
}
else
{
currencyRate = BigDecimal.ONE;
}
//
glJournal.setCurrencyRate(currencyRate);
}
// Old/missing callouts
// "GL_Journal";"C_Period_ID";"org.compiere.model.CalloutGLJournal.period"
// "GL_Journal";"DateAcct";"org.compiere.model.CalloutGLJournal.period"
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_Journal.java | 1 |
请完成以下Java代码 | protected String resolveAccessExternalSchemaProperty() {
String systemProperty = System.getProperty(JAXP_ACCESS_EXTERNAL_SCHEMA_SYSTEM_PROPERTY);
if (systemProperty != null) {
return systemProperty;
} else {
return JAXP_ACCESS_EXTERNAL_SCHEMA_ALL;
}
}
public ModelInstance parseModelFromStream(InputStream inputStream) {
DomDocument document = null;
synchronized(documentBuilderFactory) {
document = DomUtil.parseInputStream(documentBuilderFactory, inputStream);
}
validateModel(document);
return createModelInstance(document);
}
public ModelInstance getEmptyModel() {
DomDocument document = null;
synchronized(documentBuilderFactory) {
document = DomUtil.getEmptyDocument(documentBuilderFactory);
}
return createModelInstance(document);
}
/**
* Validate DOM document
*
* @param document the DOM document to validate
*/
public void validateModel(DomDocument document) {
Schema schema = getSchema(document);
if (schema == null) {
return;
}
Validator validator = schema.newValidator(); | try {
synchronized(document) {
validator.validate(document.getDomSource());
}
} catch (IOException e) {
throw new ModelValidationException("Error during DOM document validation", e);
} catch (SAXException e) {
throw new ModelValidationException("DOM document is not valid", e);
}
}
protected Schema getSchema(DomDocument document) {
DomElement rootElement = document.getRootElement();
String namespaceURI = rootElement.getNamespaceURI();
return schemas.get(namespaceURI);
}
protected void addSchema(String namespaceURI, Schema schema) {
schemas.put(namespaceURI, schema);
}
protected Schema createSchema(String location, ClassLoader classLoader) {
URL cmmnSchema = ReflectUtil.getResource(location, classLoader);
try {
return schemaFactory.newSchema(cmmnSchema);
} catch (SAXException e) {
throw new ModelValidationException("Unable to parse schema:" + cmmnSchema);
}
}
protected abstract ModelInstance createModelInstance(DomDocument document);
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\parser\AbstractModelParser.java | 1 |
请完成以下Java代码 | public int[] allTags()
{
return allTags;
}
public void save(DataOutputStream out) throws IOException
{
out.writeInt(type.ordinal());
out.writeInt(size());
for (String tag : idStringMap)
{
out.writeUTF(tag);
}
}
@Override
public boolean load(ByteArray byteArray)
{
idStringMap.clear();
stringIdMap.clear();
int size = byteArray.nextInt();
for (int i = 0; i < size; i++)
{
String tag = byteArray.nextUTF();
idStringMap.add(tag);
stringIdMap.put(tag, i);
}
lock();
return true;
} | public void load(DataInputStream in) throws IOException
{
idStringMap.clear();
stringIdMap.clear();
int size = in.readInt();
for (int i = 0; i < size; i++)
{
String tag = in.readUTF();
idStringMap.add(tag);
stringIdMap.put(tag, i);
}
lock();
}
public Collection<String> tags()
{
return idStringMap;
}
public boolean contains(String tag)
{
return idStringMap.contains(tag);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\TagSet.java | 1 |
请完成以下Java代码 | public class WFProcessMapper
{
public static InventoryId toInventoryId(final WFProcessId wfProcessId)
{
return wfProcessId.getRepoIdAssumingApplicationId(InventoryMobileApplication.APPLICATION_ID, InventoryId::ofRepoId);
}
public static WFProcessId toWFProcessId(final InventoryId inventoryId)
{
return WFProcessId.ofIdPart(InventoryMobileApplication.APPLICATION_ID, inventoryId);
}
public static WFProcess toWFProcess(final Inventory inventory)
{
return WFProcess.builder()
.id(toWFProcessId(inventory.getId()))
.responsibleId(inventory.getResponsibleId()) | .document(inventory)
.activities(ImmutableList.of(
WFActivity.builder()
.id(WFActivityId.ofString("A1"))
.caption(TranslatableStrings.empty())
.wfActivityType(InventoryJobWFActivityHandler.HANDLED_ACTIVITY_TYPE)
.status(InventoryJobWFActivityHandler.computeActivityState(inventory))
.build(),
WFActivity.builder()
.id(WFActivityId.ofString("A2"))
.caption(TranslatableStrings.adRefList(IDocument.ACTION_AD_Reference_ID, IDocument.ACTION_Complete))
.wfActivityType(CompleteWFActivityHandler.HANDLED_ACTIVITY_TYPE)
.status(CompleteWFActivityHandler.computeActivityState(inventory))
.build()
))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\mappers\WFProcessMapper.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
} | public void setModeratorGroups(List<Group> moderatorGroups) {
this.moderatorGroups = moderatorGroups;
}
public List<Group> getModeratorGroups() {
return moderatorGroups;
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\wherejointable\User.java | 1 |
请完成以下Java代码 | public static BigDecimal toBigDecimalOrZero(final String str)
{
if (str == null || str.isEmpty())
{
return BigDecimal.ZERO;
}
try
{
return new BigDecimal(str);
}
catch (NumberFormatException e)
{
return BigDecimal.ZERO;
}
}
public static String formatMessage(final String message, Object... params)
{
String messageFormated;
if (params != null && params.length > 0)
{
try
{
messageFormated = MessageFormat.format(message, params);
}
catch (Exception e)
{
// In case message formating failed, we have a fallback format to use
messageFormated = new StringBuilder()
.append(message)
.append(" (").append(params).append(")")
.toString();
}
}
else
{
messageFormated = message;
}
return messageFormated;
}
/**
* String diacritics from given string
*
* @param s original string
* @return string without diacritics
*/
// note: we just moved the method here, and left it unchanges. as of now idk why all this code is commented out
public static String stripDiacritics(String s)
{
/* JAVA5 behaviour */
return s;
/*
* JAVA6 behaviour * if (s == null) { return s; } String normStr = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD); | *
* StringBuffer sb = new StringBuffer(); for (int i = 0; i < normStr.length(); i++) { char ch = normStr.charAt(i); if (ch < 255) sb.append(ch); } return sb.toString(); /*
*/
}
/**
* Check if given string contains digits only.
*
* @param stringToVerify
* @return {@link code true} if the given string consists only of digits (i.e. contains no letter, whitespace decimal point etc).
*/
public static final boolean isNumber(final String stringToVerify)
{
// Null or empty strings are not numbers
if (stringToVerify == null || stringToVerify.isEmpty())
{
return false;
}
final int length = stringToVerify.length();
for (int i = 0; i < length; i++)
{
if (!Character.isDigit(stringToVerify.charAt(i)))
{
return false;
}
}
return true;
}
public static final String toString(final Collection<?> collection, final String separator)
{
if (collection == null)
{
return "null";
}
if (collection.isEmpty())
{
return "";
}
final StringBuilder sb = new StringBuilder();
for (final Object item : collection)
{
if (sb.length() > 0)
{
sb.append(separator);
}
sb.append(String.valueOf(item));
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\util\StringUtils.java | 1 |
请完成以下Java代码 | public ResponseEntity createUser(@Valid @RequestBody RegisterParam registerParam) {
User user = userService.createUser(registerParam);
UserData userData = userQueryService.findById(user.getId()).get();
return ResponseEntity.status(201)
.body(userResponse(new UserWithToken(userData, jwtService.toToken(user))));
}
@RequestMapping(path = "/users/login", method = POST)
public ResponseEntity userLogin(@Valid @RequestBody LoginParam loginParam) {
Optional<User> optional = userRepository.findByEmail(loginParam.getEmail());
if (optional.isPresent()
&& passwordEncoder.matches(loginParam.getPassword(), optional.get().getPassword())) {
UserData userData = userQueryService.findById(optional.get().getId()).get();
return ResponseEntity.ok(
userResponse(new UserWithToken(userData, jwtService.toToken(optional.get()))));
} else {
throw new InvalidAuthenticationException();
}
}
private Map<String, Object> userResponse(UserWithToken userWithToken) {
return new HashMap<String, Object>() { | {
put("user", userWithToken);
}
};
}
}
@Getter
@JsonRootName("user")
@NoArgsConstructor
class LoginParam {
@NotBlank(message = "can't be empty")
@Email(message = "should be an email")
private String email;
@NotBlank(message = "can't be empty")
private String password;
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\UsersApi.java | 1 |
请完成以下Java代码 | public static String fileAsString(File file) {
try {
return inputStreamAsString(new FileInputStream(file));
} catch(FileNotFoundException e) {
throw LOG.fileNotFoundException(file.getAbsolutePath(), e);
}
}
/**
* Returns the content of a File.
*
* @param file the file to load
* @return Content of the file as String
*/
public static byte[] fileAsByteArray(File file) {
try {
return inputStreamAsByteArray(new FileInputStream(file));
} catch(FileNotFoundException e) {
throw LOG.fileNotFoundException(file.getAbsolutePath(), e);
}
}
/**
* Returns the input stream of a file with specified filename
*
* @param filename the name of a File to load
* @return the file content as input stream
* @throws IoUtilException if the file cannot be loaded
*/
public static InputStream fileAsStream(String filename) {
File classpathFile = getClasspathFile(filename);
return fileAsStream(classpathFile);
}
/**
* Returns the input stream of a file.
*
* @param file the File to load
* @return the file content as input stream
* @throws IoUtilException if the file cannot be loaded
*/
public static InputStream fileAsStream(File file) {
try {
return new BufferedInputStream(new FileInputStream(file));
} catch(FileNotFoundException e) {
throw LOG.fileNotFoundException(file.getAbsolutePath(), e);
}
}
/**
* Returns the File for a filename.
*
* @param filename the filename to load
* @return the file object
*/
public static File getClasspathFile(String filename) {
if(filename == null) {
throw LOG.nullParameter("filename");
}
return getClasspathFile(filename, null);
}
/**
* Returns the File for a filename.
*
* @param filename the filename to load
* @param classLoader the classLoader to load file with, if null falls back to TCCL and then this class's classloader
* @return the file object
* @throws IoUtilException if the file cannot be loaded
*/
public static File getClasspathFile(String filename, ClassLoader classLoader) {
if(filename == null) { | throw LOG.nullParameter("filename");
}
URL fileUrl = null;
if (classLoader != null) {
fileUrl = classLoader.getResource(filename);
}
if (fileUrl == null) {
// Try the current Thread context classloader
classLoader = Thread.currentThread().getContextClassLoader();
fileUrl = classLoader.getResource(filename);
if (fileUrl == null) {
// Finally, try the classloader for this class
classLoader = IoUtil.class.getClassLoader();
fileUrl = classLoader.getResource(filename);
}
}
if(fileUrl == null) {
throw LOG.fileNotFoundException(filename);
}
try {
return new File(fileUrl.toURI());
} catch(URISyntaxException e) {
throw LOG.fileNotFoundException(filename, e);
}
}
} | repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\IoUtil.java | 1 |
请完成以下Java代码 | private void adjustLUTUConfiguration(final I_M_HU_LUTU_Configuration lutuConfig, final I_M_ReceiptSchedule receiptSchedule)
{
if (lutuConfigurationFactory.isNoLU(lutuConfig))
{
//
// Adjust TU
lutuConfig.setIsInfiniteQtyTU(false);
lutuConfig.setQtyTU(BigDecimal.ONE);
}
else
{
//
// Adjust LU
lutuConfig.setIsInfiniteQtyLU(false);
lutuConfig.setQtyLU(BigDecimal.ONE);
//
// Adjust TU
// * if the standard QtyTU is less than how much is available to be received => enforce the available Qty
// * else always take the standard QtyTU
// see https://github.com/metasfresh/metasfresh-webui/issues/228
{
final BigDecimal qtyToMoveTU = huReceiptScheduleBL.getQtyToMoveTU(receiptSchedule);
if (qtyToMoveTU.signum() > 0 && qtyToMoveTU.compareTo(lutuConfig.getQtyTU()) < 0)
{
lutuConfig.setQtyTU(qtyToMoveTU);
}
} | // Adjust CU if TU can hold an infinite qty, but the material receipt is of course finite, so we need to adjust the LUTU Configuration.
// Otherwise, receiving using the default configuration will not work.
final BigDecimal qtyTU = lutuConfig.getQtyTU();
if (lutuConfig.isInfiniteQtyCU() && qtyTU.signum() > 0)
{
lutuConfig.setIsInfiniteQtyCU(false);
final BigDecimal qtyToMoveCU = receiptSchedule.getQtyToMove().divide(qtyTU, RoundingMode.UP);
lutuConfig.setQtyCUsPerTU(qtyToMoveCU);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_UsingDefaults.java | 1 |
请完成以下Java代码 | protected TaskListener initializeTaskListener(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, CamundaTaskListener listener) {
Collection<CamundaField> fields = listener.getCamundaFields();
List<FieldDeclaration> fieldDeclarations = initializeFieldDeclarations(element, activity, context, fields);
ExpressionManager expressionManager = context.getExpressionManager();
TaskListener taskListener = null;
String className = listener.getCamundaClass();
String expression = listener.getCamundaExpression();
String delegateExpression = listener.getCamundaDelegateExpression();
CamundaScript scriptElement = listener.getCamundaScript();
if (className != null) {
taskListener = new ClassDelegateTaskListener(className, fieldDeclarations);
} else if (expression != null) {
Expression expressionExp = expressionManager.createExpression(expression);
taskListener = new ExpressionTaskListener(expressionExp);
} else if (delegateExpression != null) {
Expression delegateExp = expressionManager.createExpression(delegateExpression);
taskListener = new DelegateExpressionTaskListener(delegateExp, fieldDeclarations);
} else if (scriptElement != null) {
ExecutableScript executableScript = initializeScript(element, activity, context, scriptElement);
if (executableScript != null) {
taskListener = new ScriptTaskListener(executableScript); | }
}
return taskListener;
}
protected HumanTask getDefinition(CmmnElement element) {
return (HumanTask) super.getDefinition(element);
}
@Override
protected CmmnActivityBehavior getActivityBehavior() {
return new HumanTaskActivityBehavior();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\HumanTaskItemHandler.java | 1 |
请完成以下Java代码 | protected Consumer<AbstractGraphQlClientSyncBuilder<?>> getBuilderInitializer() {
return (builder) -> {
builder.interceptors((interceptorList) -> interceptorList.addAll(this.interceptors));
builder.documentSource(this.documentSource);
builder.setJsonConverter(getJsonConverter());
};
}
private Chain createExecuteChain(SyncGraphQlTransport transport) {
Encoder<?> encoder = HttpMessageConverterDelegate.asEncoder(getJsonConverter());
Decoder<?> decoder = HttpMessageConverterDelegate.asDecoder(getJsonConverter());
Chain chain = (request) -> {
GraphQlResponse response = transport.execute(request);
return new DefaultClientGraphQlResponse(request, response, encoder, decoder);
};
return this.interceptors.stream()
.reduce(SyncGraphQlClientInterceptor::andThen)
.map((i) -> (Chain) (request) -> i.intercept(request, chain))
.orElse(chain);
}
private HttpMessageConverter<Object> getJsonConverter() {
Assert.notNull(this.jsonConverter, "jsonConverter has not been set");
return this.jsonConverter;
}
private static final class DefaultJacksonConverter {
static HttpMessageConverter<Object> initialize() { | JsonMapper jsonMapper = JsonMapper.builder().addModule(new GraphQlJacksonModule()).build();
return new JacksonJsonHttpMessageConverter(jsonMapper);
}
}
@SuppressWarnings("removal")
private static final class DefaultJackson2Converter {
static HttpMessageConverter<Object> initialize() {
com.fasterxml.jackson.databind.ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(new GraphQlJackson2Module()).build();
return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientSyncBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
@Override
public void setSUMUP_Transaction_ID (final int SUMUP_Transaction_ID)
{
if (SUMUP_Transaction_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, SUMUP_Transaction_ID);
}
@Override
public int getSUMUP_Transaction_ID() | {
return get_ValueAsInt(COLUMNNAME_SUMUP_Transaction_ID);
}
@Override
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Transaction.java | 2 |
请完成以下Java代码 | public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set IsDestination.
@param IsDestination IsDestination */
@Override
public void setIsDestination (boolean IsDestination)
{
set_Value (COLUMNNAME_IsDestination, Boolean.valueOf(IsDestination));
}
/** Get IsDestination.
@return IsDestination */
@Override
public boolean isDestination ()
{
Object oo = get_Value(COLUMNNAME_IsDestination);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Beleg soll per EDI übermittelt werden.
@param IsEdiEnabled Beleg soll per EDI übermittelt werden */
@Override
public void setIsEdiEnabled (boolean IsEdiEnabled)
{
set_Value (COLUMNNAME_IsEdiEnabled, Boolean.valueOf(IsEdiEnabled));
}
/** Get Beleg soll per EDI übermittelt werden.
@return Beleg soll per EDI übermittelt werden */
@Override
public boolean isEdiEnabled ()
{
Object oo = get_Value(COLUMNNAME_IsEdiEnabled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
@Override
public void setURL (java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
@Override
public java.lang.String getURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL);
}
/** 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_AD_InputDataSource.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public org.compiere.model.I_AD_Ref_List getAD_Ref_List()
{
return get_ValueAsPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class);
}
@Override
public void setAD_Ref_List(final org.compiere.model.I_AD_Ref_List AD_Ref_List)
{
set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List);
}
@Override
public void setAD_Ref_List_ID (final int AD_Ref_List_ID)
{
if (AD_Ref_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID);
} | @Override
public int getAD_Ref_List_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List_Trl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AlipayConfigUtil {
private static final Log LOG = LogFactory.getLog(AlipayConfigUtil.class);
/**
* 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例)
*/
private static Properties properties = new Properties();
/**
* 私有构造方法
**/
private AlipayConfigUtil() {
}
static {
try {
// 从类路径下读取属性文件
properties.load(AlipayConfigUtil.class.getClassLoader()
.getResourceAsStream("alipay_config.properties"));
} catch (IOException e) {
LOG.error(e);
}
}
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 合作身份者ID,签约账号,以2088开头由16位纯数字组成的字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
public static final String partner = (String) properties.get("partner");
// 收款支付宝账号,以2088开头由16位纯数字组成的字符串,一般情况下收款账号就是签约账号
public static final String seller_id = (String) properties.get("seller_id");
// MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
public static final String key = (String) properties.get("key");
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static final String notify_url = (String) properties.get("notify_url");
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static final String return_url = (String) properties.get("return_url");
// 签名方式
public static final String sign_type = (String) properties.get("sign_type");
// 调试用,创建TXT日志文件夹路径,见AlipayCore.java类中的logResult(String sWord)打印方法。
public static final String log_path = (String) properties.get("log_path"); | // 字符编码格式 目前支持 gbk 或 utf-8
public static final String input_charset = (String) properties.get("input_charset");
// 支付类型 ,无需修改
public static final String payment_type = (String) properties.get("payment_type");
// 调用的接口名,无需修改
public static final String service = (String) properties.get("service");
//支付宝被扫地址
public static final String trade_pay_url = (String) properties.get("trade_pay_url");
//支付宝交易查询地址
public static final String trade_query_url = (String) properties.get("trade_query_url");
//app_id
public static final String app_id = (String) properties.get("app_id");
//商户私钥
public static final String mch_private_key = (String) properties.get("mch_private_key");
//支付宝公钥
public static final String ali_public_key = (String) properties.get("ali_public_key");
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//↓↓↓↓↓↓↓↓↓↓ 请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 防钓鱼时间戳 若要使用请调用类文件submit中的query_timestamp函数
public static final String anti_phishing_key = "";
// 客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1
public static final String exter_invoke_ip = "";
//↑↑↑↑↑↑↑↑↑↑请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\alipay\config\AlipayConfigUtil.java | 2 |
请完成以下Java代码 | private BankStatementLineAndPaymentsRows retrieveRowsData(final BanksStatementReconciliationViewCreateRequest request)
{
final List<BankStatementLineRow> bankStatementLineRows = rowsRepo.getBankStatementLineRowsByIds(request.getBankStatementLineIds());
final List<PaymentToReconcileRow> paymentToReconcileRows = rowsRepo.getPaymentToReconcileRowsByIds(request.getPaymentIds());
return BankStatementLineAndPaymentsRows.builder()
.bankStatementLineRows(BankStatementLineRows.builder()
.repository(rowsRepo)
.rows(bankStatementLineRows)
.build())
.paymentToReconcileRows(PaymentToReconcileRows.builder()
.repository(rowsRepo)
.rows(paymentToReconcileRows)
.build())
.build();
}
@Override
public WindowId getWindowId()
{
return WINDOW_ID;
}
@Override
public void put(final IView view)
{
views.put(view);
}
@Nullable
@Override
public BankStatementReconciliationView getByIdOrNull(final ViewId viewId)
{
return BankStatementReconciliationView.cast(views.getByIdOrNull(viewId));
}
@Override
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
views.closeById(viewId, closeAction);
}
@Override
public Stream<IView> streamAllViews()
{
return views.streamAllViews(); | }
@Override
public void invalidateView(final ViewId viewId)
{
views.invalidateView(viewId);
}
private List<RelatedProcessDescriptor> getPaymentToReconcilateProcesses()
{
return ImmutableList.of(
createProcessDescriptor(PaymentsToReconcileView_Reconcile.class));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass))
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementReconciliationViewFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BankStatementCreateRequest
{
@Nullable
BankStatementImportFileId bankStatementImportFileId;
@NonNull
OrgId orgId;
@NonNull
BankAccountId orgBankAccountId;
@NonNull
LocalDate statementDate;
@NonNull
String name;
@Nullable | String description;
@Nullable
BigDecimal beginningBalance;
@Nullable
ElectronicFundsTransfer eft;
@Value
@Builder
public static class ElectronicFundsTransfer
{
LocalDate statementDate;
String statementReference;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementCreateRequest.java | 2 |
请完成以下Java代码 | public void setC_OLCand_AlbertaTherapy_ID(final int C_OLCand_AlbertaTherapy_ID)
{
if (C_OLCand_AlbertaTherapy_ID < 1)
set_ValueNoCheck(COLUMNNAME_C_OLCand_AlbertaTherapy_ID, null);
else
set_ValueNoCheck(COLUMNNAME_C_OLCand_AlbertaTherapy_ID, C_OLCand_AlbertaTherapy_ID);
}
@Override
public int getC_OLCand_AlbertaTherapy_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_AlbertaTherapy_ID);
}
@Override
public void setC_OLCand_ID(final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_Value(COLUMNNAME_C_OLCand_ID, null);
else
set_Value(COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
} | @Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setTherapy(final String Therapy)
{
set_Value(COLUMNNAME_Therapy, Therapy);
}
@Override
public String getTherapy()
{
return get_ValueAsString(COLUMNNAME_Therapy);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaTherapy.java | 1 |
请完成以下Java代码 | public void setAD_Print_Clients_ID (int AD_Print_Clients_ID)
{
if (AD_Print_Clients_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Print_Clients_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Print_Clients_ID, Integer.valueOf(AD_Print_Clients_ID));
}
@Override
public int getAD_Print_Clients_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Print_Clients_ID);
}
@Override
public org.compiere.model.I_AD_Session getAD_Session()
{
return get_ValueAsPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class);
}
@Override
public void setAD_Session(org.compiere.model.I_AD_Session AD_Session)
{
set_ValueFromPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class, AD_Session);
}
@Override
public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_Value (COLUMNNAME_AD_Session_ID, null);
else
set_Value (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
@Override
public int getAD_Session_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Session_ID);
}
@Override
public void setDateLastPoll (java.sql.Timestamp DateLastPoll) | {
set_Value (COLUMNNAME_DateLastPoll, DateLastPoll);
}
@Override
public java.sql.Timestamp getDateLastPoll()
{
return get_ValueAsTimestamp(COLUMNNAME_DateLastPoll);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Print_Clients.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.