instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean matches(@NonNull final IAttributeSet attributes)
{
// If there is no attribute restrictions we can accept this "attributes" right away
if (onlyAttributes == null || onlyAttributes.isEmpty())
{
return true;
}
for (final HUAttributeQueryFilterVO attributeFilter : onlyAttributes.values())
{
if (!attributeFilter.matches(attributes))
{
return false;
}
}
return true;
}
public void setBarcode(final String barcode)
{
this.barcode = barcode != null ? barcode.trim() : null;
}
private Collection<HUAttributeQueryFilterVO> createBarcodeHUAttributeQueryFilterVOs()
{
if (Check.isEmpty(barcode, true))
{
return ImmutableList.of();
}
final HashMap<AttributeId, HUAttributeQueryFilterVO> filterVOs = new HashMap<>();
for (final I_M_Attribute attribute : getBarcodeAttributes())
{
final HUAttributeQueryFilterVO barcodeAttributeFilterVO = getOrCreateAttributeFilterVO(
filterVOs,
attribute,
HUAttributeQueryFilterVO.ATTRIBUTEVALUETYPE_Unknown);
barcodeAttributeFilterVO.addValue(barcode); | }
return filterVOs.values();
}
private List<I_M_Attribute> getBarcodeAttributes()
{
final IDimensionspecDAO dimensionSpecsRepo = Services.get(IDimensionspecDAO.class);
final DimensionSpec barcodeDimSpec = dimensionSpecsRepo.retrieveForInternalNameOrNull(HUConstants.DIM_Barcode_Attributes);
if (barcodeDimSpec == null)
{
return ImmutableList.of(); // no barcode dimension spec. Nothing to do
}
return barcodeDimSpec.retrieveAttributes()
.stream()
// Barcode must be a String attribute. In the database, this is forced by a validation rule
.filter(attribute -> attribute.getAttributeValueType().equals(X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40))
.collect(ImmutableList.toImmutableList());
}
public void setAllowSql(final boolean allowSql)
{
this.allowSql = allowSql;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder_Attributes.java | 1 |
请完成以下Java代码 | public class SysUserTenantVo {
/**
* 用户id
*/
private String id;
/**
* 用户账号
*/
private String username;
/**
* 用户昵称
*/
private String realname;
/**
* 工号
*/
private String workNo;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String phone;
/**
* 头像
*/
private String avatar;
/**
* 创建日期
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 职位
*/
@Dict(dictTable ="sys_position",dicText = "name",dicCode = "id")
private String post;
/**
* 审核状态
*/
private String status;
/**
* 部门名称
*/
private String orgCodeTxt;
/**
* 部门code
*/
private String orgCode;
/**
* 租户id
*/
private String relTenantIds;
/**
* 租户创建人
*/
private String createBy; | /**
* 用户租户状态
*/
private String userTenantStatus;
/**
* 用户租户id
*/
private String tenantUserId;
/**
* 租户名称
*/
private String name;
/**
* 所属行业
*/
@Dict(dicCode = "trade")
private String trade;
/**
* 门牌号
*/
private String houseNumber;
/**
* 是否为会员
*/
private String memberType;
/**
* 是否为租户管理员
*/
private Boolean tenantAdmin = false;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\SysUserTenantVo.java | 1 |
请完成以下Java代码 | public UomId getUomId()
{
return getPrice().getUomId();
}
public CostElementId getCostElementId()
{
return getCostSegmentAndElement().getCostElementId();
}
public boolean isInboundCost()
{
return !getTrxType().isOutboundCost();
}
public boolean isMainProduct()
{
return getTrxType() == PPOrderCostTrxType.MainProduct;
}
public boolean isCoProduct()
{
return getTrxType().isCoProduct();
}
public boolean isByProduct()
{
return getTrxType() == PPOrderCostTrxType.ByProduct;
}
@NonNull
public PPOrderCost addingAccumulatedAmountAndQty(
@NonNull final CostAmount amt,
@NonNull final Quantity qty,
@NonNull final QuantityUOMConverter uomConverter)
{
if (amt.isZero() && qty.isZero())
{
return this;
}
final boolean amtIsPositiveOrZero = amt.signum() >= 0;
final boolean amtIsNotZero = amt.signum() != 0;
final boolean qtyIsPositiveOrZero = qty.signum() >= 0;
if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero )
{
throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty);
}
final Quantity accumulatedQty = getAccumulatedQty();
final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId());
return toBuilder()
.accumulatedAmount(getAccumulatedAmount().add(amt))
.accumulatedQty(accumulatedQty.add(qtyConv))
.build();
}
public PPOrderCost subtractingAccumulatedAmountAndQty(
@NonNull final CostAmount amt,
@NonNull final Quantity qty,
@NonNull final QuantityUOMConverter uomConverter)
{
return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter); | }
public PPOrderCost withPrice(@NonNull final CostPrice newPrice)
{
if (this.getPrice().equals(newPrice))
{
return this;
}
return toBuilder().price(newPrice).build();
}
/* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount)
{
this.postCalculationAmount = postCalculationAmount;
}
/* package */void setPostCalculationAmountAsAccumulatedAmt()
{
setPostCalculationAmount(getAccumulatedAmount());
}
/* package */void setPostCalculationAmountAsZero()
{
setPostCalculationAmount(getPostCalculationAmount().toZero());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<SysPermissionDataRule> getPermRuleListByPermId(String permissionId) {
LambdaQueryWrapper<SysPermissionDataRule> query = new LambdaQueryWrapper<SysPermissionDataRule>();
query.eq(SysPermissionDataRule::getPermissionId, permissionId);
query.orderByDesc(SysPermissionDataRule::getCreateTime);
List<SysPermissionDataRule> permRuleList = this.list(query);
return permRuleList;
}
/**
* 根据前端传递的权限名称和权限值参数来查询权限数据
*/
@Override
public List<SysPermissionDataRule> queryPermissionRule(SysPermissionDataRule permRule) {
QueryWrapper<SysPermissionDataRule> queryWrapper = QueryGenerator.initQueryWrapper(permRule, null);
return this.list(queryWrapper);
}
@Override
public List<SysPermissionDataRule> queryPermissionDataRules(String username,String permissionId) {
List<String> idsList = this.baseMapper.queryDataRuleIds(username, permissionId);
// 代码逻辑说明: 数据权限失效问题处理--------------------
if(idsList==null || idsList.size()==0) {
return null;
}
Set<String> set = new HashSet<String>();
for (String ids : idsList) {
if(oConvertUtils.isEmpty(ids)) {
continue;
}
String[] arr = ids.split(",");
for (String id : arr) {
if(oConvertUtils.isNotEmpty(id) && !set.contains(id)) {
set.add(id);
}
}
}
if(set.size()==0) {
return null;
}
return this.baseMapper.selectList(new QueryWrapper<SysPermissionDataRule>().in("id", set).eq("status",CommonConstant.STATUS_1));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void savePermissionDataRule(SysPermissionDataRule sysPermissionDataRule) {
this.save(sysPermissionDataRule); | SysPermission permission = sysPermissionMapper.selectById(sysPermissionDataRule.getPermissionId());
boolean flag = permission != null && (permission.getRuleFlag() == null || permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_0));
if(flag) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_1);
sysPermissionMapper.updateById(permission);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deletePermissionDataRule(String dataRuleId) {
SysPermissionDataRule dataRule = this.baseMapper.selectById(dataRuleId);
if(dataRule!=null) {
this.removeById(dataRuleId);
Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysPermissionDataRule>().eq(SysPermissionDataRule::getPermissionId, dataRule.getPermissionId()));
//注:同一个事务中删除后再查询是会认为数据已被删除的 若事务回滚上述删除无效
if(count==null || count==0) {
SysPermission permission = sysPermissionMapper.selectById(dataRule.getPermissionId());
if(permission!=null && permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_1)) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_0);
sysPermissionMapper.updateById(permission);
}
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysPermissionDataRuleImpl.java | 2 |
请完成以下Java代码 | private static String stripInlineComment(String line) {
int index = line.indexOf("//");
return index >= 0 ? line.substring(0, index) : line;
}
private static String stripStringLiterals(String line) {
StringBuilder sb = new StringBuilder();
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"' && !inSingleQuote) {
inDoubleQuote = !inDoubleQuote; | continue;
} else if (c == '\'' && !inDoubleQuote) {
inSingleQuote = !inSingleQuote;
continue;
}
if (!inSingleQuote && !inDoubleQuote) {
sb.append(c);
}
}
return sb.toString();
}
} | repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\JsValidator.java | 1 |
请完成以下Java代码 | protected static String segLongest(char[] charArray, AhoCorasickDoubleArrayTrie<String> trie)
{
final String[] wordNet = new String[charArray.length];
final int[] lengthNet = new int[charArray.length];
trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<String>()
{
@Override
public void hit(int begin, int end, String value)
{
int length = end - begin;
if (length > lengthNet[begin])
{
wordNet[begin] = value;
lengthNet[begin] = length;
}
}
});
StringBuilder sb = new StringBuilder(charArray.length);
for (int offset = 0; offset < wordNet.length; )
{
if (wordNet[offset] == null)
{
sb.append(charArray[offset]);
++offset;
continue;
}
sb.append(wordNet[offset]);
offset += lengthNet[offset];
}
return sb.toString();
}
/**
* 最长分词
*/
public static class Searcher extends BaseSearcher<String>
{
/**
* 分词从何处开始,这是一个状态
*/
int begin;
DoubleArrayTrie<String> trie;
protected Searcher(char[] c, DoubleArrayTrie<String> trie)
{
super(c); | this.trie = trie;
}
protected Searcher(String text, DoubleArrayTrie<String> trie)
{
super(text);
this.trie = trie;
}
@Override
public Map.Entry<String, String> next()
{
// 保证首次调用找到一个词语
Map.Entry<String, String> result = null;
while (begin < c.length)
{
LinkedList<Map.Entry<String, String>> entryList = trie.commonPrefixSearchWithValue(c, begin);
if (entryList.size() == 0)
{
++begin;
}
else
{
result = entryList.getLast();
offset = begin;
begin += result.getKey().length();
break;
}
}
if (result == null)
{
return null;
}
return result;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\BaseChineseDictionary.java | 1 |
请完成以下Java代码 | public boolean doCatch(final Throwable ex)
{
Loggables.addLog("@Error@ @C_BPartner_ID@:" + partner.getValue() + "_" + partner.getName() + ": " + ex.getLocalizedMessage());
logger.debug("Failed creating contract for {}", partner, ex);
return true; // rollback
}
});
}
}
return flatrateTermsCollector.build();
}
private void createTerm(@NonNull final I_C_BPartner partner, @NonNull final ImmutableList.Builder<I_C_Flatrate_Term> flatrateTermCollector)
{
final IFlatrateBL flatrateBL = Services.get(IFlatrateBL.class);
final IContextAware context = PlainContextAware.newWithThreadInheritedTrx(ctx);
for (final I_M_Product product : products)
{
final CreateFlatrateTermRequest createFlatrateTermRequest = CreateFlatrateTermRequest.builder()
.orgId(OrgId.ofRepoId(conditions.getAD_Org_ID()))
.context(context)
.bPartner(partner)
.conditions(conditions)
.startDate(startDate) | .endDate(endDate)
.userInCharge(userInCharge)
.productAndCategoryId(createProductAndCategoryId(product))
.isSimulation(isSimulation)
.completeIt(isCompleteDocument)
.build();
flatrateTermCollector.add(flatrateBL.createTerm(createFlatrateTermRequest));
}
}
@Nullable
public ProductAndCategoryId createProductAndCategoryId(@Nullable final I_M_Product productRecord)
{
if (productRecord == null)
{
return null;
}
return ProductAndCategoryId.of(productRecord.getM_Product_ID(), productRecord.getM_Product_Category_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\process\FlatrateTermCreator.java | 1 |
请完成以下Java代码 | public static String joinDbEntityIds(Collection<? extends DbEntity> dbEntities) {
return join(new StringIterator<DbEntity>(dbEntities.iterator()) {
public String next() {
return iterator.next().getId();
}
});
}
public static String joinProcessElementInstanceIds(Collection<? extends ProcessElementInstance> processElementInstances) {
final Iterator<? extends ProcessElementInstance> iterator = processElementInstances.iterator();
return join(new StringIterator<ProcessElementInstance>(iterator) {
public String next() {
return iterator.next().getId();
}
});
}
/**
* @param string the String to check.
* @return a boolean <code>TRUE</code> if the String is not null and not empty. <code>FALSE</code> otherwise.
*/
public static boolean hasText(String string) {
return string != null && !string.isEmpty();
}
public static String join(Iterator<String> iterator) {
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
builder.append(iterator.next());
if (iterator.hasNext()) {
builder.append(", ");
}
} | return builder.toString();
}
public abstract static class StringIterator<T> implements Iterator<String> {
protected Iterator<? extends T> iterator;
public StringIterator(Iterator<? extends T> iterator) {
this.iterator = iterator;
}
public boolean hasNext() {
return iterator.hasNext();
}
public void remove() {
iterator.remove();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\StringUtil.java | 1 |
请完成以下Java代码 | public class DefaultServiceTaskBehavior implements DelegateExecutionFunction {
private final ApplicationContext applicationContext;
private final IntegrationContextBuilder integrationContextBuilder;
private final VariablesPropagator variablesPropagator;
public DefaultServiceTaskBehavior(
ApplicationContext applicationContext,
IntegrationContextBuilder integrationContextBuilder,
VariablesPropagator variablesPropagator
) {
this.applicationContext = applicationContext;
this.integrationContextBuilder = integrationContextBuilder;
this.variablesPropagator = variablesPropagator;
}
/**
* We have two different implementation strategy that can be executed
* in according if we have a connector action definition match or not.
**/
@Override
public DelegateExecutionOutcome apply(DelegateExecution execution) {
Connector connector = getConnector(getImplementation(execution));
IntegrationContext integrationContext = connector.apply(integrationContextBuilder.from(execution));
variablesPropagator.propagate(execution, integrationContext.getOutBoundVariables()); | return DelegateExecutionOutcome.LEAVE_EXECUTION;
}
private String getImplementation(DelegateExecution execution) {
return ((ServiceTask) execution.getCurrentFlowElement()).getImplementation();
}
private Connector getConnector(String implementation) {
return applicationContext.getBean(implementation, Connector.class);
}
private String getServiceTaskImplementation(DelegateExecution execution) {
return ((ServiceTask) execution.getCurrentFlowElement()).getImplementation();
}
public boolean hasConnectorBean(DelegateExecution execution) {
String implementation = getServiceTaskImplementation(execution);
return (
applicationContext.containsBean(implementation) &&
applicationContext.getBean(implementation) instanceof Connector
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\connector\DefaultServiceTaskBehavior.java | 1 |
请完成以下Java代码 | public static String[] split(String text, String regex) {
if (text == null) {
return null;
}
else if (regex == null) {
return new String[] { text };
}
else {
String[] result = text.split(regex);
for (int i = 0; i < result.length; i++) {
result[i] = result[i].trim();
}
return result;
}
}
/**
* Joins a list of Strings to a single one.
*
* @param delimiter the delimiter between the joined parts
* @param parts the parts to join
* @return the joined String or null if parts was null
*/
public static String join(String delimiter, String... parts) {
if (parts == null) {
return null;
}
if (delimiter == null) {
delimiter = "";
}
StringBuilder stringBuilder = new StringBuilder();
for (int i=0; i < parts.length; i++) {
if (i > 0) {
stringBuilder.append(delimiter);
} | stringBuilder.append(parts[i]);
}
return stringBuilder.toString();
}
/**
* Returns either the passed in String, or if the String is <code>null</code>, an empty String ("").
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @param text the String to check, may be null
* @return the passed in String, or the empty String if it was <code>null</code>
*/
public static String defaultString(String text) {
return text == null ? "" : text;
}
/**
* Fetches the stack trace of an exception as a String.
*
* @param throwable to get the stack trace from
* @return the stack trace as String
*/
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw, true));
return sw.toString();
}
} | repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\StringUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getWfResult(@PathVariable("wfid") String workflowId,
@PathVariable("wfrunid") String workflowRunId) {
try {
WorkflowStub workflowStub =
workflowClient.newUntypedWorkflowStub(workflowId,
Optional.of(workflowRunId),
Optional.empty());
CloudEvent ce = workflowStub.getResult(CloudEvent.class);
if (ce == null) {
log.warn("Workflow result is null for workflow: {}", workflowId);
return "Error: Workflow returned no result";
}
String res = new String(EventFormatProvider
.getInstance()
.resolveFormat(JsonFormat.CONTENT_TYPE) | .serialize(ce));
JsonNode resJson = objectMapper.readTree(res);
return resJson.toPrettyString();
} catch (Exception e) {
log.error("Failed to get workflow result: {}", workflowId, e);
return "Error: " + e.getMessage();
}
}
@GetMapping("/")
public String displayDemo(Model model) {
model.addAttribute("startInfo", new StartInfo());
return "index";
}
} | repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\controller\TemporalWebDialectController.java | 2 |
请完成以下Java代码 | public int getM_BOMAlternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMAlternative.java | 1 |
请完成以下Java代码 | public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
return this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
SimpleCustomKeyValue<?, ?> that = (SimpleCustomKeyValue<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return new StringJoiner(", ", SimpleCustomKeyValue.class.getSimpleName() + "[", "]").add("key=" + key).add("value=" + value).toString();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-4\src\main\java\com\baeldung\entries\SimpleCustomKeyValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PessimisticLockingStudent {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "student")
private List<PessimisticLockingCourse> courses;
public PessimisticLockingStudent(Long id, String name) {
this.id = id;
this.name = name;
}
public PessimisticLockingStudent() {
}
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 List<PessimisticLockingCourse> getCourses() {
return courses;
}
public void setCourses(List<PessimisticLockingCourse> courses) {
this.courses = courses;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\pessimisticlocking\PessimisticLockingStudent.java | 2 |
请完成以下Java代码 | private static String extractNameAndModifiers(
@NonNull final String contextWithoutMarkers,
@NonNull final List<String> modifiers)
{
String name = null;
boolean firstToken = true;
for (final String token : SEPARATOR_SPLITTER.splitToList(contextWithoutMarkers))
{
if (firstToken)
{
name = token.trim();
}
else
{
modifiers.add(token);
}
firstToken = false;
}
assertValidName(name);
return name;
}
private static void assertValidName(@Nullable final String name)
{
if (name == null || name.isEmpty())
{
throw new AdempiereException("Empty name is not a valid name");
}
if (!NAME_PATTERN.matcher(name).matches())
{
throw new AdempiereException("Invalid name '" + name + "'. It shall match '" + NAME_PATTERN + "'");
}
}
@Nullable
private static String extractDefaultValue(final ArrayList<String> modifiers)
{
final String defaultValue;
if (!modifiers.isEmpty() && !isModifier(modifiers.get(modifiers.size() - 1)))
{
defaultValue = modifiers.remove(modifiers.size() - 1);
}
else
{
defaultValue = VALUE_NULL;
}
return defaultValue;
}
/**
* Parse a given name, surrounded by {@value #NAME_Marker}
*/
@Nullable
public static CtxName parseWithMarkers(@Nullable final String contextWithMarkers)
{
if (contextWithMarkers == null)
{
return null;
} | String contextWithoutMarkers = contextWithMarkers.trim();
if (contextWithoutMarkers.startsWith(NAME_Marker))
{
contextWithoutMarkers = contextWithoutMarkers.substring(1);
}
if (contextWithoutMarkers.endsWith(NAME_Marker))
{
contextWithoutMarkers = contextWithoutMarkers.substring(0, contextWithoutMarkers.length() - 1);
}
return parse(contextWithoutMarkers);
}
/**
* @param expression expression with context variables (e.g. sql where clause)
* @return true if expression contains given name
*/
@VisibleForTesting
static boolean containsName(@Nullable final String name, @Nullable final String expression)
{
// FIXME: replace it with StringExpression
if (name == null || name.isEmpty())
{
return false;
}
if (expression == null || expression.isEmpty())
{
return false;
}
final int idx = expression.indexOf(NAME_Marker + name);
if (idx < 0)
{
return false;
}
final int idx2 = expression.indexOf(NAME_Marker, idx + 1);
if (idx2 < 0)
{
return false;
}
final String nameStr = expression.substring(idx + 1, idx2);
return name.equals(parse(nameStr).getName());
}
/**
* @return true if given string is a registered modifier
*/
private static boolean isModifier(final String modifier)
{
if (Check.isEmpty(modifier))
{
return false;
}
return MODIFIERS.contains(modifier);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxNames.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Person save(@RequestBody Person person) {
Person p = personRepository.save(person);
return p;
}
/**
* 测试findByAddress
*/
@RequestMapping("/q1")
public List<Person> q1(String address) {
List<Person> people = personRepository.findByAddress(address);
return people;
}
/**
* 测试findByNameAndAddress
*/
@RequestMapping("/q2")
public Person q2(String name, String address) {
Person people = personRepository.findByNameAndAddress(name, address);
return people;
}
/**
* 测试withNameAndAddressQuery
*/
@RequestMapping("/q3")
public Person q3(String name, String address) {
Person p = personRepository.withNameAndAddressQuery(name, address); | return p;
}
/**
* 测试withNameAndAddressNamedQuery
*/
@RequestMapping("/q4")
public Person q4(String name, String address) {
Person p = personRepository.withNameAndAddressNamedQuery(name, address);
return p;
}
/**
* 测试排序
*/
@RequestMapping("/sort")
public List<Person> sort() {
List<Person> people = personRepository.findAll(new Sort(Direction.ASC, "age"));
return people;
}
/**
* 测试分页
*/
@RequestMapping("/page")
public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
Page<Person> pagePeople = personRepository.findAll(new PageRequest(pageNo, pageSize));
return pagePeople;
}
} | repos\spring-boot-student-master\spring-boot-student-data-jpa\src\main\java\com\xiaolyuh\controller\DataController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@OneToMany
@JoinColumn(name = "user_id")
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String firstName, String lastName) { | this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public Set<Role> getRoles() {
return roles;
}
public void addRole(Role role) {
roles.add(role);
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\lazyinitialization\entity\User.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static BeanMetadataElement getLogoutRequestValidator(Element element) {
String logoutRequestValidator = element.getAttribute(ATT_LOGOUT_REQUEST_VALIDATOR_REF);
if (StringUtils.hasText(logoutRequestValidator)) {
return new RuntimeBeanReference(logoutRequestValidator);
}
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5LogoutRequestValidator.class).getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
static BeanMetadataElement getLogoutResponseValidator(Element element) {
String logoutResponseValidator = element.getAttribute(ATT_LOGOUT_RESPONSE_VALIDATOR_REF);
if (StringUtils.hasText(logoutResponseValidator)) {
return new RuntimeBeanReference(logoutResponseValidator);
}
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5LogoutResponseValidator.class).getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
static BeanMetadataElement getLogoutRequestRepository(Element element) {
String logoutRequestRepository = element.getAttribute(ATT_LOGOUT_REQUEST_REPOSITORY_REF);
if (StringUtils.hasText(logoutRequestRepository)) {
return new RuntimeBeanReference(logoutRequestRepository);
}
return BeanDefinitionBuilder.rootBeanDefinition(HttpSessionLogoutRequestRepository.class).getBeanDefinition();
} | static BeanMetadataElement getLogoutRequestResolver(Element element, BeanMetadataElement registrations) {
String logoutRequestResolver = element.getAttribute(ATT_LOGOUT_REQUEST_RESOLVER_REF);
if (StringUtils.hasText(logoutRequestResolver)) {
return new RuntimeBeanReference(logoutRequestResolver);
}
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5LogoutRequestResolver.class)
.addConstructorArgValue(registrations)
.getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LogoutBeanDefinitionParserUtils.java | 2 |
请完成以下Java代码 | public class DeleteIdentityLinkCmd extends NeedsAppDefinitionCmd<Void> {
private static final long serialVersionUID = 1L;
public static final int IDENTITY_USER = 1;
public static final int IDENTITY_GROUP = 2;
protected String userId;
protected String groupId;
protected String type;
public DeleteIdentityLinkCmd(String appDefinitionId, String userId, String groupId, String type) {
super(appDefinitionId);
validateParams(userId, groupId, type, appDefinitionId);
this.appDefinitionId = appDefinitionId;
this.userId = userId;
this.groupId = groupId;
this.type = type;
}
protected void validateParams(String userId, String groupId, String type, String taskId) {
if (appDefinitionId == null) {
throw new FlowableIllegalArgumentException("appDefinitionId is null");
} | if (type == null) {
throw new FlowableIllegalArgumentException("type is required when adding a new app identity link");
}
if (userId == null && groupId == null) {
throw new FlowableIllegalArgumentException("userId and groupId cannot both be null");
}
}
@Override
protected Void execute(CommandContext commandContext, AppDefinition appDefinition) {
CommandContextUtil.getIdentityLinkService().deleteScopeIdentityLink(appDefinitionId, ScopeTypes.APP, userId, groupId, type);
return null;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\cmd\DeleteIdentityLinkCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static String extractEndpointURI(@Nullable final Endpoint endpoint)
{
return endpoint != null && Check.isNotBlank(endpoint.getEndpointUri())
? endpoint.getEndpointUri()
: "[Could not obtain endpoint information]";
}
@NonNull
private static String getAuditEndpoint(@NonNull final Exchange exchange)
{
final String auditTrailEndpoint = exchange.getIn().getHeader(HEADER_AUDIT_TRAIL, String.class);
if (EmptyUtil.isEmpty(auditTrailEndpoint))
{
throw new RuntimeCamelException("auditTrailEndpoint cannot be empty at this point!");
}
final String externalSystemValue = exchange.getIn().getHeader(HEADER_EXTERNAL_SYSTEM_VALUE, String.class); | final String value = FileUtil.stripIllegalCharacters(externalSystemValue);
final String traceId = CoalesceUtil.coalesceNotNull(exchange.getIn().getHeader(HEADER_TRACE_ID, String.class), UUID.randomUUID().toString());
final String auditFolderName = DateTimeFormatter.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.systemDefault())
.format(LocalDate.now());
final String auditFileNameTimeStamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmssSSS")
.withZone(ZoneId.systemDefault())
.format(Instant.now());
final String auditFileName = traceId + "_" + value + "_" + auditFileNameTimeStamp + ".txt";
return file(auditTrailEndpoint + "/" + auditFolderName + "/?fileName=" + auditFileName).getUri();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AuditEventNotifier.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName().replace("Impl", "")).append("[")
.append("id=").append(id)
.append(", jobHandlerType=").append(jobHandlerType)
.append(", jobType=").append(jobType);
if (category != null) {
sb.append(", category=").append(category);
}
if (elementId != null) {
sb.append(", elementId=").append(elementId);
}
if (correlationId != null) {
sb.append(", correlationId=").append(correlationId);
}
if (executionId != null) {
sb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId);
} else if (scopeId != null) {
sb.append(", scopeId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeType=").append(scopeType);
}
if (processDefinitionId != null) { | sb.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeDefinitionId != null) {
if (scopeId == null) {
sb.append(", scopeType=").append(scopeType);
}
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\AbstractJobEntityImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(oidc -> {
oidc.clientRegistrationEndpoint(Customizer.withDefaults());
});
// Redirect to login page when user not authenticated
http.exceptionHandling((exceptions) -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
);
// Accept access tokens for User Info and/or Client Registration
http.oauth2ResourceServer((resourceServer) -> resourceServer
.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests( r -> r.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.build();
}
@Bean
public RegisteredClientRepository registeredClientRepository(RegistrationProperties props) {
RegisteredClient registrarClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId(props.getRegistrarClientId())
.clientSecret(props.getRegistrarClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.clientSettings(ClientSettings.builder()
.requireProofKey(false) | .requireAuthorizationConsent(false)
.build())
.scope("client.create")
.scope("client.read")
.build();
RegisteredClientRepository delegate = new InMemoryRegisteredClientRepository(registrarClient);
return new CustomRegisteredClientRepository(delegate);
}
@ConfigurationProperties(prefix = "baeldung.security.server.registration")
@Getter
@Setter
public static class RegistrationProperties {
private String registrarClientId;
private String registrarClientSecret;
}
} | repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-authorization-server\src\main\java\com\baeldung\spring\security\authserver\config\SecurityConfig.java | 2 |
请完成以下Java代码 | public class R_Request
{
@Init
public void init()
{
CopyRecordFactory.enableForTableName(I_R_Request.Table_Name);
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_R_Request.COLUMNNAME_R_RequestType_ID)
@CalloutMethod(columnNames = { I_R_Request.COLUMNNAME_R_RequestType_ID })
public void onRequestTypeChange(final I_R_Request request)
{
final I_R_RequestType requestType = request.getR_RequestType();
if (requestType == null)
{
// in case the request type is deleted, the R_RequestType_InternalName must be set to null
request.setR_RequestType_InternalName(null);
}
else
{
// set the internal name of the request type
request.setR_RequestType_InternalName(requestType.getInternalName());
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_R_Request.COLUMNNAME_M_InOut_ID)
@CalloutMethod(columnNames = { I_R_Request.COLUMNNAME_M_InOut_ID })
public void onMInOutSet(final de.metas.request.model.I_R_Request request)
{
final I_M_InOut inout = InterfaceWrapperHelper.create(request.getM_InOut(), I_M_InOut.class);
if (inout == null)
{
// in case the inout was removed or is not set, the DateDelivered shall also be not set
request.setDateDelivered(null);
}
else
{
request.setDateDelivered(inout.getMovementDate());
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = de.metas.request.model.I_R_Request.COLUMNNAME_M_QualityNote_ID)
@CalloutMethod(columnNames = { de.metas.request.model.I_R_Request.COLUMNNAME_M_QualityNote_ID })
public void onQualityNoteChanged(final de.metas.request.model.I_R_Request request)
{
final QualityNoteId qualityNoteId = QualityNoteId.ofRepoIdOrNull(request.getM_QualityNote_ID());
if (qualityNoteId == null) | {
// nothing to do
return;
}
final I_M_QualityNote qualityNote = Services.get(IQualityNoteDAO.class).getById(qualityNoteId);
if (qualityNote == null)
{
// nothing to do
return;
}
// set the request's performance type with the value form the quality note entry
final String performanceType = qualityNote.getPerformanceType();
request.setPerformanceType(performanceType);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW })
public void setSalesRep(final I_R_Request request)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(request);
final RoleId adRoleId = Env.getLoggedRoleId(ctx);
final Role role = Services.get(IRoleDAO.class).getById(adRoleId);
// task #577: The SalesRep in R_Request will be Role's supervisor
final UserId supervisorId = role.getSupervisorId();
if (supervisorId != null)
{
request.setSalesRep_ID(supervisorId.getRepoId());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\model\validator\R_Request.java | 1 |
请完成以下Java代码 | public class DmnVariableImpl {
protected String id;
protected String name;
protected DmnTypeDefinition typeDefinition;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DmnTypeDefinition getTypeDefinition() {
return typeDefinition;
} | public void setTypeDefinition(DmnTypeDefinition typeDefinition) {
this.typeDefinition = typeDefinition;
}
@Override
public String toString() {
return "DmnVariableImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", typeDefinition=" + typeDefinition +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnVariableImpl.java | 1 |
请完成以下Java代码 | public List<MoveToAvailablePlanItemDefinitionMapping> getMoveToAvailablePlanItemDefinitionMappings() {
return moveToAvailablePlanItemDefinitionMappings;
}
@Override
public List<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitionMappings() {
return waitingForRepetitionPlanItemDefinitionMappings;
}
@Override
public List<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitionMappings() {
return removeWaitingForRepetitionPlanItemDefinitionMappings;
}
@Override
public List<ChangePlanItemIdMapping> getChangePlanItemIdMappings() {
return changePlanItemIdMappings;
}
@Override
public List<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdWithDefinitionIdMappings() {
return changePlanItemIdWithDefinitionIdMappings;
}
@Override
public List<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIdsMappings() {
return changePlanItemDefinitionWithNewTargetIdsMappings; | }
@Override
public String getPreUpgradeExpression() {
return preUpgradeExpression;
}
@Override
public String getPostUpgradeExpression() {
return postUpgradeExpression;
}
@Override
public Map<String, Map<String, Object>> getPlanItemLocalVariables() {
return this.planItemLocalVariables;
}
@Override
public Map<String, Object> getCaseInstanceVariables() {
return this.caseInstanceVariables;
}
@Override
public String asJsonString() {
return CaseInstanceMigrationDocumentConverter.convertToJsonString(this);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InsuranceContractMaximumAmountForProductGroups {
@SerializedName("productGroupId")
private String productGroupId = null;
@SerializedName("quantity")
private InsuranceContractQuantity quantity = null;
public InsuranceContractMaximumAmountForProductGroups productGroupId(String productGroupId) {
this.productGroupId = productGroupId;
return this;
}
/**
* Alberta-Id der Warengruppe - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /productGroup
* @return productGroupId
**/
@Schema(example = "c5630d50-9ca9-44bb-bb4e-2cf724f671e1", description = "Alberta-Id der Warengruppe - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /productGroup")
public String getProductGroupId() {
return productGroupId;
}
public void setProductGroupId(String productGroupId) {
this.productGroupId = productGroupId;
}
public InsuranceContractMaximumAmountForProductGroups quantity(InsuranceContractQuantity quantity) {
this.quantity = quantity;
return this;
}
/**
* Get quantity
* @return quantity
**/
@Schema(description = "")
public InsuranceContractQuantity getQuantity() {
return quantity;
}
public void setQuantity(InsuranceContractQuantity quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractMaximumAmountForProductGroups insuranceContractMaximumAmountForProductGroups = (InsuranceContractMaximumAmountForProductGroups) o;
return Objects.equals(this.productGroupId, insuranceContractMaximumAmountForProductGroups.productGroupId) &&
Objects.equals(this.quantity, insuranceContractMaximumAmountForProductGroups.quantity);
}
@Override
public int hashCode() {
return Objects.hash(productGroupId, quantity);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractMaximumAmountForProductGroups {\n");
sb.append(" productGroupId: ").append(toIndentedString(productGroupId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaximumAmountForProductGroups.java | 2 |
请完成以下Java代码 | void changeEmail(Email email) {
this.email = email;
}
void changePassword(Password password) {
this.password = password;
}
void changeName(UserName userName) {
profile.changeUserName(userName);
}
void changeBio(String bio) {
profile.changeBio(bio);
}
void changeImage(Image image) {
profile.changeImage(image);
}
public Long getId() {
return id;
}
public Email getEmail() {
return email;
}
public UserName getName() {
return profile.getUserName();
}
String getBio() {
return profile.getBio();
} | Image getImage() {
return profile.getImage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final var user = (User) o;
return email.equals(user.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public KeyGenerator keyGenerator() {
return (target, method, params) -> {
Map<String,Object> container = new HashMap<>(8);
Class<?> targetClassClass = target.getClass();
// 类地址
container.put("class",targetClassClass.toGenericString());
// 方法名称
container.put("methodName",method.getName());
// 包名称
container.put("package",targetClassClass.getPackage());
// 参数列表
for (int i = 0; i < params.length; i++) {
container.put(String.valueOf(i),params[i]);
}
// 转为JSON字符串
String jsonString = JSON.toJSONString(container);
// 使用 MurmurHash 生成 hash
return Integer.toHexString(MurmurHash3.hash32x86(jsonString.getBytes()));
};
}
@Bean
@SuppressWarnings({"unchecked","all"})
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
// 处理缓存读取错误
log.error("Cache Get Error: {}",exception.getMessage());
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
// 处理缓存写入错误
log.error("Cache Put Error: {}",exception.getMessage());
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
// 处理缓存删除错误
log.error("Cache Evict Error: {}",exception.getMessage());
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
// 处理缓存清除错误
log.error("Cache Clear Error: {}",exception.getMessage());
}
};
}
/**
* Value 序列化
*
* @param <T>
* @author /
*/ | static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private final Class<T> clazz;
FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || bytes.length == 0) {
return null;
}
String str = new String(bytes, StandardCharsets.UTF_8);
return JSON.parseObject(str, clazz);
}
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedisConfiguration.java | 2 |
请完成以下Java代码 | public class MyCell {
private String content;
private String textColor;
private String bgColor;
private String textSize;
private String textWeight;
public MyCell() {
}
public MyCell(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTextColor() {
return textColor;
}
public void setTextColor(String textColor) {
this.textColor = textColor;
}
public String getBgColor() { | return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextWeight() {
return textWeight;
}
public void setTextWeight(String textWeight) {
this.textWeight = textWeight;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\excel\MyCell.java | 1 |
请完成以下Java代码 | private static class NextDispatch
{
public static NextDispatch schedule(final Runnable task, final ZonedDateTime date, final TaskScheduler taskScheduler)
{
final ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(task, TimeUtil.asDate(date));
return builder()
.task(task)
.scheduledFuture(scheduledFuture)
.notificationTime(date)
.build();
}
Runnable task;
ScheduledFuture<?> scheduledFuture;
ZonedDateTime notificationTime;
public void cancel()
{
final boolean canceled = scheduledFuture.cancel(false);
logger.trace("Cancel requested for {} (result was: {})", this, canceled);
}
public NextDispatch rescheduleIfAfter(final ZonedDateTime date, final TaskScheduler taskScheduler)
{
if (!notificationTime.isAfter(date) && !scheduledFuture.isDone()) | {
logger.trace("Skip rescheduling {} because it's not after {}", date);
return this;
}
cancel();
final ScheduledFuture<?> nextScheduledFuture = taskScheduler.schedule(task, TimeUtil.asTimestamp(date));
NextDispatch nextDispatch = NextDispatch.builder()
.task(task)
.scheduledFuture(nextScheduledFuture)
.notificationTime(date)
.build();
logger.trace("Rescheduled {} to {}", this, nextDispatch);
return nextDispatch;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\purchasecandidate\reminder\PurchaseCandidateReminderScheduler.java | 1 |
请完成以下Java代码 | public PrintData getPrintData()
{
return m_pd;
} // getPrintData
/*************************************************************************/
/**
* Receive notification of the start of an element.
*
* @param uri namespace
* @param localName simple name
* @param qName qualified name
* @param attributes attributes
* @throws org.xml.sax.SAXException
*/
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws org.xml.sax.SAXException
{
if (qName.equals(PrintData.XML_TAG))
{
String name = attributes.getValue(PrintData.XML_ATTRIBUTE_NAME);
if (m_pd == null)
{
m_pd = new PrintData(m_ctx, name);
push(m_pd);
}
else
{
PrintData temp = new PrintData(m_ctx, name);
m_curPD.addNode(temp);
push(temp);
}
}
else if (qName.equals(PrintData.XML_ROW_TAG))
{
m_curPD.addRow(false, 0);
}
else if (qName.equals(PrintDataElement.XML_TAG))
{
m_curPDEname = attributes.getValue(PrintDataElement.XML_ATTRIBUTE_NAME);
m_curPDEvalue = new StringBuffer();
}
} // startElement
/**
* Receive notification of character data inside an element.
*
* @param ch buffer
* @param start start
* @param length length
* @throws SAXException
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
m_curPDEvalue.append(ch, start, length);
} // characters
/**
* Receive notification of the end of an element.
* @param uri namespace
* @param localName simple name | * @param qName qualified name
* @throws SAXException
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if (qName.equals(PrintData.XML_TAG))
{
pop();
}
else if (qName.equals(PrintDataElement.XML_TAG))
{
m_curPD.addNode(new PrintDataElement(m_curPDEname, m_curPDEvalue.toString(),0, null));
}
} // endElement
/*************************************************************************/
/** Stack */
private ArrayList<PrintData> m_stack = new ArrayList<PrintData>();
/**
* Push new PD on Stack and set m_cutPD
* @param newPD new PD
*/
private void push (PrintData newPD)
{
// add
m_stack.add(newPD);
m_curPD = newPD;
} // push
/**
* Pop last PD from Stack and set m_cutPD
*/
private void pop ()
{
// remove last
if (m_stack.size() > 0)
m_stack.remove(m_stack.size()-1);
// get previous
if (m_stack.size() > 0)
m_curPD = (PrintData)m_stack.get(m_stack.size()-1);
} // pop
} // PrintDataHandler | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductDbConfig {
@Bean
public DataSource productDataSource() {
return DataSourceBuilder.create()
.url("jdbc:h2:mem:productdb")
.username("sa")
.password("")
.driverClassName("org.h2.Driver")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean productEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(productDataSource())
.packages("com.baeldung.entity")
.persistenceUnit("productPU")
.properties(Map.of("hibernate.hbm2ddl.auto", "none"))
.build(); | }
@Bean
public PlatformTransactionManager productTransactionManager(
EntityManagerFactory productEntityManagerFactory) {
return new JpaTransactionManager(productEntityManagerFactory);
}
@PostConstruct
public void migrateProductDb() {
Flyway.configure()
.dataSource(productDataSource())
.locations("classpath:db/migration/productdb")
.load()
.migrate();
}
} | repos\tutorials-master\spring-boot-modules\flyway-multidb-springboot\src\main\java\com\baeldung\config\ProductDbConfig.java | 2 |
请完成以下Java代码 | public class WebApplicationUtil {
public static void setApplicationServer(String serverInfo) {
if (serverInfo != null && !serverInfo.isEmpty() ) {
// set the application server info globally for all engines in the container
if (PlatformDiagnosticsRegistry.getApplicationServer() == null) {
PlatformDiagnosticsRegistry.setApplicationServer(serverInfo);
}
}
}
public static void setLicenseKey(LicenseKeyDataImpl licenseKeyData) {
if (licenseKeyData != null) {
ProcessEngineProvider processEngineProvider = getProcessEngineProvider();
for (String engineName : processEngineProvider.getProcessEngineNames()) {
if (engineName != null) {
ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineProvider.getProcessEngine(engineName).getManagementService();
managementService.setLicenseKeyForDiagnostics(licenseKeyData);
}
}
}
} | /**
* Adds the web application name to the telemetry data of the engine.
*
* @param engineName
* the engine for which the web application usage should be indicated
* @param webapp
* the web application that is used with the engine
* @return whether the web application was successfully added or not
*/
public static boolean setWebapp(String engineName, String webapp) {
ProcessEngineProvider processEngineProvider = getProcessEngineProvider();
ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineProvider.getProcessEngine(engineName).getManagementService();
return managementService.addWebappToTelemetry(webapp);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\util\WebApplicationUtil.java | 1 |
请完成以下Java代码 | private void insertLogs(@NonNull final PInstanceId pInstanceId, @NonNull final List<ProcessInfoLog> logsToSave, @Nullable final String trxName)
{
final String sql = "INSERT INTO " + I_AD_PInstance_Log.Table_Name
+ " ("
+ I_AD_PInstance_Log.COLUMNNAME_AD_PInstance_ID
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_Log_ID
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_P_Date
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_P_Number
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_P_Msg
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_AD_Table_ID
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_Record_ID
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_AD_Issue_ID
+ ", "
+ I_AD_PInstance_Log.COLUMNNAME_Warnings
+ ")"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
for (final ProcessInfoLog log : logsToSave)
{
final Integer tableId = Optional.ofNullable(log.getTableRecordReference())
.map(ITableRecordReference::getAD_Table_ID)
.orElse(null);
final Integer recordId = Optional.ofNullable(log.getTableRecordReference())
.map(ITableRecordReference::getRecord_ID)
.orElse(null);
final Integer adIssueId = Optional.ofNullable(log.getAdIssueId())
.map(AdIssueId::getRepoId)
.orElse(null); | final Object[] sqlParams = new Object[] {
pInstanceId.getRepoId(),
log.getLog_ID(),
log.getP_Date(),
log.getP_Number(),
log.getP_Msg(),
tableId,
recordId,
adIssueId,
log.getWarningMessages()
};
DB.setParameters(pstmt, sqlParams);
pstmt.addBatch();
}
pstmt.executeBatch();
logsToSave.forEach(ProcessInfoLog::markAsSavedInDB);
}
catch (final SQLException e)
{
// log only, don't fail
logger.error("Error while saving the process log lines", e);
}
finally
{
DB.close(pstmt);
}
DB.executeUpdateAndThrowExceptionOnFail(SQL_DeleteFrom_AD_PInstance_SelectedIncludedRecords, new Object[] { pInstanceId }, ITrx.TRXNAME_ThreadInherited);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADPInstanceDAO.java | 1 |
请完成以下Java代码 | public void setUpdateObjectIdentity(String updateObjectIdentity) {
this.updateObjectIdentity = updateObjectIdentity;
}
/**
* @param foreignKeysInDatabase if false this class will perform additional FK
* constrain checking, which may cause deadlocks (the default is true, so deadlocks
* are avoided but the database is expected to enforce FKs)
*/
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
this.foreignKeysInDatabase = foreignKeysInDatabase;
}
@Override
public void setAclClassIdSupported(boolean aclClassIdSupported) {
super.setAclClassIdSupported(aclClassIdSupported);
if (aclClassIdSupported) {
// Change the default insert if it hasn't been overridden
if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) {
this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID;
}
else {
log.debug("Insert class statement has already been overridden, so not overridding the default"); | }
}
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcMutableAclService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SalesOrderLine
{
OrderAndLineId id;
@Getter(AccessLevel.NONE)
SalesOrder order;
@Getter(AccessLevel.NONE)
OrderLine orderLine;
Quantity deliveredQty;
@Builder
private SalesOrderLine(
@NonNull final SalesOrder order,
@NonNull final OrderLine orderLine,
@NonNull final Quantity deliveredQty)
{
this.order = order;
this.orderLine = orderLine;
this.deliveredQty = deliveredQty;
final OrderLineId orderLineId = orderLine.getId();
this.id = orderLineId != null ? OrderAndLineId.of(orderLine.getOrderId(), orderLineId) : null;
}
public ZonedDateTime getPreparationDate()
{
return order.getPreparationDate();
}
public OrgId getOrgId()
{
return orderLine.getOrgId();
}
public WarehouseId getWarehouseId()
{
return orderLine.getWarehouseId(); | }
public int getLine()
{
return orderLine.getLine();
}
public ZonedDateTime getDatePromised()
{
return orderLine.getDatePromised();
}
public ProductId getProductId()
{
return orderLine.getProductId();
}
public AttributeSetInstanceId getAsiId()
{
return orderLine.getAsiId();
}
public Quantity getOrderedQty()
{
return orderLine.getOrderedQty();
}
public ProductPrice getPriceActual()
{
return orderLine.getPriceActual();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\SalesOrderLine.java | 2 |
请完成以下Java代码 | public float getScaleFactor() {
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return m_scaleFactor;
}
/**
* @author teo_sarca - [ 1673590 ] report table - barcode overflows over next fields
* @return can this element overflow over the next fields
*/
public boolean isAllowOverflow() { //
return m_allowOverflow;
}
/**
* Paint Element
* @param g2D graphics
* @param pageNo page no
* @param pageStart page start
* @param ctx context
* @param isView view
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (!m_valid || m_barcode == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
try {
int w = m_barcode.getWidth();
int h = m_barcode.getHeight();
// draw barcode to buffer | BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D temp = (Graphics2D) image.getGraphics();
m_barcode.draw(temp, 0, 0);
// scale barcode and paint
AffineTransform transform = new AffineTransform();
transform.translate(x,y);
transform.scale(m_scaleFactor, m_scaleFactor);
g2D.drawImage(image, transform, this);
} catch (OutputException e) {
}
} // paint
/**
* String Representation
* @return info
*/
public String toString ()
{
if (m_barcode == null)
return super.toString();
return super.toString() + " " + m_barcode.getData();
} // toString
} // BarcodeElement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\BarcodeElement.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getLatitude() {
return lattitude;
}
public void setLatitude(double latitude) {
this.lattitude = latitude;
}
public double getLongitude() {
return longitude;
} | public void setLongitude(double longitude) {
this.longitude = longitude;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Hotel hotel = (Hotel) o;
if (Double.compare(hotel.lattitude, lattitude) != 0) return false;
if (Double.compare(hotel.longitude, longitude) != 0) return false;
if (deleted != hotel.deleted) return false;
if (!Objects.equals(id, hotel.id)) return false;
if (!Objects.equals(name, hotel.name)) return false;
if (!Objects.equals(rating, hotel.rating)) return false;
if (!Objects.equals(city, hotel.city)) return false;
return Objects.equals(address, hotel.address);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\ttl\model\Hotel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static ScannableCodeFormatPart fromRecord(@NotNull final I_C_ScannableCode_Format_Part record)
{
final ScannableCodeFormatPartType type = ScannableCodeFormatPartType.ofCode(record.getDataType());
final ScannableCodeFormatPart.ScannableCodeFormatPartBuilder builder = ScannableCodeFormatPart.builder()
.startPosition(record.getStartNo())
.endPosition(record.getEndNo())
.type(type);
if (type == ScannableCodeFormatPartType.Constant)
{
builder.constantValue(record.getConstantValue());
}
else if (type.isDate())
{
builder.dateFormat(PatternedDateTimeFormatter.ofNullablePattern((record.getDataFormat())));
}
return builder.build();
}
public ScannableCodeFormat create(@NotNull final ScannableCodeFormatCreateRequest request)
{
final I_C_ScannableCode_Format record = InterfaceWrapperHelper.newInstance(I_C_ScannableCode_Format.class);
record.setName(request.getName());
record.setDescription(request.getDescription());
InterfaceWrapperHelper.saveRecord(record);
addToCache(record);
final ScannableCodeFormatId formatId = ScannableCodeFormatId.ofRepoId(record.getC_ScannableCode_Format_ID());
request.getParts().forEach(part -> createPart(part, formatId)); | return getById(formatId);
}
private void createPart(@NotNull final ScannableCodeFormatCreateRequest.Part part, @NotNull final ScannableCodeFormatId formatId)
{
final I_C_ScannableCode_Format_Part record = InterfaceWrapperHelper.newInstance(I_C_ScannableCode_Format_Part.class);
record.setC_ScannableCode_Format_ID(formatId.getRepoId());
record.setStartNo(part.getStartPosition());
record.setEndNo(part.getEndPosition());
record.setDataType(part.getType().getCode());
record.setDataFormat(PatternedDateTimeFormatter.toPattern(part.getDateFormat()));
record.setConstantValue(part.getConstantValue());
record.setDecimalPointPosition(part.getDecimalPointPosition());
record.setDescription(part.getDescription());
InterfaceWrapperHelper.saveRecord(record);
addToCache(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\repository\ScannableCodeFormatLoaderAndSaver.java | 2 |
请完成以下Java代码 | public Company post(@RequestBody Company company) {
return companyRepo.insert(company);
}
@PutMapping("/company")
public Company put(@RequestBody Company company) {
return companyRepo.save(company);
}
@GetMapping("/company/{id}")
public Optional<Company> getCompany(@PathVariable String id) {
return companyRepo.findById(id);
}
@PostMapping("/customer")
public Customer post(@RequestBody Customer customer) {
return customerRepo.insert(customer);
} | @GetMapping("/customer/{id}")
public Optional<Customer> getCustomer(@PathVariable String id) {
return customerRepo.findById(id);
}
@PostMapping("/asset")
public Asset post(@RequestBody Asset asset) {
return assetRepo.insert(asset);
}
@GetMapping("/asset/{id}")
public Optional<Asset> getAsset(@PathVariable String id) {
return assetRepo.findById(id);
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\unique\field\web\UniqueFieldController.java | 1 |
请完成以下Java代码 | public static String escape(final String str)
{
if (Check.isEmpty(str, true))
{
return str;
}
return str.replace(PARAMETER_TAG, PARAMETER_DOUBLE_TAG);
}
private StringExpressionCompiler()
{
super();
}
@Override
protected IStringExpression getNullExpression()
{
return IStringExpression.NULL;
} | @Override
protected IStringExpression createConstantExpression(final ExpressionContext context, final String expressionStr)
{
return ConstantStringExpression.of(expressionStr);
}
@Override
protected IStringExpression createSingleParamaterExpression(final ExpressionContext context, final String expressionStr, final CtxName parameter)
{
return new SingleParameterStringExpression(expressionStr, parameter);
}
@Override
protected IStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks)
{
return new StringExpression(expressionStr, expressionChunks);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionCompiler.java | 1 |
请完成以下Java代码 | public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutElementGroupDescriptor.Builder.class);
private String internalName;
private LayoutType layoutType;
public Integer columnCount = null;
private final List<DocumentLayoutElementLineDescriptor.Builder> elementLinesBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("layoutType", layoutType)
.add("elementsLines-count", elementLinesBuilders.size())
.toString();
}
public DocumentLayoutElementGroupDescriptor build()
{
final DocumentLayoutElementGroupDescriptor result = new DocumentLayoutElementGroupDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result;
}
private List<DocumentLayoutElementLineDescriptor> buildElementLines()
{
return elementLinesBuilders
.stream()
.map(elementLinesBuilder -> elementLinesBuilder.build())
.collect(GuavaCollectors.toImmutableList());
}
public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
public Builder setLayoutType(final LayoutType layoutType)
{
this.layoutType = layoutType;
return this;
}
public Builder setLayoutType(final String layoutTypeStr)
{
layoutType = LayoutType.fromNullable(layoutTypeStr);
return this;
}
public Builder setColumnCount(final int columnCount)
{ | this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1);
return this;
}
public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder)
{
elementLinesBuilders.add(elementLineBuilder);
return this;
}
public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders)
{
elementLinesBuilders.addAll(elementLineBuilders);
return this;
}
public boolean hasElementLines()
{
return !elementLinesBuilders.isEmpty();
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public ESProductDO setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public ESProductDO setName(String name) {
this.name = name;
return this;
}
public String getSellPoint() {
return sellPoint;
}
public ESProductDO setSellPoint(String sellPoint) {
this.sellPoint = sellPoint;
return this;
}
public String getDescription() {
return description;
}
public ESProductDO setDescription(String description) {
this.description = description;
return this;
}
public Integer getCid() {
return cid;
}
public ESProductDO setCid(Integer cid) {
this.cid = cid;
return this;
} | public String getCategoryName() {
return categoryName;
}
public ESProductDO setCategoryName(String categoryName) {
this.categoryName = categoryName;
return this;
}
@Override
public String toString() {
return "ProductDO{" +
"id=" + id +
", name='" + name + '\'' +
", sellPoint='" + sellPoint + '\'' +
", description='" + description + '\'' +
", cid=" + cid +
", categoryName='" + categoryName + '\'' +
'}';
}
} | repos\SpringBoot-Labs-master\lab-15-spring-data-es\lab-15-spring-data-jest\src\main\java\cn\iocoder\springboot\lab15\springdatajest\dataobject\ESProductDO.java | 1 |
请完成以下Java代码 | public Object getParameterComponent(final int index)
{
return null;
}
@Override
public Object getParameterToComponent(final int index)
{
return null;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
return new String[0];
}
@Override
public String getText()
{
return null;
}
@Override
public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet())
{
final Integer recordId = e.getKey();
if (recordId == null || recordId <= 0)
{
continue;
}
final Integer asiId = e.getValue();
if (asiId == null || asiId <= 0)
{
continue;
} | final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder();
productQtyBuilder.setSource(recordId, asiId);
builders.addGridTabRowBuilder(recordId, productQtyBuilder);
}
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel);
editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext);
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java | 1 |
请完成以下Java代码 | public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception {
if (!accepts(parentElement)) {
return;
}
FormProperty property = new FormProperty();
BpmnXMLUtil.addXMLLocation(property, xtr);
property.setId(xtr.getAttributeValue(null, ATTRIBUTE_FORM_ID));
property.setName(xtr.getAttributeValue(null, ATTRIBUTE_FORM_NAME));
property.setType(xtr.getAttributeValue(null, ATTRIBUTE_FORM_TYPE));
property.setVariable(xtr.getAttributeValue(null, ATTRIBUTE_FORM_VARIABLE));
property.setExpression(xtr.getAttributeValue(null, ATTRIBUTE_FORM_EXPRESSION));
property.setDefaultExpression(xtr.getAttributeValue(null, ATTRIBUTE_FORM_DEFAULT));
property.setDatePattern(xtr.getAttributeValue(null, ATTRIBUTE_FORM_DATEPATTERN));
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_FORM_REQUIRED))) {
property.setRequired(Boolean.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_FORM_REQUIRED)));
}
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_FORM_READABLE))) {
property.setReadable(Boolean.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_FORM_READABLE)));
}
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_FORM_WRITABLE))) {
property.setWriteable(Boolean.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_FORM_WRITABLE)));
}
boolean readyWithFormProperty = false;
try { | while (!readyWithFormProperty && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement() && ELEMENT_VALUE.equalsIgnoreCase(xtr.getLocalName())) {
FormValue value = new FormValue();
BpmnXMLUtil.addXMLLocation(value, xtr);
value.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID));
value.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
property.getFormValues().add(value);
} else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithFormProperty = true;
}
}
} catch (Exception e) {
LOGGER.warn("Error parsing form properties child elements", e);
}
if (parentElement instanceof UserTask) {
((UserTask) parentElement).getFormProperties().add(property);
} else {
((StartEvent) parentElement).getFormProperties().add(property);
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\FormPropertyParser.java | 1 |
请完成以下Java代码 | private static void unboxAndAppendToList(@Nullable final IValidationRule rule, @NonNull final ArrayList<IValidationRule> list)
{
if (rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
for (final IValidationRule childRule : compositeRule.rules)
{
unboxAndAppendToList(childRule, list);
}
}
else if (rule != null && !NullValidationRule.isNull(rule))
{
list.add(rule);
}
}
@SuppressWarnings("UnusedReturnValue")
public static final class Builder
{
private final List<IValidationRule> rules = new ArrayList<>();
private Builder() {}
public IValidationRule build()
{
if (rules.isEmpty())
{
return NullValidationRule.instance;
}
else if (rules.size() == 1)
{
return rules.get(0);
}
else
{
return new CompositeValidationRule(this);
}
}
public Builder add(final IValidationRule rule)
{
add(rule, false);
return this;
}
public Builder addExploded(final IValidationRule rule)
{
add(rule, true);
return this;
}
private Builder add(final IValidationRule rule, final boolean explodeComposite)
{ | // Don't add null rules
if (NullValidationRule.isNull(rule))
{
return this;
}
// Don't add if already exists
if (rules.contains(rule))
{
return this;
}
if (explodeComposite && rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
addAll(compositeRule.getValidationRules(), true);
}
else
{
rules.add(rule);
}
return this;
}
private Builder addAll(final Collection<IValidationRule> rules)
{
return addAll(rules, false);
}
private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite)
{
rules.forEach(includedRule -> add(includedRule, explodeComposite));
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java | 1 |
请完成以下Java代码 | private static ImmutableList<InstantInterval> removeGaps(@NonNull final List<AnnotatedPoint> annotatedPointList)
{
final List<InstantInterval> result = new ArrayList<>();
// iterate over the annotatedPointList
boolean isInterval = false;
boolean isGap = false;
Instant intervalStart = null;
for (final AnnotatedPoint point : annotatedPointList)
{
switch (point.type)
{
case Start:
if (!isGap)
{
intervalStart = point.value;
}
isInterval = true;
break;
case End:
if (!isGap)
{
//ignore the null warning as we are on the End case branch
result.add(InstantInterval.of(intervalStart, point.value));
}
isInterval = false;
break;
case GapStart:
if (isInterval)
{
result.add(InstantInterval.of(intervalStart, point.value));
}
isGap = true;
break;
case GapEnd:
if (isInterval)
{
intervalStart = point.value;
}
isGap = false;
break;
}
}
return ImmutableList.copyOf(result);
}
@Value
@Builder | private static class AnnotatedPoint implements Comparable<AnnotatedPoint>
{
@NonNull
Instant value;
@NonNull
PointType type;
public static AnnotatedPoint of(@NonNull final Instant instant, @NonNull final PointType type)
{
return AnnotatedPoint.builder()
.value(instant)
.type(type)
.build();
}
@Override
public int compareTo(@NonNull final AnnotatedPoint other)
{
if (other.value.compareTo(this.value) == 0)
{
return this.type.ordinal() < other.type.ordinal() ? -1 : 1;
}
else
{
return this.value.compareTo(other.value);
}
}
// the order is important here, as if multiple points have the same value
// this is the order in which we deal with them
public enum PointType
{
End, GapEnd, GapStart, Start
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\IntervalUtils.java | 1 |
请完成以下Java代码 | public InterestType1Choice getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link InterestType1Choice }
*
*/
public void setTp(InterestType1Choice value) {
this.tp = value;
}
/**
* Gets the value of the rate property.
*
* @return
* possible object is
* {@link Rate3 }
*
*/
public Rate3 getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link Rate3 }
*
*/
public void setRate(Rate3 value) {
this.rate = value;
}
/**
* Gets the value of the frToDt property.
*
* @return
* possible object is
* {@link DateTimePeriodDetails }
*
*/
public DateTimePeriodDetails getFrToDt() {
return frToDt;
}
/**
* Sets the value of the frToDt property.
*
* @param value
* allowed object is
* {@link DateTimePeriodDetails }
*
*/
public void setFrToDt(DateTimePeriodDetails value) {
this.frToDt = value;
}
/**
* Gets the value of the rsn property. | *
* @return
* possible object is
* {@link String }
*
*/
public String getRsn() {
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRsn(String value) {
this.rsn = value;
}
/**
* Gets the value of the tax property.
*
* @return
* possible object is
* {@link TaxCharges2 }
*
*/
public TaxCharges2 getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxCharges2 }
*
*/
public void setTax(TaxCharges2 value) {
this.tax = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java | 1 |
请完成以下Java代码 | Mono<Map<String, String>> getIndexes(String sessionId) {
String sessionIndexesKey = getSessionIndexesKey(sessionId);
return this.sessionRedisOperations.opsForSet()
.members(sessionIndexesKey)
.cast(String.class)
.collectMap((indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[0],
(indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[1]);
}
Flux<String> getSessionIds(String indexName, String indexValue) {
String indexKey = getIndexKey(indexName, indexValue);
return this.sessionRedisOperations.opsForSet().members(indexKey).cast(String.class);
}
private void updateIndexKeyPrefix() {
this.indexKeyPrefix = this.namespace + "sessions:index:";
}
private String getSessionIndexesKey(String sessionId) {
return this.namespace + "sessions:" + sessionId + ":idx";
} | private String getIndexKey(String indexName, String indexValue) {
return this.indexKeyPrefix + indexName + ":" + indexValue;
}
void setNamespace(String namespace) {
Assert.hasText(namespace, "namespace cannot be empty");
this.namespace = namespace;
updateIndexKeyPrefix();
}
void setIndexResolver(IndexResolver<Session> indexResolver) {
Assert.notNull(indexResolver, "indexResolver cannot be null");
this.indexResolver = indexResolver;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionIndexer.java | 1 |
请完成以下Java代码 | public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** RatioElementType AD_Reference_ID=372 */
public static final int RATIOELEMENTTYPE_AD_Reference_ID=372;
/** Ratio = R */
public static final String RATIOELEMENTTYPE_Ratio = "R";
/** Constant = C */
public static final String RATIOELEMENTTYPE_Constant = "C";
/** Calculation = X */
public static final String RATIOELEMENTTYPE_Calculation = "X";
/** Account Value = A */
public static final String RATIOELEMENTTYPE_AccountValue = "A";
/** Set Element Type.
@param RatioElementType
Ratio Element Type
*/
public void setRatioElementType (String RatioElementType)
{
set_Value (COLUMNNAME_RatioElementType, RatioElementType);
}
/** Get Element Type.
@return Ratio Element Type
*/
public String getRatioElementType ()
{
return (String)get_Value(COLUMNNAME_RatioElementType);
}
/** RatioOperand AD_Reference_ID=373 */
public static final int RATIOOPERAND_AD_Reference_ID=373;
/** Plus = P */
public static final String RATIOOPERAND_Plus = "P";
/** Minus = N */
public static final String RATIOOPERAND_Minus = "N";
/** Multiply = M */
public static final String RATIOOPERAND_Multiply = "M";
/** Divide = D */ | public static final String RATIOOPERAND_Divide = "D";
/** Set Operand.
@param RatioOperand
Ratio Operand
*/
public void setRatioOperand (String RatioOperand)
{
set_Value (COLUMNNAME_RatioOperand, RatioOperand);
}
/** Get Operand.
@return Ratio Operand
*/
public String getRatioOperand ()
{
return (String)get_Value(COLUMNNAME_RatioOperand);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_RatioElement.java | 1 |
请完成以下Java代码 | public BigDecimal getRecognizedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Total Amount.
@param TotalAmt
Total Amount
*/
public void setTotalAmt (BigDecimal TotalAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Total Amount.
@return Total Amount
*/
public BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ValidCombination getUnEarnedRevenue_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getUnEarnedRevenue_Acct(), get_TrxName()); }
/** Set Unearned Revenue.
@param UnEarnedRevenue_Acct
Account for unearned revenue
*/ | public void setUnEarnedRevenue_Acct (int UnEarnedRevenue_Acct)
{
set_ValueNoCheck (COLUMNNAME_UnEarnedRevenue_Acct, Integer.valueOf(UnEarnedRevenue_Acct));
}
/** Get Unearned Revenue.
@return Account for unearned revenue
*/
public int getUnEarnedRevenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnEarnedRevenue_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Plan.java | 1 |
请完成以下Java代码 | public String getEmployeesByIdWithRequired(@PathVariable String id) {
return "ID: " + id;
}
@GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) {
if (id != null) {
return "ID: " + id;
} else {
return "ID missing";
}
}
@GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
if (id.isPresent()) {
return "ID: " + id.get();
} else {
return "ID missing";
}
}
@GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" })
@ResponseBody
public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
if (id.isPresent()) {
return "ID: " + id.get(); | } else {
return "ID: Default Employee";
}
}
@GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" })
@ResponseBody
public String getEmployeesByIdWithMap(@PathVariable Map<String, String> pathVarsMap) {
String id = pathVarsMap.get("id");
if (id != null) {
return "ID: " + id;
} else {
return "ID missing";
}
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\pathvariable\PathVariableAnnotationController.java | 1 |
请完成以下Java代码 | public class VerbindungTesten {
@XmlElement(namespace = "", required = true)
protected String clientSoftwareKennung;
/**
* Gets the value of the clientSoftwareKennung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientSoftwareKennung() {
return clientSoftwareKennung; | }
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerbindungTesten.java | 1 |
请完成以下Java代码 | private void executeNow(
@NonNull final Object po,
@NonNull final Pointcut pointcut,
final int timing)
{
if (AnnotatedModelInterceptorDisabler.get().isDisabled(pointcut))
{
logger.info("Not executing pointCut because it is disabled via sysconfig (name-prefix={}); pointcut={}",
AnnotatedModelInterceptorDisabler.SYS_CONFIG_NAME_PREFIX, pointcut);
return;
}
final Object model = InterfaceWrapperHelper.create(po, pointcut.getModelClass());
try
{
executeNow0(model, pointcut, timing);
}
catch (final Exception e)
{
throw appendHowtoDisableMessage(e, pointcut);
}
}
private static AdempiereException appendHowtoDisableMessage(
@NonNull final Exception e,
@NonNull final Pointcut pointcut)
{
final String parameterName = "HowtoDisableModelInterceptor";
final AdempiereException ae = AdempiereException.wrapIfNeeded(e);
if (!ae.hasParameter(parameterName))
{
final String howtoDisableMsg = AnnotatedModelInterceptorDisabler.createHowtoDisableMessage(pointcut);
ae.setParameter(parameterName, howtoDisableMsg);
}
return ae;
}
private void executeNow0(
@NonNull final Object model,
@NonNull final Pointcut pointcut,
final int timing) throws IllegalAccessException, InvocationTargetException
{
final Method method = pointcut.getMethod(); | // Make sure the method is accessible
if (!method.isAccessible())
{
method.setAccessible(true);
}
final Stopwatch stopwatch = Stopwatch.createStarted();
if (pointcut.isMethodRequiresTiming())
{
final Object timingParam = pointcut.convertToMethodTimingParameterType(timing);
method.invoke(annotatedObject, model, timingParam);
}
else
{
method.invoke(annotatedObject, model);
}
logger.trace("Executed in {}: {} (timing={}) on {}", stopwatch, pointcut, timing, model);
}
/**
* @return true if timing is change (before, after)
*/
private static boolean isTimingChange(final int timing)
{
return ModelValidator.TYPE_BEFORE_CHANGE == timing
|| ModelValidator.TYPE_AFTER_CHANGE == timing
|| ModelValidator.TYPE_AFTER_CHANGE_REPLICATION == timing;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AnnotatedModelInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getRetentionShardDuration() {
return this.retentionShardDuration;
}
public void setRetentionShardDuration(@Nullable String retentionShardDuration) {
this.retentionShardDuration = retentionShardDuration;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isCompressed() {
return this.compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public boolean isAutoCreateDb() {
return this.autoCreateDb;
}
public void setAutoCreateDb(boolean autoCreateDb) {
this.autoCreateDb = autoCreateDb;
}
public @Nullable InfluxApiVersion getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(@Nullable InfluxApiVersion apiVersion) {
this.apiVersion = apiVersion;
}
public @Nullable String getOrg() {
return this.org; | }
public void setOrg(@Nullable String org) {
this.org = org;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxProperties.java | 2 |
请完成以下Java代码 | public class CaseInstanceDto extends LinkableDto {
protected String id;
protected String caseDefinitionId;
protected String businessKey;
protected String tenantId;
protected boolean active;
protected boolean completed;
protected boolean terminated;
public String getId() {
return id;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getBusinessKey() {
return businessKey;
}
public String getTenantId() {
return tenantId;
}
public boolean isActive() {
return active;
}
public boolean isCompleted() {
return completed;
}
public boolean isTerminated() {
return terminated;
} | public static CaseInstanceDto fromCaseInstance(CaseInstance instance) {
CaseInstanceDto result = new CaseInstanceDto();
result.id = instance.getId();
result.caseDefinitionId = instance.getCaseDefinitionId();
result.businessKey = instance.getBusinessKey();
result.tenantId = instance.getTenantId();
result.active = instance.isActive();
result.completed = instance.isCompleted();
result.terminated = instance.isTerminated();
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\CaseInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Todo {
public Todo() {
}
public Todo(int id, String username, String description, LocalDate targetDate, boolean done) {
super();
this.id = id;
this.username = username;
this.description = description;
this.targetDate = targetDate;
this.done = done;
}
@Id
@GeneratedValue
private int id;
private String username;
@Size(min=10, message="Enter at least 10 characters")
private String description;
private LocalDate targetDate;
private boolean done;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} | public LocalDate getTargetDate() {
return targetDate;
}
public void setTargetDate(LocalDate targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
@Override
public String toString() {
return "Todo [id=" + id + ", username=" + username + ", description=" + description + ", targetDate="
+ targetDate + ", done=" + done + "]";
}
} | repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\Todo.java | 2 |
请完成以下Java代码 | public class StartSubProcessInstanceBeforeContext extends AbstractStartProcessInstanceBeforeContext {
protected ExecutionEntity callActivityExecution;
protected List<IOParameter> inParameters;
protected boolean inheritVariables;
public StartSubProcessInstanceBeforeContext() {
}
public StartSubProcessInstanceBeforeContext(String businessKey, String businessStatus, String processInstanceName, Map<String, Object> variables,
Map<String, Object> transientVariables, ExecutionEntity callActivityExecution, List<IOParameter> inParameters, boolean inheritVariables,
String initialActivityId, FlowElement initialFlowElement, Process process, ProcessDefinition processDefinition) {
super(businessKey, businessStatus, processInstanceName, variables, transientVariables, initialActivityId, initialFlowElement, process,
processDefinition);
this.callActivityExecution = callActivityExecution;
this.inParameters = inParameters;
this.inheritVariables = inheritVariables;
}
public ExecutionEntity getCallActivityExecution() { | return callActivityExecution;
}
public void setCallActivityExecution(ExecutionEntity callActivityExecution) {
this.callActivityExecution = callActivityExecution;
}
public List<IOParameter> getInParameters() {
return inParameters;
}
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
public boolean isInheritVariables() {
return inheritVariables;
}
public void setInheritVariables(boolean inheritVariables) {
this.inheritVariables = inheritVariables;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\StartSubProcessInstanceBeforeContext.java | 1 |
请完成以下Java代码 | public void setCountryCode(final String countryCode)
{
this.countryCode = countryCode;
this.countryCodeSet = true;
}
public void setGln(final String gln)
{
this.gln = gln;
this.glnSet = true;
}
public void setShipTo(final Boolean shipTo)
{
this.shipTo = shipTo;
this.shipToSet = true;
}
public void setShipToDefault(final Boolean shipToDefault)
{
this.shipToDefault = shipToDefault;
this.shipToDefaultSet = true;
}
public void setBillTo(final Boolean billTo)
{
this.billTo = billTo;
this.billToSet = true; | }
public void setBillToDefault(final Boolean billToDefault)
{
this.billToDefault = billToDefault;
this.billToDefaultSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestLocation.java | 1 |
请完成以下Java代码 | public class Person {
private Long id;
private String name;
public Person() {
super();
}
public Person(String name) {
super();
this.name = name;
}
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;
}
} | repos\springBoot-master\springboot-springCloud\ui\src\main\java\com\abel\bean\Person.java | 1 |
请完成以下Java代码 | public class Doc_Movement extends Doc<DocLine_Movement>
{
public Doc_Movement(final AcctDocContext ctx)
{
super(ctx, DocBaseType.MaterialMovement);
}
@Override
protected void loadDocumentDetails()
{
setNoCurrency();
final I_M_Movement move = getModel(I_M_Movement.class);
setDateDoc(move.getMovementDate());
setDateAcct(move.getMovementDate());
// m_Reversal_ID = move.getReversal_ID();// store original (voided/reversed) document
// m_DocStatus = move.getDocStatus();
setDocLines(loadLines(move));
}
private List<DocLine_Movement> loadLines(final I_M_Movement movement)
{
return Services.get(IMovementDAO.class)
.retrieveLines(movement)
.stream()
.map(movementLine -> new DocLine_Movement(movementLine, this))
.collect(ImmutableList.toImmutableList());
}
/**
* Get Balance
*
* @return balance (ZERO) - always balanced
*/
@Override
public BigDecimal getBalance()
{
return BigDecimal.ZERO;
}
/**
* Create Facts (the accounting logic) for
* MMM.
*
* <pre>
* Movement
* Inventory DR CR
* InventoryTo DR CR
* </pre>
*
* @param as account schema
* @return Fact
*/
@Override
public List<Fact> createFacts(final AcctSchema as)
{
final Fact fact = new Fact(this, as, PostingType.Actual);
setC_Currency_ID(as.getCurrencyId());
getDocLines().forEach(line -> createFactsForMovementLine(fact, line)); | return ImmutableList.of(fact);
}
private void createFactsForMovementLine(final Fact fact, final DocLine_Movement line)
{
final AcctSchema as = fact.getAcctSchema();
final MoveCostsResult costs = line.getCreateCosts(as);
//
// Inventory CR/DR (from locator)
final CostAmount outboundCosts = costs.getOutboundAmountToPost(as);
fact.createLine()
.setDocLine(line)
.setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as))
.setAmtSourceDrOrCr(outboundCosts.toMoney()) // from (-) CR
.setQty(line.getQty().negate()) // outgoing
.locatorId(line.getM_Locator_ID())
.activityId(line.getActivityFromId())
.buildAndAdd();
//
// InventoryTo DR/CR (to locator)
final CostAmount inboundCosts = costs.getInboundAmountToPost(as);
fact.createLine()
.setDocLine(line)
.setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as))
.setAmtSourceDrOrCr(inboundCosts.toMoney()) // to (+) DR
.setQty(line.getQty()) // incoming
.locatorId(line.getM_LocatorTo_ID())
.activityId(line.getActivityId())
.buildAndAdd();
}
} // Doc_Movement | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Movement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class DefaultPrimitiveTypeVisitor extends TypeKindVisitor8<Object, Void> {
static final DefaultPrimitiveTypeVisitor INSTANCE = new DefaultPrimitiveTypeVisitor();
@Override
public Object visitPrimitiveAsBoolean(PrimitiveType type, Void parameter) {
return false;
}
@Override
public Object visitPrimitiveAsByte(PrimitiveType type, Void parameter) {
return (byte) 0;
}
@Override
public Object visitPrimitiveAsShort(PrimitiveType type, Void parameter) {
return (short) 0;
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, Void parameter) {
return 0;
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, Void parameter) {
return 0L;
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, Void parameter) {
return null;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, Void parameter) {
return 0F;
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, Void parameter) {
return 0D;
}
}
/**
* Visitor that gets the default using coercion.
*/
private static final class DefaultValueCoercionTypeVisitor extends TypeKindVisitor8<Object, String> {
static final DefaultValueCoercionTypeVisitor INSTANCE = new DefaultValueCoercionTypeVisitor();
private <T extends Number> T parseNumber(String value, Function<String, T> parser,
PrimitiveType primitiveType) {
try {
return parser.apply(value);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(
String.format("Invalid %s representation '%s'", primitiveType, value));
}
}
@Override
public Object visitPrimitiveAsBoolean(PrimitiveType type, String value) {
return Boolean.parseBoolean(value); | }
@Override
public Object visitPrimitiveAsByte(PrimitiveType type, String value) {
return parseNumber(value, Byte::parseByte, type);
}
@Override
public Object visitPrimitiveAsShort(PrimitiveType type, String value) {
return parseNumber(value, Short::parseShort, type);
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, String value) {
return parseNumber(value, Integer::parseInt, type);
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, String value) {
return parseNumber(value, Long::parseLong, type);
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, String value) {
if (value.length() > 1) {
throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value));
}
return value;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, String value) {
return parseNumber(value, Float::parseFloat, type);
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, String value) {
return parseNumber(value, Double::parseDouble, type);
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ParameterPropertyDescriptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void addAuthorsWithBooks() {
Publisher publisher = publisherRepository.findByUrc(92284434);
Author author1 = new Author();
author1.setId(new AuthorId(publisher, "Alicia Tom"));
author1.setGenre("Anthology");
Author author2 = new Author();
author2.setId(new AuthorId(publisher, "Joana Nimar"));
author2.setGenre("History");
Book book1 = new Book();
book1.setIsbn("001-AT");
book1.setTitle("The book of swords");
Book book2 = new Book();
book2.setIsbn("002-AT");
book2.setTitle("Anthology of a day");
Book book3 = new Book();
book3.setIsbn("003-AT");
book3.setTitle("Anthology today");
author1.addBook(book1); // use addBook() helper
author1.addBook(book2);
author2.addBook(book3);
authorRepository.save(author1);
authorRepository.save(author2);
}
@Transactional(readOnly = true)
public void fetchAuthorByName() {
Author author = authorRepository.fetchByName("Alicia Tom"); | System.out.println(author);
}
@Transactional
public void removeBookOfAuthor() {
Publisher publisher = publisherRepository.findByUrc(92284434);
Author author = authorRepository.fetchWithBooks(new AuthorId(publisher, "Alicia Tom"));
author.removeBook(author.getBooks().get(0));
}
@Transactional
public void removeAuthor() {
Publisher publisher = publisherRepository.findByUrc(92284434);
authorRepository.deleteById(new AuthorId(publisher, "Alicia Tom"));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static DeploymentWithDefinitionsDto fromDeployment(DeploymentWithDefinitions deployment) {
DeploymentWithDefinitionsDto dto = new DeploymentWithDefinitionsDto();
dto.id = deployment.getId();
dto.name = deployment.getName();
dto.source = deployment.getSource();
dto.deploymentTime = deployment.getDeploymentTime();
dto.tenantId = deployment.getTenantId();
initDeployedResourceLists(deployment, dto);
return dto;
}
private static void initDeployedResourceLists(DeploymentWithDefinitions deployment, DeploymentWithDefinitionsDto dto) {
List<ProcessDefinition> deployedProcessDefinitions = deployment.getDeployedProcessDefinitions();
if (deployedProcessDefinitions != null) {
dto.deployedProcessDefinitions = new HashMap<String, ProcessDefinitionDto>();
for (ProcessDefinition processDefinition : deployedProcessDefinitions) {
dto.deployedProcessDefinitions
.put(processDefinition.getId(), ProcessDefinitionDto.fromProcessDefinition(processDefinition));
}
}
List<CaseDefinition> deployedCaseDefinitions = deployment.getDeployedCaseDefinitions();
if (deployedCaseDefinitions != null) {
dto.deployedCaseDefinitions = new HashMap<String, CaseDefinitionDto>();
for (CaseDefinition caseDefinition : deployedCaseDefinitions) { | dto.deployedCaseDefinitions
.put(caseDefinition.getId(), CaseDefinitionDto.fromCaseDefinition(caseDefinition));
}
}
List<DecisionDefinition> deployedDecisionDefinitions = deployment.getDeployedDecisionDefinitions();
if (deployedDecisionDefinitions != null) {
dto.deployedDecisionDefinitions = new HashMap<String, DecisionDefinitionDto>();
for (DecisionDefinition decisionDefinition : deployedDecisionDefinitions) {
dto.deployedDecisionDefinitions
.put(decisionDefinition.getId(), DecisionDefinitionDto.fromDecisionDefinition(decisionDefinition));
}
}
List<DecisionRequirementsDefinition> deployedDecisionRequirementsDefinitions = deployment.getDeployedDecisionRequirementsDefinitions();
if (deployedDecisionRequirementsDefinitions != null) {
dto.deployedDecisionRequirementsDefinitions = new HashMap<String, DecisionRequirementsDefinitionDto>();
for (DecisionRequirementsDefinition drd : deployedDecisionRequirementsDefinitions) {
dto.deployedDecisionRequirementsDefinitions
.put(drd.getId(), DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(drd));
}
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentWithDefinitionsDto.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void grantTaskAccess(@NonNull final I_AD_Role_PermRequest request)
{
final int AD_Task_ID = request.getAD_Task_ID();
final RoleId roleId = RoleId.ofRepoId(request.getAD_Role_ID());
final Role role = Services.get(IRoleDAO.class).getById(roleId);
Services.get(IUserRolePermissionsDAO.class)
.createTaskAccess(CreateTaskAccessRequest.builder()
.roleId(role.getId())
.clientId(role.getClientId())
.orgId(role.getOrgId())
.adTaskId(AD_Task_ID)
.readWrite(request.isReadWrite())
.build());
final I_AD_Task task = InterfaceWrapperHelper.loadOutOfTrx(AD_Task_ID, I_AD_Task.class);
logGranted(I_AD_Task.COLUMNNAME_AD_Task_ID, task.getName());
}
private void grantDocActionAccess(@NonNull final I_AD_Role_PermRequest request)
{
final DocTypeId docTypeId = DocTypeId.ofRepoId(request.getC_DocType_ID());
final String docAction = request.getDocAction();
final ADRefListItem docActionItem = ADReferenceService.get().retrieveListItemOrNull(X_C_Invoice.DOCACTION_AD_Reference_ID, docAction);
Check.assumeNotNull(docActionItem, "docActionItem is missing for {}", docAction);
final int docActionRefListId = docActionItem.getRefListId().getRepoId();
final RoleId roleId = RoleId.ofRepoId(request.getAD_Role_ID());
final Role role = Services.get(IRoleDAO.class).getById(roleId);
Services.get(IUserRolePermissionsDAO.class)
.createDocumentActionAccess(CreateDocActionAccessRequest.builder()
.roleId(role.getId())
.clientId(role.getClientId())
.orgId(role.getOrgId())
.docTypeId(docTypeId) | .docActionRefListId(docActionRefListId)
.readWrite(request.isReadWrite())
.build());
final I_C_DocType docType = Services.get(IDocTypeDAO.class).getById(docTypeId);
logGranted(I_C_DocType.COLUMNNAME_C_DocType_ID, docType.getName() + "/" + docAction);
}
private void logGranted(final String type, final ITranslatableString name)
{
logGranted(type, name.translate(Env.getAD_Language()));
}
private void logGranted(final String type, final String name)
{
Loggables
.getLoggableOrLogger(logger, Level.INFO)
.addLog("Access granted: " + Services.get(IMsgBL.class).translate(Env.getCtx(), type) + ":" + name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\RolePermGrandAccess.java | 2 |
请完成以下Java代码 | public class MMediaDeploy extends X_CM_MediaDeploy
{
/**
*
*/
private static final long serialVersionUID = -339938737506660238L;
/**
* Standard Constructor
* @param ctx context
* @param CM_MediaDeploy_ID id
* @param trxName transaction
*/
public MMediaDeploy (Properties ctx, int CM_MediaDeploy_ID, String trxName)
{
super (ctx, CM_MediaDeploy_ID, trxName);
} // MMediaDeploy
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName tansaction
*/
public MMediaDeploy (Properties ctx, ResultSet rs, String trxName)
{ | super (ctx, rs, trxName);
} // MMediaDeploy
/**
* Deployment Parent Constructor
* @param server server
* @param media media
*/
public MMediaDeploy (MMediaServer server, MMedia media)
{
this (server.getCtx(), 0, server.get_TrxName());
setCM_Media_Server_ID(server.getCM_Media_Server_ID());
setCM_Media_ID(media.getCM_Media_ID());
setClientOrg(server);
//
setIsDeployed(true);
setLastSynchronized(new Timestamp(System.currentTimeMillis()));
} // MMediaDeploy
} // MMediaDeploy | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMediaDeploy.java | 1 |
请完成以下Java代码 | public static String getDockerCoapPublishCommand(String protocol, String baseUrl, String host, String port, DeviceCredentials deviceCredentials) {
String coapCommand = getCoapPublishCommand(protocol, host, port, deviceCredentials);
if (coapCommand == null) {
return null;
}
StringBuilder coapDockerCommand = new StringBuilder();
coapDockerCommand.append(DOCKER_RUN).append(isLocalhost(host) ? ADD_DOCKER_INTERNAL_HOST : "").append(COAP_IMAGE);
if (isLocalhost(host)) {
coapCommand = coapCommand.replace(host, HOST_DOCKER_INTERNAL);
}
if (COAPS.equals(protocol)) {
coapDockerCommand.append("/bin/sh -c \"")
.append(getCurlPemCertCommand(baseUrl, protocol))
.append(" && ")
.append(coapCommand)
.append("\"");
} else {
coapDockerCommand.append(coapCommand);
}
return coapDockerCommand.toString();
}
public static String getHost(String baseUrl, DeviceConnectivityInfo properties, String protocol) throws URISyntaxException {
String initialHost = StringUtils.isBlank(properties.getHost()) ? baseUrl : properties.getHost();
InetAddress inetAddress;
String host = null;
if (VALID_URL_PATTERN.matcher(initialHost).matches()) {
host = new URI(initialHost).getHost();
}
if (host == null) {
host = initialHost;
}
try {
host = host.replaceAll("^https?://", "");
inetAddress = InetAddress.getByName(host);
} catch (UnknownHostException e) { | return host;
}
if (inetAddress instanceof Inet6Address) {
host = host.replaceAll("[\\[\\]]", "");
if (!MQTT.equals(protocol) && !MQTTS.equals(protocol)) {
host = "[" + host + "]";
}
}
return host;
}
public static String getPort(DeviceConnectivityInfo properties) {
return StringUtils.isBlank(properties.getPort()) ? "" : properties.getPort();
}
public static boolean isLocalhost(String host) {
try {
InetAddress inetAddress = InetAddress.getByName(host);
return inetAddress.isLoopbackAddress();
} catch (UnknownHostException e) {
return false;
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\DeviceConnectivityUtil.java | 1 |
请完成以下Java代码 | public static MTree_Node get (MTree_Base tree, int Node_ID)
{
MTree_Node retValue = null;
String sql = "SELECT * FROM AD_TreeNode WHERE AD_Tree_ID=? AND Node_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, tree.get_TrxName());
pstmt.setInt (1, tree.getAD_Tree_ID());
pstmt.setInt (2, Node_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
retValue = new MTree_Node (tree.getCtx(), rs, tree.get_TrxName());
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return retValue; | } // get
/** Static Logger */
private static Logger s_log = LogManager.getLogger(MTree_Node.class);
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MTree_Node (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MTree_Node
/**
* Full Constructor
* @param tree tree
* @param Node_ID node
*/
public MTree_Node (MTree_Base tree, int Node_ID)
{
super (tree.getCtx(), 0, tree.get_TrxName());
setClientOrg(tree);
setAD_Tree_ID (tree.getAD_Tree_ID());
setNode_ID(Node_ID);
// Add to root
setParent_ID(0);
setSeqNo (0);
} // MTree_Node
} // MTree_Node | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree_Node.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String get(String k) {
return null;
}
@Override
public boolean enabled() {
return obtain(GangliaProperties::isEnabled, GangliaConfig.super::enabled);
}
@Override
public Duration step() {
return obtain(GangliaProperties::getStep, GangliaConfig.super::step);
}
@Override
public TimeUnit durationUnits() {
return obtain(GangliaProperties::getDurationUnits, GangliaConfig.super::durationUnits);
}
@Override
public GMetric.UDPAddressingMode addressingMode() {
return obtain(GangliaProperties::getAddressingMode, GangliaConfig.super::addressingMode);
} | @Override
public int ttl() {
return obtain(GangliaProperties::getTimeToLive, GangliaConfig.super::ttl);
}
@Override
public String host() {
return obtain(GangliaProperties::getHost, GangliaConfig.super::host);
}
@Override
public int port() {
return obtain(GangliaProperties::getPort, GangliaConfig.super::port);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\ganglia\GangliaPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public boolean offer(E element) {
if (isNotFull()) {
int nextWriteSeq = writeSequence + 1;
data[nextWriteSeq % capacity] = element;
writeSequence++;
return true;
}
return false;
}
public E poll() {
if (isNotEmpty()) {
E nextValue = data[readSequence % capacity];
readSequence++;
return nextValue;
}
return null;
}
public int capacity() {
return capacity;
}
public int size() {
return (writeSequence - readSequence) + 1;
} | public boolean isEmpty() {
return writeSequence < readSequence;
}
public boolean isFull() {
return size() >= capacity;
}
private boolean isNotEmpty() {
return !isEmpty();
}
private boolean isNotFull() {
return !isFull();
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\circularbuffer\CircularBuffer.java | 1 |
请完成以下Spring Boot application配置 | server.port=80
# Mysql 数据源配置
spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# mybatis配置
mybatis.type-aliases-package=cn.codesheep.springbt_ehcache.entity
myb | atis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
spring.cache.ehcache.config=classpath:ehcache.xml | repos\Spring-Boot-In-Action-master\springbt_ehcache\src\main\resources\application.properties | 2 |
请完成以下Java代码 | protected Session doReadSession(Serializable sessionId) {
Session session = null;
HttpServletRequest request = ServletKit.getRequest();
if (request != null) {
String uri = request.getServletPath();
if (ServletKit.isStaticFile(uri)) {
return null;
}
session = (Session) request.getAttribute("session_" + sessionId);
}
if (session == null) {
session = super.doReadSession(sessionId);
}
if (session == null) {
session = (Session) cache().get(sessionId.toString());
}
return session;
}
/**
* 更新session的最后一次访问时间
*
* @param session
*/
@Override
protected void doUpdate(Session session) {
HttpServletRequest request = ServletKit.getRequest();
if (request != null) { | String uri = request.getServletPath();
if (ServletKit.isStaticFile(uri)) {
return;
}
}
super.doUpdate(session);
cache().put(session.getId().toString(), session);
logger.debug("{}", session.getAttribute("shiroUserId"));
}
/**
* 删除session
*
* @param session
*/
@Override
protected void doDelete(Session session) {
super.doDelete(session);
cache().remove(session.getId().toString());
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\RedisSessionDao.java | 1 |
请完成以下Java代码 | public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public List<AbstractProcessInstanceModificationCommand> getInstructions() {
return instructions;
} | public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotationInternal(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBuilderImpl.java | 1 |
请完成以下Java代码 | public boolean hasNext()
{
if (nextSet)
{
return true;
}
else
{
return setNextValid();
}
}
@Override
public E next()
{
if (!nextSet)
{
if (!setNextValid())
{
throw new NoSuchElementException();
}
}
nextSet = false;
return next;
}
/**
* Set next valid element
*
* @return true if next valid element was found and set
*/
private final boolean setNextValid()
{
while (iterator.hasNext()) | {
final E element = iterator.next();
if (predicate.test(element))
{
next = element;
nextSet = true;
return true;
}
}
return false;
}
/**
* @throws UnsupportedOperationException always
*/
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<E> getParentIterator()
{
return iterator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\FilterIterator.java | 1 |
请完成以下Java代码 | public String toString()
{
return "DunningContext ["
+ "dunningLevel=" + dunningLevel
+ ", dunningDate=" + dunningDate
+ ", trxName=" + trxName
+ ", config=" + dunningConfig
+ ", ctx=" + ctx
+ "]";
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
return trxName;
}
@Override
public ITrxRunConfig getTrxRunnerConfig()
{
return trxRunnerConfig;
}
@Override
public I_C_DunningLevel getC_DunningLevel()
{
return dunningLevel; | }
@Override
public IDunningConfig getDunningConfig()
{
return dunningConfig;
}
@Override
public Date getDunningDate()
{
if (dunningDate == null)
{
return dunningDate;
}
return (Date)dunningDate.clone();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningContext.java | 1 |
请完成以下Java代码 | public JobQuery orderByProcessDefinitionKey() {
return orderBy(JobQueryProperty.PROCESS_DEFINITION_KEY);
}
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public JobQuery orderByJobPriority() {
return orderBy(JobQueryProperty.PRIORITY);
}
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
//results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobCountByQueryCriteria(this);
}
@Override
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobsByQueryCriteria(this, page);
}
@Override
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
//getters //////////////////////////////////////////
public Set<String> getIds() {
return ids;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds; | }
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public boolean getAcquired() {
return acquired;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) {
if (app == null) {
app = MachineDiscovery.UNKNOWN_APP_NAME;
}
if (ip == null) {
return Result.ofFail(-1, "ip can't be null");
}
if (port == null) {
return Result.ofFail(-1, "port can't be null");
}
if (port == -1) {
logger.info("Receive heartbeat from " + ip + " but port not set yet");
return Result.ofFail(-1, "your port not set yet");
}
String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v;
version = version == null ? System.currentTimeMillis() : version;
try {
MachineInfo machineInfo = new MachineInfo(); | machineInfo.setApp(app);
machineInfo.setAppType(appType);
machineInfo.setHostname(hostname);
machineInfo.setIp(ip);
machineInfo.setPort(port);
machineInfo.setHeartbeatVersion(version);
machineInfo.setLastHeartbeat(System.currentTimeMillis());
machineInfo.setVersion(sentinelVersion);
appManagement.addMachine(machineInfo);
return Result.ofSuccessMsg("success");
} catch (Exception e) {
logger.error("Receive heartbeat error", e);
return Result.ofFail(-1, e.getMessage());
}
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\MachineRegistryController.java | 2 |
请完成以下Java代码 | public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger) {
this.switchUserAuthorityChanger = switchUserAuthorityChanger;
}
/**
* Sets the {@link UserDetailsChecker} that is called on the target user whenever the
* user is switched.
* @param userDetailsChecker the {@link UserDetailsChecker} that checks the status of
* the user that is being switched to. Defaults to
* {@link AccountStatusUserDetailsChecker}.
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
this.userDetailsChecker = userDetailsChecker;
}
/**
* Allows the parameter containing the username to be customized.
* @param usernameParameter the parameter name. Defaults to {@code username}
*/
public void setUsernameParameter(String usernameParameter) {
this.usernameParameter = usernameParameter;
}
/**
* Allows the role of the switchAuthority to be customized.
* @param switchAuthorityRole the role name. Defaults to
* {@link #ROLE_PREVIOUS_ADMINISTRATOR}
*/
public void setSwitchAuthorityRole(String switchAuthorityRole) {
Assert.notNull(switchAuthorityRole, "switchAuthorityRole cannot be null");
this.switchAuthorityRole = switchAuthorityRole;
} | /**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* switch user success. The default is
* {@link RequestAttributeSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
* @since 5.7.7
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
private static RequestMatcher createMatcher(String pattern) {
return pathPattern(HttpMethod.POST, pattern);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilter.java | 1 |
请完成以下Java代码 | private void enqueueGenerateSchedulesAfterCommit(@NonNull final I_C_Order orderRecord)
{
final OrderId orderId = OrderId.ofRepoId(orderRecord.getC_Order_ID());
if (isEligibleForAutoProcessing(orderRecord))
{
Loggables.withLogger(logger, Level.DEBUG).addLog("OrderId: {} qualified for auto ship and invoice! Enqueueing order.", orderId);
final String trxName = InterfaceWrapperHelper.getTrxName(orderRecord);
completeShipAndInvoiceEnqueuer.enqueue(orderId, trxName);
}
else
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Schedule generating missing shipments for orderId: {}", orderId);
CreateMissingShipmentSchedulesWorkpackageProcessor.scheduleIfNotPostponed(orderRecord);
}
}
private boolean isEligibleForAutoProcessing(@NonNull final I_C_Order orderRecord)
{
final boolean featureEnabled = sysConfigBL.getBooleanValue(SYS_Config_AUTO_SHIP_AND_INVOICE, false, orderRecord.getAD_Client_ID(), orderRecord.getAD_Org_ID());
final DeliveryRule deliveryRule = DeliveryRule.ofCode(orderRecord.getDeliveryRule());
final boolean canDoAutoShipAndInvoice = featureEnabled && deliveryRule.isBasedOnDelivery(); | if (!canDoAutoShipAndInvoice)
{
return false;
}
//dev-note: check to see if the order is not already involved in another async job
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(orderRecord.getC_Async_Batch_ID());
if (asyncBatchId == null)
{
return true;
}
return !asyncBatchObserver.isAsyncBatchObserved(asyncBatchId);
}
} | repos\metasfresh-new_dawn_uat\backend\de-metas-salesorder\src\main\java\de\metas\salesorder\interceptor\C_Order_AutoProcess_Async.java | 1 |
请完成以下Java代码 | public int getCode() {
return code;
}
/**
* Sets the 编号.
*
* @param code
* the new 编号
*/
public void setCode(int code) {
this.code = code;
}
/**
* Gets the 信息.
*
* @return the 信息
*/
public String getMessage() {
return message;
}
/**
* Sets the 信息.
*
* @param message
* the new 信息
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Sets the 编号 ,返回自身的引用.
*
* @param code
* the new 编号
*
* @return the wrapper
*/
public Wrapper<T> code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 ,返回自身的引用.
* | * @param message
* the new 信息
*
* @return the wrapper
*/
public Wrapper<T> message(String message) {
this.setMessage(message);
return this;
}
/**
* Sets the 结果数据 ,返回自身的引用.
*
* @param result
* the new 结果数据
*
* @return the wrapper
*/
public Wrapper<T> result(T result) {
this.setData(result);
return this;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\wrapper\Wrapper.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder bpmnModelBuilder) {
ModelElementTypeBuilder typeBuilder = bpmnModelBuilder.defineType(CallableElement.class, BPMN_ELEMENT_CALLABLE_ELEMENT)
.namespaceUri(BPMN20_NS)
.extendsType(RootElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ModelElementInstance>() {
public ModelElementInstance newInstance(ModelTypeInstanceContext instanceContext) {
return new CallableElementImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
supportedInterfaceRefCollection = sequenceBuilder.elementCollection(SupportedInterfaceRef.class)
.qNameElementReferenceCollection(Interface.class)
.build();
ioSpecificationChild = sequenceBuilder.element(IoSpecification.class)
.build();
ioBindingCollection = sequenceBuilder.elementCollection(IoBinding.class)
.build();
typeBuilder.build();
}
public CallableElementImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
} | public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Collection<Interface> getSupportedInterfaces() {
return supportedInterfaceRefCollection.getReferenceTargetElements(this);
}
public IoSpecification getIoSpecification() {
return ioSpecificationChild.getChild(this);
}
public void setIoSpecification(IoSpecification ioSpecification) {
ioSpecificationChild.setChild(this, ioSpecification);
}
public Collection<IoBinding> getIoBindings() {
return ioBindingCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallableElementImpl.java | 1 |
请完成以下Java代码 | public static Timestamp asDayTimestamp()
{
final GregorianCalendar cal = asGregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Timestamp(cal.getTimeInMillis());
}
public static Instant asInstant()
{
return Instant.ofEpochMilli(millis());
}
public static LocalDateTime asLocalDateTime()
{
return asZonedDateTime().toLocalDateTime();
}
@NonNull
public static LocalDate asLocalDate()
{
return asLocalDate(zoneId());
}
@NonNull
public static LocalDate asLocalDate(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId).toLocalDate();
} | public static ZonedDateTime asZonedDateTime()
{
return asZonedDateTime(zoneId());
}
public static ZonedDateTime asZonedDateTimeAtStartOfDay()
{
return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS);
}
public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId)
.toLocalDate()
.atTime(LocalTime.MAX)
.atZone(zoneId);
}
public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId)
{
return asInstant().atZone(zoneId);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java | 1 |
请完成以下Java代码 | public List<TimescaleTsKvEntity> findAvg(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs) {
return getResultList(entityId, entityKey, timeBucket, startTs, endTs, FIND_AVG);
}
@SuppressWarnings("unchecked")
public List<TimescaleTsKvEntity> findMax(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs) {
return getResultList(entityId, entityKey, timeBucket, startTs, endTs, FIND_MAX);
}
@SuppressWarnings("unchecked")
public List<TimescaleTsKvEntity> findMin(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs) {
return getResultList(entityId, entityKey, timeBucket, startTs, endTs, FIND_MIN);
}
@SuppressWarnings("unchecked")
public List<TimescaleTsKvEntity> findSum(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs) {
return getResultList(entityId, entityKey, timeBucket, startTs, endTs, FIND_SUM); | }
@SuppressWarnings("unchecked")
public List<TimescaleTsKvEntity> findCount(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs) {
return getResultList(entityId, entityKey, timeBucket, startTs, endTs, FIND_COUNT);
}
private List getResultList(UUID entityId, int entityKey, long timeBucket, long startTs, long endTs, String query) {
return entityManager.createNamedQuery(query)
.setParameter("entityId", entityId)
.setParameter("entityKey", entityKey)
.setParameter("timeBucket", timeBucket)
.setParameter("startTs", startTs)
.setParameter("endTs", endTs)
.getResultList();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\timescale\AggregationRepository.java | 1 |
请完成以下Java代码 | public String getResolvedBy() {
return resolvedBy;
}
public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
}
public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId + | ", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java | 1 |
请完成以下Java代码 | public void setSalesLineId (final @Nullable String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class CloudFoundryClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition {
protected static final String CLOUD_FOUNDRY_NAME = "CloudFoundry";
protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for VMs";
@Override
protected String getCloudPlatformName() {
return CLOUD_FOUNDRY_NAME;
}
@Override
protected String getRuntimeEnvironmentName() {
return RUNTIME_ENVIRONMENT_NAME;
}
@Override
protected boolean isCloudPlatformActive(@NonNull Environment environment) {
return environment != null && CloudPlatform.CLOUD_FOUNDRY.isActive(environment);
}
}
public static class KubernetesClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition {
protected static final String KUBERNETES_NAME = "Kubernetes";
protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for K8S";
@Override
protected String getCloudPlatformName() {
return KUBERNETES_NAME;
}
@Override
protected String getRuntimeEnvironmentName() {
return RUNTIME_ENVIRONMENT_NAME;
}
@Override
protected boolean isCloudPlatformActive(@NonNull Environment environment) {
return environment != null && CloudPlatform.KUBERNETES.isActive(environment);
} | }
public static class StandaloneClusterAvailableCondition
extends ClusterAwareConfiguration.ClusterAwareCondition {
@Override
public synchronized boolean matches(@NonNull ConditionContext conditionContext,
@NonNull AnnotatedTypeMetadata typeMetadata) {
return isNotSupportedCloudPlatform(conditionContext)
&& super.matches(conditionContext, typeMetadata);
}
private boolean isNotSupportedCloudPlatform(@NonNull ConditionContext conditionContext) {
return conditionContext != null && isNotSupportedCloudPlatform(conditionContext.getEnvironment());
}
private boolean isNotSupportedCloudPlatform(@NonNull Environment environment) {
CloudPlatform activeCloudPlatform = environment != null
? CloudPlatform.getActive(environment)
: null;
return !isSupportedCloudPlatform(activeCloudPlatform);
}
private boolean isSupportedCloudPlatform(@NonNull CloudPlatform cloudPlatform) {
return cloudPlatform != null && SUPPORTED_CLOUD_PLATFORMS.contains(cloudPlatform);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAvailableConfiguration.java | 2 |
请完成以下Java代码 | public BigDecimal getApprovalAmt(final DocumentTableFields docFields)
{
return BigDecimal.ZERO;
}
@Override
public File createPDF(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public String completeIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
@Override
public void approveIt(final DocumentTableFields docFields)
{
}
@Override
public void rejectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void voidIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(forecast.getDocStatus());
if (docStatus.isClosedReversedOrVoided())
{
throw new AdempiereException("Document Closed: " + docStatus);
}
getLines(forecast).forEach(this::voidLine);
forecast.setProcessed(true);
forecast.setDocAction(IDocument.ACTION_None);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException(); | }
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setProcessed(false);
forecast.setDocAction(IDocument.ACTION_Complete);
}
@Override
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
return TimeUtil.asLocalDate(forecast.getDatePromised());
}
private void voidLine(@NonNull final I_M_ForecastLine line)
{
line.setQty(BigDecimal.ZERO);
line.setQtyCalculated(BigDecimal.ZERO);
InterfaceWrapperHelper.save(line);
}
private List<I_M_ForecastLine> getLines(@NonNull final I_M_Forecast forecast)
{
return forecastDAO.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\ForecastDocumentHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
EbayTaxReference ebayTaxReference = (EbayTaxReference)o;
return Objects.equals(this.name, ebayTaxReference.name) &&
Objects.equals(this.value, ebayTaxReference.value);
}
@Override
public int hashCode()
{
return Objects.hash(name, value);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class EbayTaxReference {\n"); | sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\EbayTaxReference.java | 2 |
请在Spring Boot框架中完成以下Java代码 | SecurityContextRepository getSecurityContextRepository() {
SecurityContextRepository securityContextRepository = getBuilder()
.getSharedObject(SecurityContextRepository.class);
if (securityContextRepository == null) {
securityContextRepository = new DelegatingSecurityContextRepository(
new RequestAttributeSecurityContextRepository(), new HttpSessionSecurityContextRepository());
}
return securityContextRepository;
}
@Override
@SuppressWarnings("unchecked")
public void configure(H http) {
SecurityContextRepository securityContextRepository = getSecurityContextRepository();
if (this.requireExplicitSave) {
SecurityContextHolderFilter securityContextHolderFilter = postProcess(
new SecurityContextHolderFilter(securityContextRepository));
securityContextHolderFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); | http.addFilter(securityContextHolderFilter);
}
else {
SecurityContextPersistenceFilter securityContextFilter = new SecurityContextPersistenceFilter(
securityContextRepository);
securityContextFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
SessionManagementConfigurer<?> sessionManagement = http.getConfigurer(SessionManagementConfigurer.class);
SessionCreationPolicy sessionCreationPolicy = (sessionManagement != null)
? sessionManagement.getSessionCreationPolicy() : null;
if (SessionCreationPolicy.ALWAYS == sessionCreationPolicy) {
securityContextFilter.setForceEagerSessionCreation(true);
http.addFilter(postProcess(new ForceEagerSessionCreationFilter()));
}
securityContextFilter = postProcess(securityContextFilter);
http.addFilter(securityContextFilter);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\SecurityContextConfigurer.java | 2 |
请完成以下Java代码 | class ConfigurationPropertySourcesCaching implements ConfigurationPropertyCaching {
private final @Nullable Iterable<ConfigurationPropertySource> sources;
ConfigurationPropertySourcesCaching(@Nullable Iterable<ConfigurationPropertySource> sources) {
this.sources = sources;
}
@Override
public void enable() {
forEach(ConfigurationPropertyCaching::enable);
}
@Override
public void disable() {
forEach(ConfigurationPropertyCaching::disable);
}
@Override
public void setTimeToLive(Duration timeToLive) {
forEach((caching) -> caching.setTimeToLive(timeToLive));
}
@Override
public void clear() {
forEach(ConfigurationPropertyCaching::clear);
}
@Override
public CacheOverride override() {
CacheOverrides override = new CacheOverrides();
forEach(override::add); | return override;
}
private void forEach(Consumer<ConfigurationPropertyCaching> action) {
if (this.sources != null) {
for (ConfigurationPropertySource source : this.sources) {
ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source);
if (caching != null) {
action.accept(caching);
}
}
}
}
/**
* Composite {@link CacheOverride}.
*/
private final class CacheOverrides implements CacheOverride {
private List<CacheOverride> overrides = new ArrayList<>();
void add(ConfigurationPropertyCaching caching) {
this.overrides.add(caching.override());
}
@Override
public void close() {
this.overrides.forEach(CacheOverride::close);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertySourcesCaching.java | 1 |
请完成以下Java代码 | public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() {
return activatePlanItemDefinitions;
}
public Set<MoveToAvailablePlanItemDefinitionMapping> getChangeToAvailableStatePlanItemDefinitions() {
return changeToAvailableStatePlanItemDefinitions;
}
public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() {
return terminatePlanItemDefinitions;
}
public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() {
return waitingForRepetitionPlanItemDefinitions;
}
public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() {
return removeWaitingForRepetitionPlanItemDefinitions;
}
public Set<ChangePlanItemIdMapping> getChangePlanItemIds() {
return changePlanItemIds;
} | public Set<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdsWithDefinitionId() {
return changePlanItemIdsWithDefinitionId;
}
public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() {
return changePlanItemDefinitionWithNewTargetIds;
}
public Map<String, Object> getCaseVariables() {
return caseVariables;
}
public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
return childInstanceTaskVariables;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\ChangePlanItemStateBuilderImpl.java | 1 |
请完成以下Java代码 | public void zoom()
{
log.info("");
//
adWindowId = null;
String ColumnName = null;
String SQL = null;
//
int lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_InOutLine_ID");
if (lineID > 0)
{
log.debug("M_InOutLine_ID=" + lineID);
if (Env.getContext(Env.getCtx(), m_WindowNo, "MovementType").startsWith("C"))
{
adWindowId = AdWindowId.ofRepoId(169); // Customer
}
else {
adWindowId = AdWindowId.ofRepoId(184); // Vendor
}
ColumnName = "M_InOut_ID";
SQL = "SELECT M_InOut_ID FROM M_InOutLine WHERE M_InOutLine_ID=?";
}
else
{
lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_InventoryLine_ID");
if (lineID > 0)
{
log.debug("M_InventoryLine_ID=" + lineID);
adWindowId = AdWindowId.ofRepoId(168);
ColumnName = "M_Inventory_ID";
SQL = "SELECT M_Inventory_ID FROM M_InventoryLine WHERE M_InventoryLine_ID=?";
}
else
{
lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_MovementLine_ID");
if (lineID > 0)
{
log.debug("M_MovementLine_ID=" + lineID);
adWindowId = AdWindowId.ofRepoId(170); | ColumnName = "M_Movement_ID";
SQL = "SELECT M_Movement_ID FROM M_MovementLine WHERE M_MovementLine_ID=?";
}
}
}
if (adWindowId == null)
{
return;
}
// Get Parent ID
final int parentID = DB.getSQLValueEx(ITrx.TRXNAME_None, SQL, lineID);
query = MQuery.getEqualQuery(ColumnName, parentID);
log.info("AD_Window_ID=" + adWindowId + " - " + query);
if (parentID <= 0)
{
log.error("No ParentValue - " + SQL + " - " + lineID);
}
} // zoom
protected final Lookup getLookup(final String columnName)
{
final GridTab gridTab = getGridTab();
final GridField gridField = gridTab.getField(columnName);
if (gridField == null)
{
return null;
}
return gridField.getLookup();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\TrxMaterial.java | 1 |
请完成以下Java代码 | private void validateScopes() {
if (CollectionUtils.isEmpty(this.scopes)) {
return;
}
for (String scope : this.scopes) {
Assert.isTrue(validateScope(scope), "scope \"" + scope + "\" contains invalid characters");
}
}
private static boolean validateScope(String scope) {
return scope == null || scope.chars()
.allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|| withinTheRangeOf(c, 0x5D, 0x7E));
}
private static boolean withinTheRangeOf(int c, int min, int max) {
return c >= min && c <= max;
}
private void validateRedirectUris() {
if (CollectionUtils.isEmpty(this.redirectUris)) {
return;
}
for (String redirectUri : this.redirectUris) {
Assert.isTrue(validateRedirectUri(redirectUri),
"redirect_uri \"" + redirectUri + "\" is not a valid redirect URI or contains fragment");
}
}
private void validatePostLogoutRedirectUris() {
if (CollectionUtils.isEmpty(this.postLogoutRedirectUris)) {
return;
} | for (String postLogoutRedirectUri : this.postLogoutRedirectUris) {
Assert.isTrue(validateRedirectUri(postLogoutRedirectUri), "post_logout_redirect_uri \""
+ postLogoutRedirectUri + "\" is not a valid post logout redirect URI or contains fragment");
}
}
private static boolean validateRedirectUri(String redirectUri) {
try {
URI validRedirectUri = new URI(redirectUri);
return validRedirectUri.getFragment() == null;
}
catch (URISyntaxException ex) {
return false;
}
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\RegisteredClient.java | 1 |
请完成以下Java代码 | public class IMPProcessorAdempiereProcessorAdapter implements AdempiereProcessor
{
private final I_IMP_Processor impProcessor;
public IMPProcessorAdempiereProcessorAdapter(@NonNull final I_IMP_Processor impProcessor)
{
this.impProcessor = impProcessor;
}
public I_IMP_Processor getIMP_Procesor()
{
return impProcessor;
}
@Override
public int getAD_Client_ID()
{
return impProcessor.getAD_Client_ID();
}
@Override
public String getName()
{
return impProcessor.getName();
}
@Override
public String getDescription()
{
return impProcessor.getDescription();
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(impProcessor);
}
@Override
public String getFrequencyType()
{
return impProcessor.getFrequencyType();
}
@Override
public int getFrequency()
{
return impProcessor.getFrequency();
}
@Override
public String getServerID()
{
return "ReplicationProcessor" + impProcessor.getIMP_Processor_ID();
}
@Override
public Timestamp getDateNextRun(boolean requery)
{
if (requery)
{
InterfaceWrapperHelper.refresh(impProcessor); | }
return impProcessor.getDateNextRun();
}
@Override
public void setDateNextRun(Timestamp dateNextWork)
{
impProcessor.setDateNextRun(dateNextWork);
}
@Override
public Timestamp getDateLastRun()
{
return impProcessor.getDateLastRun();
}
@Override
public void setDateLastRun(Timestamp dateLastRun)
{
impProcessor.setDateLastRun(dateLastRun);
}
@Override
public boolean saveOutOfTrx()
{
InterfaceWrapperHelper.save(impProcessor, ITrx.TRXNAME_None);
return true;
}
@Override
public AdempiereProcessorLog[] getLogs()
{
final List<AdempiereProcessorLog> list = Services.get(IIMPProcessorDAO.class).retrieveAdempiereProcessorLogs(impProcessor);
return list.toArray(new AdempiereProcessorLog[list.size()]);
}
@Override
public String get_TableName()
{
return I_IMP_Processor.Table_Name;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\IMPProcessorAdempiereProcessorAdapter.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getTransitionId() {
return transitionId;
}
public void setTransitionId(String transitionId) {
this.transitionId = transitionId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTransitionInstanceId() {
return transitionInstanceId;
}
public void setTransitionInstanceId(String transitionInstanceId) {
this.transitionInstanceId = transitionInstanceId;
}
public String getAncestorActivityInstanceId() {
return ancestorActivityInstanceId;
}
public void setAncestorActivityInstanceId(String ancestorActivityInstanceId) {
this.ancestorActivityInstanceId = ancestorActivityInstanceId;
}
public boolean isCancelCurrentActiveActivityInstances() {
return cancelCurrentActiveActivityInstances;
}
public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) {
this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances;
}
public abstract void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper); | public abstract void applyTo(InstantiationBuilder<?> builder, ProcessEngine engine, ObjectMapper mapper);
protected String buildErrorMessage(String message) {
return "For instruction type '" + type + "': " + message;
}
protected void applyVariables(ActivityInstantiationBuilder<?> builder,
ProcessEngine engine, ObjectMapper mapper) {
if (variables != null) {
for (Map.Entry<String, TriggerVariableValueDto> variableValue : variables.entrySet()) {
TriggerVariableValueDto value = variableValue.getValue();
if (value.isLocal()) {
builder.setVariableLocal(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
else {
builder.setVariable(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
}
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\modification\ProcessInstanceModificationInstructionDto.java | 1 |
请完成以下Java代码 | protected Optional<String> getAccountIBAN()
{
return Optional.ofNullable(accountStatement2.getAcct().getId().getIBAN());
}
@Override
@NonNull
protected Optional<String> getSwiftCode()
{
return Optional.ofNullable(accountStatement2.getAcct().getSvcr())
.map(branchAndFinancialInstitutionIdentification4 -> branchAndFinancialInstitutionIdentification4.getFinInstnId().getBIC())
.filter(Check::isNotBlank);
}
@Override
@NonNull
protected Optional<String> getAccountNo()
{
return Optional.ofNullable(accountStatement2.getAcct().getId().getOthr())
.map(GenericAccountIdentification1::getId);
}
@NonNull
private IStatementLineWrapper buildBatchReportEntryWrapper(@NonNull final ReportEntry2 reportEntry)
{
return BatchReportEntry2Wrapper.builder()
.currencyRepository(getCurrencyRepository())
.entry(reportEntry)
.build();
}
@NonNull
private Optional<CashBalance3> findOPBDCashBalance()
{
return accountStatement2.getBal()
.stream()
.filter(AccountStatement2Wrapper::isOPBDCashBalance)
.findFirst();
}
@NonNull
private Optional<CashBalance3> findPRCDCashBalance()
{
return accountStatement2.getBal()
.stream() | .filter(AccountStatement2Wrapper::isPRCDCashBalance)
.findFirst();
}
private static boolean isPRCDCashBalance(@NonNull final CashBalance3 cashBalance)
{
final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd();
return BalanceType12Code.PRCD.equals(balanceTypeCode);
}
private static boolean isOPBDCashBalance(@NonNull final CashBalance3 cashBalance)
{
final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd();
return BalanceType12Code.OPBD.equals(balanceTypeCode);
}
private static boolean isCRDTCashBalance(@NonNull final CashBalance3 cashBalance)
{
return CRDT.equals(cashBalance.getCdtDbtInd());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\AccountStatement2Wrapper.java | 1 |
请完成以下Java代码 | public String getPrintName (String AD_Language)
{
if (AD_Language == null || AD_Language.length() == 0)
{
return super.getPrintName();
}
return get_Translation (COLUMNNAME_PrintName, AD_Language);
} // getPrintName
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success)
{
// Add doctype/docaction access to all roles of client
String sqlDocAction = "INSERT INTO AD_Document_Action_Access "
+ "(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,"
+ "C_DocType_ID , AD_Ref_List_ID, AD_Role_ID) "
+ "(SELECT "
+ getAD_Client_ID() + ",0,'Y', now(),"
+ getUpdatedBy() + ", now()," + getUpdatedBy()
+ ", doctype.C_DocType_ID, action.AD_Ref_List_ID, rol.AD_Role_ID "
+ "FROM AD_Client client "
+ "INNER JOIN C_DocType doctype ON (doctype.AD_Client_ID=client.AD_Client_ID) "
+ "INNER JOIN AD_Ref_List action ON (action.AD_Reference_ID=135) "
+ "INNER JOIN AD_Role rol ON (rol.AD_Client_ID=client.AD_Client_ID) "
+ "WHERE client.AD_Client_ID=" + getAD_Client_ID()
+ " AND doctype.C_DocType_ID=" + get_ID()
+ " AND rol.IsManual='N'"
+ ")"; | int docact = DB.executeUpdateAndSaveErrorOnFail(sqlDocAction, get_TrxName());
log.debug("AD_Document_Action_Access=" + docact);
}
return success;
} // afterSave
/**
* Executed after Delete operation.
* @param success true if record deleted
* @return true if delete is a success
*/
@Override
protected boolean afterDelete (boolean success)
{
if(success) {
//delete access records
int docactDel = DB.executeUpdateAndSaveErrorOnFail("DELETE FROM AD_Document_Action_Access WHERE C_DocType_ID=" + get_IDOld(), get_TrxName());
log.debug("Deleting AD_Document_Action_Access=" + docactDel + " for C_DocType_ID: " + get_IDOld());
}
return success;
} // afterDelete
} // MDocType | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDocType.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/flyway
username: flyway
password: 12345678
flyw | ay:
locations:
- classpath:flyway
table: t_flyway_history | repos\spring-boot-best-practice-master\spring-boot-flyway\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public class WorkpackageSkipRequestException extends AdempiereException implements IWorkpackageSkipRequest
{
private static final long serialVersionUID = 5950712616746434839L;
private final int skipTimeoutMillis;
private final static Random RANDOM = new Random();
public static WorkpackageSkipRequestException create(final String message)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS,
null);
}
public static WorkpackageSkipRequestException createWithThrowable(final String message, final Throwable cause)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS,
cause);
}
public static WorkpackageSkipRequestException createWithTimeoutAndThrowable(
final String message,
final int skipTimeoutMillis,
final Throwable cause)
{
return new WorkpackageSkipRequestException(message,
skipTimeoutMillis,
cause);
}
public static WorkpackageSkipRequestException createWithTimeout(
final String message,
final int skipTimeoutMillis)
{
return new WorkpackageSkipRequestException(message,
skipTimeoutMillis,
null);
}
/**
* A random int between 0 and 5000 is added to the {@link Async_Constants#DEFAULT_RETRY_TIMEOUT_MILLIS} timeout. Use this if you want workpackages that are postponed at the same time to be
* retried at different times.
*/
public static WorkpackageSkipRequestException createWithRandomTimeout(final String message)
{
return new WorkpackageSkipRequestException(message,
Async_Constants.DEFAULT_RETRY_TIMEOUT_MILLIS + RANDOM.nextInt(5001),
null);
}
private WorkpackageSkipRequestException(final String message, final int skipTimeoutMillis, final Throwable cause)
{
super(message, cause);
this.skipTimeoutMillis = skipTimeoutMillis;
}
@Override | public String getSkipReason()
{
return getLocalizedMessage();
}
@Override
public boolean isSkip()
{
return true;
}
@Override
public int getSkipTimeoutMillis()
{
return skipTimeoutMillis;
}
@Override
public Exception getException()
{
return this;
}
/**
* No need to fill the log if this exception is thrown.
*/
protected boolean isLoggedInTrxManager()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\exceptions\WorkpackageSkipRequestException.java | 1 |
请完成以下Java代码 | public class FlowableObjectNotFoundException extends FlowableException {
private static final long serialVersionUID = 1L;
private Class<?> objectClass;
public FlowableObjectNotFoundException(String message) {
super(message);
}
public FlowableObjectNotFoundException(String message, Class<?> objectClass) {
this(message, objectClass, null);
}
public FlowableObjectNotFoundException(Class<?> objectClass) { | this(null, objectClass, null);
}
public FlowableObjectNotFoundException(String message, Class<?> objectClass, Throwable cause) {
super(message, cause);
this.objectClass = objectClass;
}
/**
* The class of the object that was not found. Contains the interface-class of the object that was not found.
*/
public Class<?> getObjectClass() {
return objectClass;
}
} | repos\flowable-engine-main\modules\flowable-engine-common-api\src\main\java\org\flowable\common\engine\api\FlowableObjectNotFoundException.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.