instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setItemType (final java.lang.String ItemType)
{
set_Value (COLUMNNAME_ItemType, ItemType);
}
@Override
public java.lang.String getItemType()
{
return get_ValueAsString(COLUMNNAME_ItemType);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PackingMaterial getM_HU_PackingMaterial()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PackingMaterial_ID, de.metas.handlingunits.model.I_M_HU_PackingMaterial.class);
}
@Override
public void setM_HU_PackingMaterial(final de.metas.handlingunits.model.I_M_HU_PackingMaterial M_HU_PackingMaterial)
{
set_ValueFromPO(COLUMNNAME_M_HU_PackingMaterial_ID, de.metas.handlingunits.model.I_M_HU_PackingMaterial.class, M_HU_PackingMaterial);
}
@Override
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID)
{
if (M_HU_PackingMaterial_ID < 1)
set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, null);
else
set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID);
}
@Override
public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID)
{
if (M_HU_PI_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID);
}
@Override
public int getM_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); | }
@Override
public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class);
}
@Override
public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version);
}
@Override
public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID)
{
if (M_HU_PI_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID);
}
@Override
public int getM_HU_PI_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public NacosDataSource nacosDataSource(ObjectMapper objectMapper) {
// Nacos 配置。这里先写死,推荐后面写到 application.yaml 配置文件中。
String serverAddress = "127.0.0.1:8848"; // Nacos 服务器地址
String namespace = ""; // Nacos 命名空间
String dataId = "demo-application-flow-rule"; // Nacos 配置集编号
// String dataId = "example-sentinel"; // Nacos 配置集编号
String group = "DEFAULT_GROUP"; // Nacos 配置分组
// 创建 NacosDataSource 对象
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddress);
properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);
NacosDataSource<List<FlowRule>> nacosDataSource = new NacosDataSource<>(properties, group, dataId,
new Converter<String, List<FlowRule>>() { // 转换器,将读取的 Nacos 配置,转换成 FlowRule 数组
@Override | public List<FlowRule> convert(String value) {
try {
return Arrays.asList(objectMapper.readValue(value, FlowRule[].class));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 FlowRuleManager 中
FlowRuleManager.register2Property(nacosDataSource.getProperty());
return nacosDataSource;
}
} | repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-nacos\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java | 2 |
请完成以下Java代码 | public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() { | return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\domain\PersistentAuditEvent.java | 1 |
请完成以下Java代码 | public static Json fail() {
return new Json(DEFAULT_OPER_VAL, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null);
}
public static Json fail(String operate) {
return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null);
}
public static Json fail(String operate, String message) {
return new Json(operate, false, DEFAULT_FAIL_CODE, message, null);
}
public static Json fail(String operate, Object data) {
return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, data);
}
public static Json fail(String operate, String dataKey, Object dataVal) {
return new Json(operate, false, DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null).data(dataKey, dataVal);
}
////// 操作动态判定成功或失败的:
public static Json result(String operate, boolean success) {
return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE),
(success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), null);
}
public static Json result(String operate, boolean success, Object data) {
return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE),
(success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), data);
}
public static Json result(String operate, boolean success, String dataKey, Object dataVal) {
return new Json(operate, success, (success ? DEFAULT_SUCC_CODE : DEFAULT_FAIL_CODE),
(success ? DEFAULT_SUCC_MSG : DEFAULT_FAIL_MSG), null).data(dataKey, dataVal);
}
/////////////////////// 各种链式调用方法 ///////////////////////
/** 设置操作名称 */
public Json oper(String operate) {
this.put(KEY_OPER, operate);
return this;
}
/** 设置操作结果是否成功的标记 */
public Json succ(boolean success) {
this.put(KEY_SUCC, success); | return this;
}
/** 设置操作结果的代码 */
public Json code(int code) {
this.put(KEY_CODE, code);
return this;
}
/** 设置操作结果的信息 */
public Json msg(String message) {
this.put(KEY_MSG, message);
return this;
}
/** 设置操作返回的数据 */
public Json data(Object dataVal) {
this.put(KEY_DATA, dataVal);
return this;
}
/** 设置操作返回的数据,数据使用自定义的key存储 */
public Json data(String dataKey, Object dataVal) {
this.put(dataKey, dataVal);
return this;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\vo\Json.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) {
return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) {
return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation);
}
/**
* {@inheritDoc}
*/
@Override | public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) {
return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding);
}
/**
* Build an
* {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails}
* @return
*/
@Override
public OpenSamlAssertingPartyDetails build() {
return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java | 2 |
请完成以下Java代码 | public boolean add(E e) {
return deque.add(e);
}
@Override
public boolean remove(Object o) {
return deque.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return deque.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return deque.addAll(c);
} | @Override
public boolean removeAll(Collection<?> c) {
return deque.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return deque.retainAll(c);
}
@Override
public void clear() {
deque.clear();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java | 1 |
请完成以下Java代码 | public class ProfileView {
String username;
String bio;
String image;
boolean following;
public static ProfileView toUnfollowedProfileView(User userToMakeView) {
return toProfileView(userToMakeView, false);
}
public static ProfileView toFollowedProfileView(User userToMakeView) {
return toProfileView(userToMakeView, true);
}
public static ProfileView toOwnProfile(User user) {
return toProfileViewForViewer(user, user); | }
public static ProfileView toProfileViewForViewer(User userToMakeView, User viewer) {
var following = userToMakeView.isFollower(viewer);
return toProfileView(userToMakeView, following);
}
private static ProfileView toProfileView(User userToMakeView, boolean following) {
return new ProfileView()
.setUsername(userToMakeView.getUsername())
.setBio(userToMakeView.getBio())
.setImage(userToMakeView.getImage())
.setFollowing(following);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\dto\ProfileView.java | 1 |
请完成以下Java代码 | public I_C_ValidCombination getC_Receivable_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getC_Receivable_Acct(), get_TrxName()); }
/** Set Customer Receivables.
@param C_Receivable_Acct
Account for Customer Receivables
*/
public void setC_Receivable_Acct (int C_Receivable_Acct)
{
set_Value (COLUMNNAME_C_Receivable_Acct, Integer.valueOf(C_Receivable_Acct));
}
/** Get Customer Receivables.
@return Account for Customer Receivables
*/
public int getC_Receivable_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getC_Receivable_Services_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) | .getPO(getC_Receivable_Services_Acct(), get_TrxName()); }
/** Set Receivable Services.
@param C_Receivable_Services_Acct
Customer Accounts Receivables Services Account
*/
public void setC_Receivable_Services_Acct (int C_Receivable_Services_Acct)
{
set_Value (COLUMNNAME_C_Receivable_Services_Acct, Integer.valueOf(C_Receivable_Services_Acct));
}
/** Get Receivable Services.
@return Customer Accounts Receivables Services Account
*/
public int getC_Receivable_Services_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Services_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_BP_Customer_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean getSuspended() {
return suspended;
}
public void setSuspended(Boolean suspended) {
this.suspended = suspended;
}
public Boolean getIncludeProcessVariables() {
return includeProcessVariables;
}
public void setIncludeProcessVariables(Boolean includeProcessVariables) {
this.includeProcessVariables = includeProcessVariables;
}
public Collection<String> getIncludeProcessVariablesNames() {
return includeProcessVariablesNames;
}
public void setIncludeProcessVariablesNames(Collection<String> includeProcessVariablesNames) {
this.includeProcessVariablesNames = includeProcessVariablesNames;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getVariables() {
return variables;
}
public void setVariables(List<QueryVariable> variables) {
this.variables = variables;
}
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
public String getParentCaseInstanceId() {
return parentCaseInstanceId;
}
public void setParentCaseInstanceId(String parentCaseInstanceId) {
this.parentCaseInstanceId = parentCaseInstanceId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() { | return tenantId;
}
public String getTenantIdLikeIgnoreCase() {
return tenantIdLikeIgnoreCase;
}
public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) {
this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getCallbackIds() {
return callbackIds;
}
public void setCallbackIds(Set<String> callbackIds) {
this.callbackIds = callbackIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceQueryRequest.java | 2 |
请完成以下Java代码 | private static final void assertValidDatePattern(I_AD_Language language)
{
final String datePattern = language.getDatePattern();
if (Check.isEmpty(datePattern))
{
return; // OK
}
if (datePattern.indexOf("MM") == -1)
{
throw new AdempiereException("@Error@ @DatePattern@ - No Month (MM)");
}
if (datePattern.indexOf("dd") == -1)
{
throw new AdempiereException("@Error@ @DatePattern@ - No Day (dd)");
}
if (datePattern.indexOf("yy") == -1)
{ | throw new AdempiereException("@Error@ @DatePattern@ - No Year (yy)");
}
final Locale locale = new Locale(language.getLanguageISO(), language.getCountryCode());
final SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale);
try
{
dateFormat.applyPattern(datePattern);
}
catch (final Exception e)
{
throw new AdempiereException("@Error@ @DatePattern@ - " + e.getMessage(), e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLanguage.java | 1 |
请完成以下Java代码 | public void saveActionLog(
@NonNull final SecurPharmLog log,
@NonNull final SecurPharmProductId productId,
@NonNull final SecurPharmActionResultId actionId)
{
final ImmutableList<SecurPharmLog> logs = ImmutableList.of(log);
saveLogs(logs, productId, actionId);
}
private void saveLogs(
@NonNull final Collection<SecurPharmLog> logs,
@Nullable final SecurPharmProductId productId,
@Nullable final SecurPharmActionResultId actionId)
{
if (logs.isEmpty())
{
return;
}
final Set<SecurPharmLogId> existingLogIds = logs.stream()
.map(SecurPharmLog::getId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
final ImmutableMap<SecurPharmLogId, I_M_Securpharm_Log> existingLogRecords = retrieveLogRecordsByIds(existingLogIds);
for (final SecurPharmLog log : logs)
{
final I_M_Securpharm_Log existingLogRecord = existingLogRecords.get(log.getId());
saveLog(log, existingLogRecord, productId, actionId);
}
}
private ImmutableMap<SecurPharmLogId, I_M_Securpharm_Log> retrieveLogRecordsByIds(final Collection<SecurPharmLogId> ids)
{
if (ids.isEmpty())
{
return ImmutableMap.of();
}
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Securpharm_Log.class)
.addInArrayFilter(I_M_Securpharm_Log.COLUMN_M_Securpharm_Log_ID, ids)
.create()
.stream()
.collect(GuavaCollectors.toImmutableMapByKey(record -> SecurPharmLogId.ofRepoId(record.getM_Securpharm_Log_ID())));
}
private void saveLog(
@NonNull final SecurPharmLog log,
@Nullable final I_M_Securpharm_Log existingLogRecord,
@Nullable final SecurPharmProductId productId,
@Nullable final SecurPharmActionResultId actionId)
{
final I_M_Securpharm_Log record;
if (existingLogRecord != null)
{
record = existingLogRecord;
}
else
{
record = newInstance(I_M_Securpharm_Log.class);
}
record.setIsActive(true); | record.setIsError(log.isError());
//
// Request
record.setRequestUrl(log.getRequestUrl());
record.setRequestMethod(log.getRequestMethod() != null ? log.getRequestMethod().name() : null);
record.setRequestStartTime(TimeUtil.asTimestamp(log.getRequestTime()));
//
// Response
record.setRequestEndTime(TimeUtil.asTimestamp(log.getResponseTime()));
record.setResponseCode(log.getResponseCode() != null ? log.getResponseCode().value() : 0);
record.setResponseText(log.getResponseData());
//
record.setTransactionIDClient(log.getClientTransactionId());
record.setTransactionIDServer(log.getServerTransactionId());
//
// Links
if (productId != null)
{
record.setM_Securpharm_Productdata_Result_ID(productId.getRepoId());
}
if (actionId != null)
{
record.setM_Securpharm_Action_Result_ID(actionId.getRepoId());
}
saveRecord(record);
log.setId(SecurPharmLogId.ofRepoId(record.getM_Securpharm_Log_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\log\SecurPharmLogRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoginController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(
@RequestParam(value = "username", required = true) String userName,
@RequestParam(value = "password", required = true) String password,
@RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe
) {
logger.info("==========" + userName + password + rememberMe);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
token.setRememberMe(rememberMe);
try { | subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
// rediect.addFlashAttribute("errorText", "您的账号或密码输入错误!");
return "{\"Msg\":\"您的账号或密码输入错误\",\"state\":\"failed\"}";
}
return "{\"Msg\":\"登陆成功\",\"state\":\"success\"}";
}
@RequestMapping("/")
@ResponseBody
public String index() {
return "no permission";
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\controller\LoginController.java | 2 |
请完成以下Java代码 | private static Object convertParameterToJson(@Nullable final Object value, @NonNull final String adLanguage)
{
if (value == null || Null.isNull(value))
{
return "<null>";
}
else if (value instanceof ITranslatableString)
{
return ((ITranslatableString)value).translate(adLanguage);
}
else if (value instanceof RepoIdAware)
{
return String.valueOf(((RepoIdAware)value).getRepoId());
}
else if (value instanceof ReferenceListAwareEnum)
{
return ((ReferenceListAwareEnum)value).getCode();
}
else if (value instanceof Collection)
{
//noinspection unchecked
final Collection<Object> collection = (Collection<Object>)value;
return collection.stream()
.map(item -> convertParameterToJson(item, adLanguage))
.collect(Collectors.toList());
}
else if (value instanceof Map)
{
//noinspection unchecked
final Map<Object, Object> map = (Map<Object, Object>)value;
return convertParametersMapToJson(map, adLanguage);
}
else
{
return value.toString();
// return JsonObjectMapperHolder.toJsonOrToString(value);
}
}
@NonNull
private static String convertParameterToStringJson(@Nullable final Object value, @NonNull final String adLanguage) | {
if (value == null || Null.isNull(value))
{
return "<null>";
}
else if (value instanceof ITranslatableString)
{
return ((ITranslatableString)value).translate(adLanguage);
}
else if (value instanceof RepoIdAware)
{
return String.valueOf(((RepoIdAware)value).getRepoId());
}
else if (value instanceof ReferenceListAwareEnum)
{
return ((ReferenceListAwareEnum)value).getCode();
}
else
{
return value.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\v2\JsonErrors.java | 1 |
请完成以下Java代码 | public IQueryFilter<I_PP_Order> getQualityInspectionFilter()
{
return qualityInspectionFilter;
}
@Override
public Timestamp getDateOfProduction(final I_PP_Order ppOrder)
{
final Timestamp dateOfProduction;
if (ppOrder.getDateDelivered() != null)
{
dateOfProduction = ppOrder.getDateDelivered();
}
else
{
dateOfProduction = ppOrder.getDateFinishSchedule();
}
Check.assumeNotNull(dateOfProduction, "dateOfProduction not null for PP_Order {}", ppOrder);
return dateOfProduction;
}
@Override | public List<I_M_InOutLine> retrieveIssuedInOutLines(final I_PP_Order ppOrder)
{
// services
final IPPOrderMInOutLineRetrievalService ppOrderMInOutLineRetrievalService = Services.get(IPPOrderMInOutLineRetrievalService.class);
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class);
final List<I_M_InOutLine> allIssuedInOutLines = new ArrayList<>();
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getByOrderId(ppOrderId))
{
if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc))
{
continue;
}
final List<I_M_InOutLine> issuedInOutLinesForCC = ppOrderMInOutLineRetrievalService.provideIssuedInOutLines(cc);
allIssuedInOutLines.addAll(issuedInOutLinesForCC);
}
return allIssuedInOutLines;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderBL.java | 1 |
请完成以下Java代码 | public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine)
{
// nothing
}
@Override
public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld)
{
// nothing
}
@Override
public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines)
{
// nothing
}
@Override | public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults)
{
// nothing;
}
@Override
public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
// nothing
}
@Override
public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\NullHUTrxListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Boolean getFailed() {
return failed;
}
public void setFailed(Boolean failed) {
this.failed = failed;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getTenantId() {
return tenantId;
} | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
} | repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java | 2 |
请完成以下Java代码 | public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID)
{
if (C_Invoice_Candidate_Term_ID < 1)
set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, null);
else
set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID));
}
/** Get Vertrag-Rechnungskandidat.
@return Vertrag-Rechnungskandidat */
@Override
public int getC_Invoice_Candidate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zugeordnete Menge wird in Summe einbez..
@param IsAssignedQuantityIncludedInSum Zugeordnete Menge wird in Summe einbez. */ | @Override
public void setIsAssignedQuantityIncludedInSum (boolean IsAssignedQuantityIncludedInSum)
{
set_Value (COLUMNNAME_IsAssignedQuantityIncludedInSum, Boolean.valueOf(IsAssignedQuantityIncludedInSum));
}
/** Get Zugeordnete Menge wird in Summe einbez..
@return Zugeordnete Menge wird in Summe einbez. */
@Override
public boolean isAssignedQuantityIncludedInSum ()
{
Object oo = get_Value(COLUMNNAME_IsAssignedQuantityIncludedInSum);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests //
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/assets/**")))
.permitAll() // <1>
.requestMatchers(
PathPatternRequestMatcher.withDefaults().matcher((this.adminServer.path("/actuator/info"))))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(adminServer.path("/actuator/health")))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/login")))
.permitAll()
.dispatcherTypeMatchers(DispatcherType.ASYNC)
.permitAll() // https://github.com/spring-projects/spring-security/issues/11027
.anyRequest()
.authenticated()) // <2>
.formLogin(
(formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler)) // <3>
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
.httpBasic(Customizer.withDefaults()); // <4>
http.addFilterAfter(new CustomCsrfFilter(), BasicAuthenticationFilter.class) // <5>
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")), // <6>
PathPatternRequestMatcher.withDefaults().matcher(DELETE, this.adminServer.path("/instances/*")), // <6>
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**")) // <7>
));
http.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600)); | return http.build();
}
// Required to provide UserDetailsService for "remember functionality"
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("user").password(passwordEncoder.encode("password")).roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
// end::configuration-spring-security[] | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SecuritySecureConfig.java | 2 |
请完成以下Java代码 | public Iterable<Path> getRootDirectories() {
assertNotClosed();
return Collections.emptySet();
}
@Override
public Iterable<FileStore> getFileStores() {
assertNotClosed();
return Collections.emptySet();
}
@Override
public Set<String> supportedFileAttributeViews() {
assertNotClosed();
return SUPPORTED_FILE_ATTRIBUTE_VIEWS;
}
@Override
public Path getPath(String first, String... more) {
assertNotClosed();
if (more.length != 0) {
throw new IllegalArgumentException("Nested paths must contain a single element");
}
return new NestedPath(this, first);
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
throw new UnsupportedOperationException("Nested paths do not support path matchers");
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service");
}
@Override
public WatchService newWatchService() throws IOException {
throw new UnsupportedOperationException("Nested paths do not support the WatchService"); | }
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
NestedFileSystem other = (NestedFileSystem) obj;
return this.jarPath.equals(other.jarPath);
}
@Override
public int hashCode() {
return this.jarPath.hashCode();
}
@Override
public String toString() {
return this.jarPath.toAbsolutePath().toString();
}
private void assertNotClosed() {
if (this.closed) {
throw new ClosedFileSystemException();
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java | 1 |
请完成以下Java代码 | private final void debugCheckItemsValid()
{
if (!DEBUG)
{
return;
}
final PT parentModel = getParentModel();
final IContextAware ctx = createPlainContextAware(parentModel);
final boolean instancesTrackerEnabled = POJOLookupMapInstancesTracker.ENABLED;
POJOLookupMapInstancesTracker.ENABLED = false;
try
{
//
// Retrieve fresh items
final List<T> itemsRetrievedNow = retrieveItems(ctx, parentModel);
if (itemsComparator != null)
{
Collections.sort(itemsRetrievedNow, itemsComparator);
} | if (!Objects.equals(this.items, itemsRetrievedNow))
{
final int itemsCount = this.items == null ? 0 : this.items.size();
final int itemsRetrievedNowCount = itemsRetrievedNow.size();
throw new AdempiereException("Loaded items and cached items does not match."
+ "\n Parent: " + parentModelRef.get()
+ "\n Cached items(" + itemsCount + "): " + this.items
+ "\n Fresh items(" + itemsRetrievedNowCount + "): " + itemsRetrievedNow
+ "\n debugEmptyNotStaledSet=" + debugEmptyNotStaledSet //
);
}
}
finally
{
POJOLookupMapInstancesTracker.ENABLED = instancesTrackerEnabled;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\cache\AbstractModelListCacheLocal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class App extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Filter[] getServletFilters() {
DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
delegateFilterProxy.setTargetBeanName("loggingFilter");
return new Filter[] { delegateFilterProxy };
}
@Override | protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return null;
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\app\App.java | 2 |
请完成以下Java代码 | private void cancelRpcSubscription(TbCoapClientState state) {
if (state.getRpc() != null) {
clientsByToken.remove(state.getRpc().getToken());
CoapExchange exchange = state.getRpc().getExchange();
state.setRpc(null);
transportService.process(state.getSession(),
TransportProtos.SubscribeToRPCMsg.newBuilder().setUnsubscribe(true).build(),
new CoapResponseCodeCallback(exchange, CoAP.ResponseCode.DELETED, CoAP.ResponseCode.INTERNAL_SERVER_ERROR));
if (state.getAttrs() == null) {
closeAndCleanup(state);
}
}
}
private void cancelAttributeSubscription(TbCoapClientState state) {
if (state.getAttrs() != null) {
clientsByToken.remove(state.getAttrs().getToken());
CoapExchange exchange = state.getAttrs().getExchange();
state.setAttrs(null);
transportService.process(state.getSession(),
TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().setUnsubscribe(true).build(), | new CoapResponseCodeCallback(exchange, CoAP.ResponseCode.DELETED, CoAP.ResponseCode.INTERNAL_SERVER_ERROR));
if (state.getRpc() == null) {
closeAndCleanup(state);
}
}
}
private void closeAndCleanup(TbCoapClientState state) {
transportService.process(state.getSession(), getSessionEventMsg(TransportProtos.SessionEvent.CLOSED), null);
transportService.deregisterSession(state.getSession());
state.setSession(null);
state.setConfiguration(null);
state.setCredentials(null);
state.setAdaptor(null);
//TODO: add optimistic lock check that the client was already deleted and cleanup "clients" map.
}
private void respond(CoapExchange exchange, Response response, int defContentFormat) {
response.getOptions().setContentFormat(TbCoapContentFormatUtil.getContentFormat(exchange.getRequestOptions().getContentFormat(), defContentFormat));
exchange.respond(response);
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\client\DefaultCoapClientContext.java | 1 |
请完成以下Java代码 | default ET compile(final String expressionStr)
{
return compile(ExpressionContext.EMPTY, expressionStr);
}
/**
* Compiles given string expression
*
* If the expression cannot be evaluated, returns the given default expression.
*
* This method does not throw any exception, but in case of error that error will be logged.
*
* @param expressionStr The expression to be compiled
* @return compiled expression or <code>defaultExpression</code>
*/ | default ET compileOrDefault(final String expressionStr, final ET defaultExpression)
{
try
{
return compile(expressionStr);
}
catch (final Exception ex)
{
final Logger logger = LogManager.getLogger(getClass());
logger.warn("Failed parsing '{}'. Returning default expression: {}", expressionStr, defaultExpression, ex);
return defaultExpression;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IExpressionCompiler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private static Map<String, ConfigAttribute> configAttributeMap = null;
@Autowired
private DynamicSecurityService dynamicSecurityService;
@PostConstruct
public void loadDataSource() {
configAttributeMap = dynamicSecurityService.loadDataSource();
}
public void clearDataSource() {
configAttributeMap.clear();
configAttributeMap = null;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher(); | Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
}
// 未设置操作请求权限,返回空集合
return configAttributes;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\DynamicSecurityMetadataSource.java | 2 |
请完成以下Java代码 | public void onParameterChanged(String parameterName)
{
if (!WAREHOUSE_PARAM_NAME.equals(parameterName))
{
return;
}
if (warehouseIdOrNull() == null)
{
locatorRepoId = 0;
return;
}
locatorRepoId = warehouseBL.getOrCreateDefaultLocatorId(warehouseId()).getRepoId();
}
@ProcessParamLookupValuesProvider(parameterName = LOCATOR_PARAM_NAME, dependsOn = WAREHOUSE_PARAM_NAME, numericKey = true)
public LookupValuesList getLocators()
{
if (warehouseRepoId <= 0)
{
return LookupValuesList.EMPTY;
}
return warehouseDAO
.getLocators(warehouseId())
.stream()
.map(locator -> IntegerLookupValue.of(locator.getM_Locator_ID(), locator.getValue()))
.collect(LookupValuesList.collect());
}
@Override | protected void customizeParametersBuilder(@NonNull final CreateReceiptsParametersBuilder parametersBuilder)
{
final LocatorId locatorId = LocatorId.ofRepoIdOrNull(warehouseIdOrNull(), locatorRepoId);
parametersBuilder.destinationLocatorIdOrNull(locatorId);
}
private WarehouseId warehouseId()
{
return WarehouseId.ofRepoId(warehouseRepoId);
}
private WarehouseId warehouseIdOrNull()
{
return WarehouseId.ofRepoIdOrNull(warehouseRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_LocatorParams.java | 1 |
请完成以下Java代码 | static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows); | markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\matrixtozero\SetMatrixToZero.java | 1 |
请完成以下Java代码 | public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} | @Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java | 1 |
请完成以下Java代码 | public void setPublishAuthorizationSuccess(boolean publishAuthorizationSuccess) {
this.publishAuthorizationSuccess = publishAuthorizationSuccess;
}
/**
* By rejecting public invocations (and setting this property to <tt>true</tt>),
* essentially you are ensuring that every secure object invocation advised by
* <code>AbstractSecurityInterceptor</code> has a configuration attribute defined.
* This is useful to ensure a "fail safe" mode where undeclared secure objects will be
* rejected and configuration omissions detected early. An
* <tt>IllegalArgumentException</tt> will be thrown by the
* <tt>AbstractSecurityInterceptor</tt> if you set this property to <tt>true</tt> and
* an attempt is made to invoke a secure object that has no configuration attributes.
* @param rejectPublicInvocations set to <code>true</code> to reject invocations of
* secure objects that have no configuration attributes (by default it is
* <code>false</code> which treats undeclared secure objects as "public" or
* unauthorized).
*/
public void setRejectPublicInvocations(boolean rejectPublicInvocations) {
this.rejectPublicInvocations = rejectPublicInvocations;
}
public void setRunAsManager(RunAsManager runAsManager) { | this.runAsManager = runAsManager;
}
public void setValidateConfigAttributes(boolean validateConfigAttributes) {
this.validateConfigAttributes = validateConfigAttributes;
}
private void publishEvent(ApplicationEvent event) {
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(event);
}
}
private static class NoOpAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new AuthenticationServiceException("Cannot authenticate " + authentication);
}
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AbstractSecurityInterceptor.java | 1 |
请完成以下Java代码 | public int getRow()
{
return m_row;
} // getRow
/**
* Get Column
* @return col no
*/
public int getCol()
{
return m_col;
} // getCol
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.<p>
*
* @param o the Object to be compared.
* @return a negative integer if this object is less than the specified object,
* zero if equal,
* or a positive integer if this object is greater than the specified object.
*/
public int compareTo(Object o)
{
ALayoutConstraint comp = null;
if (o instanceof ALayoutConstraint)
comp = (ALayoutConstraint)o;
if (comp == null)
return +111;
// Row compare
int rowComp = m_row - comp.getRow();
if (rowComp != 0)
return rowComp;
// Column compare
return m_col - comp.getCol();
} // compareTo | /**
* Is Object Equal
* @param o
* @return true if equal
*/
public boolean equals(Object o)
{
if (o instanceof ALayoutConstraint)
return compareTo(o) == 0;
return false;
} // equal
/**
* To String
* @return info
*/
public String toString()
{
return "ALayoutConstraint [Row=" + m_row + ", Col=" + m_col + "]";
} // toString
} // ALayoutConstraint | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayoutConstraint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TransactionalService {
private final Cache<String, Integer> transactionalCache;
private static final String KEY = "key";
public TransactionalService(Cache<String, Integer> transactionalCache) {
this.transactionalCache = transactionalCache;
transactionalCache.put(KEY, 0);
}
public Integer getQuickHowManyVisits() {
try {
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
tm.begin();
Integer howManyVisits = transactionalCache.get(KEY);
howManyVisits++;
System.out.println("Ill try to set HowManyVisits to " + howManyVisits);
StopWatch watch = new StopWatch();
watch.start();
transactionalCache.put(KEY, howManyVisits);
watch.stop();
System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds");
tm.commit();
return howManyVisits;
} catch (Exception e) { | e.printStackTrace();
return 0;
}
}
public void startBackgroundBatch() {
try {
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
tm.begin();
transactionalCache.put(KEY, 1000);
System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction");
Thread.sleep(1000L);
tm.rollback();
System.out.println("The slow batch suffered a rollback");
} catch (Exception e) {
e.printStackTrace();
}
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\infinispan\service\TransactionalService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MaterialTrackingId implements RepoIdAware
{
int repoId;
@JsonCreator
public static MaterialTrackingId ofRepoId(final int repoId)
{
return new MaterialTrackingId(repoId);
}
public static MaterialTrackingId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new MaterialTrackingId(repoId) : null;
}
public static MaterialTrackingId ofRepoIdOrNull(@Nullable final int repoId)
{
return repoId > 0 ? new MaterialTrackingId(repoId) : null;
}
private MaterialTrackingId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "productId");
}
public TableRecordReference toTableRecordReference()
{ | return TableRecordReference.of(I_M_Material_Tracking.Table_Name, getRepoId());
}
public static int toRepoId(@Nullable final MaterialTrackingId materialTrackingId)
{
return materialTrackingId != null ? materialTrackingId.getRepoId() : -1;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\MaterialTrackingId.java | 2 |
请完成以下Java代码 | public EsrAddressType getBank() {
return bank;
}
/**
* Sets the value of the bank property.
*
* @param value
* allowed object is
* {@link EsrAddressType }
*
*/
public void setBank(EsrAddressType value) {
this.bank = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "15";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the participantNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getParticipantNumber() {
return participantNumber;
}
/**
* Sets the value of the participantNumber property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setParticipantNumber(String value) {
this.participantNumber = value;
}
/**
* Gets the value of the referenceNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the codingLine property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingLine() {
return codingLine;
}
/**
* Sets the value of the codingLine property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine(String value) {
this.codingLine = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\Esr5Type.java | 1 |
请完成以下Java代码 | public I_C_UOM getC_UOM(final I_PP_MRP mrp)
{
Check.assumeNotNull(mrp, "mrp not null");
return Services.get(IProductBL.class).getStockUOM(mrp.getM_Product_ID());
}
@Override
public I_C_UOM getC_UOM(final I_PP_MRP_Alternative mrpAlternative)
{
Check.assumeNotNull(mrpAlternative, "mrpAlternative not null");
return Services.get(IProductBL.class).getStockUOM(mrpAlternative.getM_Product_ID());
}
@Override
public String toString(final I_PP_MRP mrp)
{
final String description = mrp.getDescription();
return mrp.getClass().getSimpleName() + "["
+ ", TypeMRP=" + mrp.getTypeMRP()
+ ", DocStatus=" + mrp.getDocStatus()
+ ", Qty=" + mrp.getQty()
+ ", DatePromised=" + mrp.getDatePromised()
+ ", Schedule=" + mrp.getDateStartSchedule() + "/" + mrp.getDateFinishSchedule()
+ ", IsAvailable=" + mrp.isAvailable()
+ (!Check.isEmpty(description, true) ? ", Description=" + description : "")
+ ", ID=" + mrp.getPP_MRP_ID()
+ "]";
}
@Override
public IMRPSegment createMRPSegment(final I_PP_MRP mrp)
{
Check.assumeNotNull(mrp, "mrp not null");
final int adClientId = mrp.getAD_Client_ID();
final I_AD_Org adOrg = mrp.getAD_Org();
final I_M_Warehouse warehouse = mrp.getM_Warehouse();
final I_S_Resource plant = mrp.getS_Resource();
final I_M_Product product = mrp.getM_Product();
return new MRPSegment(adClientId, adOrg, warehouse, plant, product);
}
@Override
public boolean isQtyOnHandReservation(final I_PP_MRP mrpSupply)
{
Check.assumeNotNull(mrpSupply, "mrpSupply not null");
final String typeMRP = mrpSupply.getTypeMRP();
if (!X_PP_MRP.TYPEMRP_Supply.equals(typeMRP))
{
return false;
}
final String orderType = mrpSupply.getOrderType();
return X_PP_MRP.ORDERTYPE_QuantityOnHandReservation.equals(orderType); | }
@Override
public boolean isQtyOnHandInTransit(final I_PP_MRP mrpSupply)
{
Check.assumeNotNull(mrpSupply, "mrpSupply not null");
final String typeMRP = mrpSupply.getTypeMRP();
if (!X_PP_MRP.TYPEMRP_Supply.equals(typeMRP))
{
return false;
}
final String orderType = mrpSupply.getOrderType();
return X_PP_MRP.ORDERTYPE_QuantityOnHandInTransit.equals(orderType);
}
@Override
public boolean isQtyOnHandAnyReservation(final I_PP_MRP mrpSupply)
{
return isQtyOnHandReservation(mrpSupply)
|| isQtyOnHandInTransit(mrpSupply);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPBL.java | 1 |
请完成以下Java代码 | public class QRPaymentStringDataProvider extends AbstractPaymentStringDataProvider
{
private static final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
private static final ICurrencyDAO currencyDAO = Services.get(ICurrencyDAO.class);
private static final IESRBPBankAccountDAO esrbpBankAccountDAO = Services.get(IESRBPBankAccountDAO.class);
public QRPaymentStringDataProvider(final PaymentString paymentString)
{
super(paymentString);
}
@Override
public List<org.compiere.model.I_C_BP_BankAccount> getC_BP_BankAccounts()
{
final PaymentString paymentString = getPaymentString();
final String IBAN = paymentString.getIBAN();
final List<org.compiere.model.I_C_BP_BankAccount> bankAccounts = InterfaceWrapperHelper.createList(
esrbpBankAccountDAO.retrieveQRBPBankAccounts(IBAN), org.compiere.model.I_C_BP_BankAccount.class);
return bankAccounts;
}
@Override
public I_C_BP_BankAccount createNewC_BP_BankAccount(final IContextAware contextProvider, final int bpartnerId)
{
final PaymentString paymentString = getPaymentString();
final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class,
contextProvider);
Check.assume(bpartnerId > 0, "We assume the bPartnerId to be greater than 0. This={}", this);
bpBankAccount.setC_BPartner_ID(bpartnerId);
final Currency currency = currencyDAO.getByCurrencyCode(CurrencyCode.CHF); // CHF, because it's ESR | bpBankAccount.setC_Currency_ID(currency.getId().getRepoId());
bpBankAccount.setIsEsrAccount(true); // ..because we are creating this from an ESR/QRR string
bpBankAccount.setIsACH(true);
final String bPartnerName = bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(bpartnerId));
bpBankAccount.setA_Name(bPartnerName);
bpBankAccount.setName(bPartnerName);
bpBankAccount.setQR_IBAN(paymentString.getIBAN());
bpBankAccount.setAccountNo(paymentString.getInnerAccountNo());
bpBankAccount.setESR_RenderedAccountNo(paymentString.getPostAccountNo()); // we can not know it
InterfaceWrapperHelper.save(bpBankAccount);
return bpBankAccount;
}
@Override
public String toString()
{
return String.format("QRPaymentStringDataProvider [getPaymentString()=%s]", getPaymentString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\api\impl\QRPaymentStringDataProvider.java | 1 |
请完成以下Java代码 | public String toJson()
{
return json;
}
@JsonCreator
public static final MediaType fromJson(final String json)
{
final MediaType type = json2type.get(json);
if (type == null)
{
throw new NoSuchElementException("Invalid media type '" + json + "'."
+ " Available media types are: " + Stream.of(values()).map(MediaType::toJson).collect(Collectors.joining(", ")));
}
return type;
}
public static final ImmutableSet<MediaType> fromNullableCommaSeparatedString(@Nullable final String str)
{ | if(Check.isBlank(str))
{
return ImmutableSet.of();
}
final List<String> parts = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(str);
return parts.stream()
.map(MediaType::fromJson)
.collect(ImmutableSet.toImmutableSet());
}
private static final ImmutableMap<String, MediaType> json2type = Stream.of(values())
.collect(ImmutableMap.toImmutableMap(MediaType::toJson, Function.identity()));
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\MediaType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricJobLogRestServiceImpl implements HistoricJobLogRestService {
protected ObjectMapper objectMapper;
protected ProcessEngine processEngine;
public HistoricJobLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) {
this.objectMapper = objectMapper;
this.processEngine = processEngine;
}
@Override
public HistoricJobLogResource getHistoricJobLog(String historicJobLogId) {
return new HistoricJobLogResourceImpl(historicJobLogId, processEngine);
}
@Override
public List<HistoricJobLogDto> getHistoricJobLogs(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricJobLogs(queryDto, firstResult, maxResults);
}
@Override
public List<HistoricJobLogDto> queryHistoricJobLogs(HistoricJobLogQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(objectMapper);
HistoricJobLogQuery query = queryDto.toQuery(processEngine);
List<HistoricJobLog> matchingHistoricJobLogs = QueryUtil.list(query, firstResult, maxResults);
List<HistoricJobLogDto> results = new ArrayList<HistoricJobLogDto>();
for (HistoricJobLog historicJobLog : matchingHistoricJobLogs) {
HistoricJobLogDto result = HistoricJobLogDto.fromHistoricJobLog(historicJobLog);
results.add(result);
}
return results;
}
@Override | public CountResultDto getHistoricJobLogsCount(UriInfo uriInfo) {
HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricJobLogsCount(queryDto);
}
@Override
public CountResultDto queryHistoricJobLogsCount(HistoricJobLogQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricJobLogQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricJobLogRestServiceImpl.java | 2 |
请完成以下Java代码 | public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderSn() {
return orderSn;
}
public void setOrderSn(String orderSn) {
this.orderSn = orderSn;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id); | sb.append(", couponId=").append(couponId);
sb.append(", memberId=").append(memberId);
sb.append(", couponCode=").append(couponCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", getType=").append(getType);
sb.append(", createTime=").append(createTime);
sb.append(", useStatus=").append(useStatus);
sb.append(", useTime=").append(useTime);
sb.append(", orderId=").append(orderId);
sb.append(", orderSn=").append(orderSn);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponHistory.java | 1 |
请完成以下Java代码 | public List<I_M_HU_PI_Item_Product> retrieveHUPIItemProductRecords(
@NonNull final Properties ctx,
@NonNull final ProductId productId,
@Nullable final BPartnerId bpartnerId,
final boolean includeVirtualItem)
{
final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class);
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean allowInfiniteCapacity = sysConfigBL.getBooleanValue(SYSCONFIG_ALLOW_INFINIT_CAPACITY_TUS, true,
Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx));
final List<I_M_HU_PI_Item_Product> list = hupiItemProductDAO
.retrieveTUs(ctx, productId, bpartnerId, allowInfiniteCapacity);
if (includeVirtualItem)
{
list.add(hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx));
}
return list;
} | /**
* Creates a string of the form "PI-Version-Name (Qty x Included-PI)", e.g. "Palette (20 x IFCO)".
*
* @param huPIItem may not be {@code null}
* @return
*/
public String buildHUPIItemString(@NonNull final I_M_HU_PI_Item huPIItem)
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final I_M_HU_PI includedPI = handlingUnitsDAO.getIncludedPI(huPIItem);
final String result = StringUtils.formatMessage("{} ({} x {})",
huPIItem.getM_HU_PI_Version().getName(),
huPIItem.getQty().setScale(0, RoundingMode.HALF_UP), // it's always integer quantities
includedPI.getName());
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\WEBUI_ProcessHelper.java | 1 |
请完成以下Java代码 | protected void registerInterceptors(@NonNull final IModelValidationEngine engine)
{
// nothing on this level
}
/**
* Called onInit to setup tab level callouts
*
* @param tabCalloutsRegistry
*/
protected void registerTabCallouts(final ITabCalloutFactory tabCalloutsRegistry)
{
// nothing on this level
}
/**
* Called onInit to setup module table callouts
*
* @param calloutsRegistry
*/
protected void registerCallouts(@NonNull final IProgramaticCalloutProvider calloutsRegistry)
{
// nothing on this level
}
private void setupEventBus()
{
final List<Topic> userNotificationsTopics = getAvailableUserNotificationsTopics();
if (userNotificationsTopics != null && !userNotificationsTopics.isEmpty())
{
final IEventBusFactory eventBusFactory = Services.get(IEventBusFactory.class);
for (final Topic topic : userNotificationsTopics)
{
eventBusFactory.addAvailableUserNotificationsTopic(topic);
}
}
}
/**
* @return available user notifications topics to listen
*/
protected List<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableList.of();
} | private void setupMigrationScriptsLogger()
{
final Set<String> tableNames = getTableNamesToSkipOnMigrationScriptsLogging();
if (tableNames != null && !tableNames.isEmpty())
{
final IMigrationLogger migrationLogger = Services.get(IMigrationLogger.class);
migrationLogger.addTablesToIgnoreList(tableNames);
}
}
protected Set<String> getTableNamesToSkipOnMigrationScriptsLogging() {return ImmutableSet.of();}
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
}
/**
* Does nothing. Module interceptors are not allowed to intercept models or documents
*/
@Override
public final void onModelChange(final Object model, final ModelChangeType changeType)
{
// nothing
}
/**
* Does nothing. Module interceptors are not allowed to intercept models or documents
*/
@Override
public final void onDocValidate(final Object model, final DocTimingType timing)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModuleInterceptor.java | 1 |
请完成以下Java代码 | public class CreditorReferenceType2 {
@XmlElement(name = "CdOrPrtry", required = true)
protected CreditorReferenceType1Choice cdOrPrtry;
@XmlElement(name = "Issr")
protected String issr;
/**
* Gets the value of the cdOrPrtry property.
*
* @return
* possible object is
* {@link CreditorReferenceType1Choice }
*
*/
public CreditorReferenceType1Choice getCdOrPrtry() {
return cdOrPrtry;
}
/**
* Sets the value of the cdOrPrtry property.
*
* @param value
* allowed object is
* {@link CreditorReferenceType1Choice }
*
*/
public void setCdOrPrtry(CreditorReferenceType1Choice value) {
this.cdOrPrtry = value;
} | /**
* Gets the value of the issr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssr() {
return issr;
}
/**
* Sets the value of the issr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssr(String value) {
this.issr = 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_02\CreditorReferenceType2.java | 1 |
请完成以下Java代码 | public class ClassDelegateHttpHandler extends AbstractClassDelegate implements HttpRequestHandler, HttpResponseHandler {
private static final long serialVersionUID = 1L;
public ClassDelegateHttpHandler(String className, List<FieldDeclaration> fieldDeclarations) {
super(className, fieldDeclarations);
}
public ClassDelegateHttpHandler(Class<?> clazz, List<FieldDeclaration> fieldDeclarations) {
super(clazz, fieldDeclarations);
}
@Override
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) {
HttpRequestHandler httpRequestHandler = getHttpRequestHandlerInstance();
CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new HttpRequestHandlerInvocation(httpRequestHandler, execution, httpRequest, client));
}
@Override
public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
HttpResponseHandler httpResponseHandler = getHttpResponseHandlerInstance();
CommandContextUtil.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new HttpResponseHandlerInvocation(httpResponseHandler, execution, httpResponse));
}
protected HttpRequestHandler getHttpRequestHandlerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof HttpRequestHandler) {
return (HttpRequestHandler) delegateInstance; | } else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpRequestHandler.class);
}
}
protected HttpResponseHandler getHttpResponseHandlerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof HttpResponseHandler) {
return (HttpResponseHandler) delegateInstance;
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + HttpResponseHandler.class);
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\http\handler\ClassDelegateHttpHandler.java | 1 |
请完成以下Java代码 | public SseEmitter handleSse() {
SseEmitter emitter = new SseEmitter();
nonBlockingService.execute(() -> {
try {
emitter.send(Constants.API_SSE_MSG + " @ " + new Date());
emitter.complete();
} catch (Exception ex) {
System.out.println(Constants.GENERIC_EXCEPTION);
emitter.completeWithError(ex);
}
});
return emitter;
}
@GetMapping("/stream-sse-mvc")
public SseEmitter streamSseMvc() {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); | sseMvcExecutor.execute(() -> {
try {
for (int i = 0; true; i++) {
SseEventBuilder event = SseEmitter.event()
.data("SSE MVC - " + LocalTime.now()
.toString())
.id(String.valueOf(i))
.name("sse event - mvc");
emitter.send(event);
Thread.sleep(1000);
}
} catch (Exception ex) {
emitter.completeWithError(ex);
}
});
return emitter;
}
} | repos\tutorials-master\spring-web-modules\spring-5-mvc\src\main\java\com\baeldung\web\SseEmitterController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class RAGChatbotConfiguration {
private static final int MAX_RESULTS = 10;
@Bean
PromptTemplate promptTemplate(
@Value("classpath:prompt-template.st") Resource promptTemplate
) throws IOException {
String template = promptTemplate.getContentAsString(StandardCharsets.UTF_8);
return PromptTemplate
.builder()
.renderer(StTemplateRenderer
.builder()
.startDelimiterToken('<')
.endDelimiterToken('>')
.build())
.template(template)
.build();
}
@Bean
ChatClient chatClient( | ChatModel chatModel,
VectorStore vectorStore,
PromptTemplate promptTemplate
) {
return ChatClient
.builder(chatModel)
.defaultAdvisors(
QuestionAnswerAdvisor
.builder(vectorStore)
.promptTemplate(promptTemplate)
.searchRequest(SearchRequest
.builder()
.topK(MAX_RESULTS)
.build())
.build()
)
.build();
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-vector-stores\spring-ai-oracle\src\main\java\com\baeldung\springai\vectorstore\oracle\RAGChatbotConfiguration.java | 2 |
请完成以下Java代码 | public static BearerTokenError invalidRequest(String message) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, message,
DEFAULT_URI);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INVALID_REQUEST;
}
}
/**
* Create a {@link BearerTokenError} caused by an invalid token
* @param message a description of the error
* @return a {@link BearerTokenError}
*/
public static BearerTokenError invalidToken(String message) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message,
DEFAULT_URI);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INVALID_TOKEN;
}
} | /**
* Create a {@link BearerTokenError} caused by an invalid token
* @param scope the scope attribute to use in the error
* @return a {@link BearerTokenError}
*/
public static BearerTokenError insufficientScope(String message, String scope) {
try {
return new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message,
DEFAULT_URI, scope);
}
catch (IllegalArgumentException ex) {
// some third-party library error messages are not suitable for RFC 6750's
// error message charset
return DEFAULT_INSUFFICIENT_SCOPE;
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\BearerTokenErrors.java | 1 |
请完成以下Spring Boot application配置 | #Stripe keys - REPLACE WITH ACTUAL KEYS
stripe.keys.public=pk_test_XXXXXXXXXXXXXX
stripe.keys.secret=sk_test_XXXXXXXXXXXXXX
#Don't cache thymel | eaf files - FOR TEST PURPOSE ONLY
spring.thymeleaf.cache=false | repos\springboot-demo-master\stripe\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setPP_Order_Receipt_ID (final int PP_Order_Receipt_ID)
{
if (PP_Order_Receipt_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Receipt_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Receipt_ID, PP_Order_Receipt_ID);
}
@Override
public int getPP_Order_Receipt_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Receipt_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override | public void setQualityInspectionCycle (final @Nullable java.lang.String QualityInspectionCycle)
{
set_ValueNoCheck (COLUMNNAME_QualityInspectionCycle, QualityInspectionCycle);
}
@Override
public java.lang.String getQualityInspectionCycle()
{
return get_ValueAsString(COLUMNNAME_QualityInspectionCycle);
}
@Override
public void setRV_M_Material_Tracking_HU_Details_ID (final int RV_M_Material_Tracking_HU_Details_ID)
{
if (RV_M_Material_Tracking_HU_Details_ID < 1)
set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, null);
else
set_ValueNoCheck (COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID, RV_M_Material_Tracking_HU_Details_ID);
}
@Override
public int getRV_M_Material_Tracking_HU_Details_ID()
{
return get_ValueAsInt(COLUMNNAME_RV_M_Material_Tracking_HU_Details_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_M_Material_Tracking_HU_Details.java | 1 |
请完成以下Java代码 | public class EngineClientLogger extends ExternalTaskClientLogger {
protected EngineClientException exceptionWhileReceivingResponse(HttpRequest httpRequest, RestException e) {
return new EngineClientException(exceptionMessage(
"001", "Request '{}' returned error: status code '{}' - message: {}", httpRequest, e.getHttpStatusCode(), e.getMessage()), e);
}
protected EngineClientException exceptionWhileEstablishingConnection(HttpRequest httpRequest, IOException e) {
return new EngineClientException(exceptionMessage(
"002", "Exception while establishing connection for request '{}'", httpRequest), e);
}
protected <T> void exceptionWhileClosingResourceStream(T response, IOException e) {
logError(
"003", "Exception while closing resource stream of response '" + response + "': ", e);
}
protected <T> EngineClientException exceptionWhileParsingJsonObject(Class<T> responseDtoClass, Throwable t) {
return new EngineClientException(exceptionMessage(
"004", "Exception while parsing json object to response dto class '{}'", responseDtoClass), t);
}
protected <T> EngineClientException exceptionWhileMappingJsonObject(Class<T> responseDtoClass, Throwable t) {
return new EngineClientException(exceptionMessage(
"005", "Exception while mapping json object to response dto class '{}'", responseDtoClass), t);
} | protected <T> EngineClientException exceptionWhileDeserializingJsonObject(Class<T> responseDtoClass, Throwable t) {
return new EngineClientException(exceptionMessage(
"006", "Exception while deserializing json object to response dto class '{}'", responseDtoClass), t);
}
protected <D extends RequestDto> EngineClientException exceptionWhileSerializingJsonObject(D dto, Throwable t) {
return new EngineClientException(exceptionMessage(
"007", "Exception while serializing json object to '{}'", dto), t);
}
public void requestInterceptorException(Throwable e) {
logError(
"008", "Exception while executing request interceptor: {}", e);
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClientLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookServiceImpl implements BookService {
private static final AtomicLong counter = new AtomicLong();
/**
* 使用集合模拟数据库
*/
private static List<Book> books = new ArrayList<>(
Arrays.asList(
new Book(counter.incrementAndGet(), "book")));
// 模拟数据库,存储 Book 信息
// 第五章《数据存储》会替换成 MySQL 存储
private static Map<String, Book> BOOK_DB = new HashMap<>();
@Override
public List<Book> findAll() {
return new ArrayList<>(BOOK_DB.values());
}
@Override
public Book insertByBook(Book book) {
book.setId(BOOK_DB.size() + 1L);
BOOK_DB.put(book.getId().toString(), book);
return book;
}
@Override
public Book update(Book book) {
BOOK_DB.put(book.getId().toString(), book);
return book;
}
@Override
public Book delete(Long id) {
return BOOK_DB.remove(id.toString());
} | @Override
public Book findById(Long id) {
return BOOK_DB.get(id.toString());
}
@Override
public boolean exists(Book book) {
return findByName(book.getName()) != null;
}
@Override
public Book findByName(String name) {
for (Book book : books) {
if (book.getName().equals(name)) {
return book;
}
}
return null;
}
} | repos\springboot-learning-example-master\chapter-3-spring-boot-web\src\main\java\demo\springboot\service\impl\BookServiceImpl.java | 2 |
请完成以下Java代码 | private void process_PriceChangeEvent(final I_PMM_RfQResponse_ChangeEvent event)
{
updateC_RfQResponseLine(event);
assertRfqResponseNotClosed(event);
final I_C_RfQResponseLine rfqResponseLine = event.getC_RfQResponseLine();
final BigDecimal priceOld = rfqResponseLine.getPrice();
rfqResponseLine.setPrice(event.getPrice());
InterfaceWrapperHelper.save(rfqResponseLine);
//
// Update event
event.setPrice_Old(priceOld);
markProcessed(event);
}
private void process_QuantityChangeEvent(final I_PMM_RfQResponse_ChangeEvent event)
{
updateC_RfQResponseLine(event);
assertRfqResponseNotClosed(event);
final I_C_RfQResponseLine rfqResponseLine = event.getC_RfQResponseLine();
final Timestamp date = event.getDatePromised();
I_C_RfQResponseLineQty rfqResponseLineQty = pmmRfqDAO.retrieveResponseLineQty(rfqResponseLine, date);
if (rfqResponseLineQty == null)
{
rfqResponseLineQty = InterfaceWrapperHelper.newInstance(I_C_RfQResponseLineQty.class, event);
rfqResponseLineQty.setAD_Org_ID(rfqResponseLine.getAD_Org_ID());
rfqResponseLineQty.setC_RfQResponseLine(rfqResponseLine);
rfqResponseLineQty.setC_RfQLine(rfqResponseLine.getC_RfQLine());
rfqResponseLineQty.setC_RfQLineQty(null);
rfqResponseLineQty.setDatePromised(date);
}
final BigDecimal qtyOld = rfqResponseLineQty.getQtyPromised();
rfqResponseLineQty.setQtyPromised(event.getQty());
InterfaceWrapperHelper.save(rfqResponseLineQty);
//
// Update event
event.setQty_Old(qtyOld);
event.setC_RfQResponseLineQty(rfqResponseLineQty);
markProcessed(event);
}
private void updateC_RfQResponseLine(final I_PMM_RfQResponse_ChangeEvent event)
{ | final String rfqResponseLine_uuid = event.getC_RfQResponseLine_UUID();
final int rfqReponseLineId = SyncUUIDs.getC_RfQResponseLine_ID(rfqResponseLine_uuid);
event.setC_RfQResponseLine_ID(rfqReponseLineId);
}
private void assertRfqResponseNotClosed(final I_PMM_RfQResponse_ChangeEvent event)
{
final I_C_RfQResponseLine rfqResponseLine = event.getC_RfQResponseLine();
Check.assumeNotNull(rfqResponseLine, "rfqResponseLine not null");
if (pmmRfqBL.isCompletedOrClosed(rfqResponseLine))
{
throw new RfQDocumentClosedException(rfqResponseLine);
}
}
public String getProcessSummary()
{
return "@Processed@ #" + countProcessed.get();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\event\impl\PMMRfQResponseChangeEventTrxItemProcessor.java | 1 |
请完成以下Java代码 | public Iterator getPrefixes(String arg0) {
return null;
}
@Override
public String getPrefix(String arg0) {
return null;
}
@Override
public String getNamespaceURI(String arg0) {
if ("bdn".equals(arg0)) {
return "http://www.baeldung.com/full_archive";
}
return null;
}
});
String expression = "/bdn:tutorials/bdn:tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
private void clean(Node node) {
NodeList childNodes = node.getChildNodes();
for (int n = childNodes.getLength() - 1; n >= 0; n--) {
Node child = childNodes.item(n); | short nodeType = child.getNodeType();
if (nodeType == Node.ELEMENT_NODE)
clean(child);
else if (nodeType == Node.TEXT_NODE) {
String trimmedNodeVal = child.getNodeValue().trim();
if (trimmedNodeVal.length() == 0)
node.removeChild(child);
else
child.setNodeValue(trimmedNodeVal);
} else if (nodeType == Node.COMMENT_NODE)
node.removeChild(child);
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\DefaultParser.java | 1 |
请完成以下Java代码 | public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
} | @Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请完成以下Java代码 | public static void schedule(@NonNull final ShipmentSchedulesUpdateSchedulerRequest request)
{
_schedule(request);
}
private static void _schedule(@NonNull final ShipmentSchedulesUpdateSchedulerRequest request)
{
SCHEDULER.schedule(request);
}
private static final UpdateInvalidShipmentSchedulesScheduler //
SCHEDULER = new UpdateInvalidShipmentSchedulesScheduler(true /*createOneWorkpackagePerAsyncBatch*/);
// services
private final transient IShipmentScheduleUpdater shipmentScheduleUpdater = Services.get(IShipmentScheduleUpdater.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName_NOTUSED)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
final PInstanceId selectionId = Services.get(IADPInstanceDAO.class).createSelectionId();
loggable.addLog("Using revalidation ID: {}", selectionId); | try (final MDCCloseable ignored = ShipmentSchedulesMDC.putRevalidationId(selectionId))
{
final ShipmentScheduleUpdateInvalidRequest request = ShipmentScheduleUpdateInvalidRequest.builder()
.ctx(InterfaceWrapperHelper.getCtx(workpackage))
.selectionId(selectionId)
.createMissingShipmentSchedules(false) // don't create missing schedules; for that we have CreateMissingShipmentSchedulesWorkpackageProcessor
.build();
loggable.addLog("Starting revalidation for {}", request);
final int updatedCount = shipmentScheduleUpdater.updateShipmentSchedules(request);
loggable.addLog("Updated {} shipment schedule entries for {}", updatedCount, request);
return Result.SUCCESS;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\async\UpdateInvalidShipmentSchedulesWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public void beforeApply(WeightConfig config) {
if (publisher != null) {
publisher.publishEvent(new WeightDefinedEvent(this, config));
}
}
@Override
public Predicate<ServerWebExchange> apply(WeightConfig config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR, Collections.emptyMap());
String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR);
if (routeId == null) {
return false;
}
// all calculations and comparison against random num happened in
// WeightCalculatorWebFilter
String group = config.getGroup();
if (weights.containsKey(group)) {
String chosenRoute = weights.get(group);
if (log.isTraceEnabled()) {
log.trace("in group weight: " + group + ", current route: " + routeId + ", chosen route: "
+ chosenRoute);
}
return routeId.equals(chosenRoute);
}
else if (log.isTraceEnabled()) {
log.trace("no weights found for group: " + group + ", current route: " + routeId);
} | return false;
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Weight: %s %s", config.getGroup(), config.getWeight());
}
};
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\WeightRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public void setIsGenerated (final boolean IsGenerated)
{
set_ValueNoCheck (COLUMNNAME_IsGenerated, IsGenerated);
}
@Override
public boolean isGenerated()
{
return get_ValueAsBoolean(COLUMNNAME_IsGenerated);
}
@Override
public void setIsSplitAcctTrx (final boolean IsSplitAcctTrx)
{
set_Value (COLUMNNAME_IsSplitAcctTrx, IsSplitAcctTrx);
}
@Override
public boolean isSplitAcctTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSplitAcctTrx);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
} | @Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=540534
* Reference name: GL_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=540534;
/** Normal = N */
public static final String TYPE_Normal = "N";
/** Tax = T */
public static final String TYPE_Tax = "T";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Response getDeploymentResourceData(String resourceId) {
RepositoryService repositoryService = engine.getRepositoryService();
InputStream resourceAsStream = repositoryService.getResourceAsStreamById(deploymentId, resourceId);
if (resourceAsStream != null) {
DeploymentResourceDto resource = getDeploymentResource(resourceId);
String name = resource.getName();
String filename = null;
String mediaType = null;
if (name != null) {
name = name.replace("\\", "/");
String[] filenameParts = name.split("/");
if (filenameParts.length > 0) {
int idx = filenameParts.length-1;
filename = filenameParts[idx];
}
String[] extensionParts = name.split("\\.");
if (extensionParts.length > 0) {
int idx = extensionParts.length-1;
String extension = extensionParts[idx];
if (extension != null) {
mediaType = MEDIA_TYPE_MAPPING.get(extension);
} | }
}
if (filename == null) {
filename = "data";
}
if (mediaType == null) {
mediaType = MediaType.APPLICATION_OCTET_STREAM;
}
return Response
.ok(resourceAsStream, mediaType)
.header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(filename))
.build();
}
else {
throw new InvalidRequestException(Status.NOT_FOUND,
"Deployment resource '" + resourceId + "' for deployment id '" + deploymentId + "' does not exist.");
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DeploymentResourcesResourceImpl.java | 2 |
请完成以下Java代码 | public class CoreJacksonModule extends SecurityJacksonModule {
public CoreJacksonModule() {
super(CoreJacksonModule.class.getName(), new Version(1, 0, 0, null, null, null));
}
protected CoreJacksonModule(String name, Version version) {
super(name, version);
}
@Override
public void configurePolymorphicTypeValidator(BasicPolymorphicTypeValidator.Builder builder) {
builder.allowIfSubType(Instant.class)
.allowIfSubType(Duration.class)
.allowIfSubType(SimpleGrantedAuthority.class)
.allowIfSubType(FactorGrantedAuthority.class)
.allowIfSubType(UsernamePasswordAuthenticationToken.class)
.allowIfSubType(RememberMeAuthenticationToken.class)
.allowIfSubType(AnonymousAuthenticationToken.class)
.allowIfSubType(User.class)
.allowIfSubType(BadCredentialsException.class)
.allowIfSubType(SecurityContextImpl.class)
.allowIfSubType(TestingAuthenticationToken.class)
.allowIfSubType("java.util.Collections$UnmodifiableSet")
.allowIfSubType("java.util.Collections$UnmodifiableRandomAccessList")
.allowIfSubType("java.util.Collections$EmptyList")
.allowIfSubType("java.util.ArrayList")
.allowIfSubType("java.util.HashMap") | .allowIfSubType("java.util.Collections$EmptyMap")
.allowIfSubType("java.util.Date")
.allowIfSubType("java.util.Arrays$ArrayList")
.allowIfSubType("java.util.Collections$UnmodifiableMap")
.allowIfSubType("java.util.LinkedHashMap")
.allowIfSubType("java.util.Collections$SingletonList")
.allowIfSubType("java.util.TreeMap")
.allowIfSubType("java.util.HashSet")
.allowIfSubType("java.util.LinkedHashSet");
}
@Override
public void setupModule(SetupContext context) {
((MapperBuilder<?, ?>) context.getOwner()).enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS);
context.setMixIn(AnonymousAuthenticationToken.class, AnonymousAuthenticationTokenMixin.class);
context.setMixIn(RememberMeAuthenticationToken.class, RememberMeAuthenticationTokenMixin.class);
context.setMixIn(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class);
context.setMixIn(FactorGrantedAuthority.class, FactorGrantedAuthorityMixin.class);
context.setMixIn(User.class, UserMixin.class);
context.setMixIn(UsernamePasswordAuthenticationToken.class, UsernamePasswordAuthenticationTokenMixin.class);
context.setMixIn(TestingAuthenticationToken.class, TestingAuthenticationTokenMixin.class);
context.setMixIn(BadCredentialsException.class, BadCredentialsExceptionMixin.class);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\jackson\CoreJacksonModule.java | 1 |
请完成以下Java代码 | public List<String> evaluateExpressionsAndExecuteIdsList(CommandContext commandContext) {
validate();
evaluateExpressions();
return !hasExcludingConditions() ? executeIdsList(commandContext) : new ArrayList<>();
}
public List<String> executeIdsList(CommandContext commandContext) {
throw new UnsupportedOperationException("executeIdsList not supported by " + getClass().getCanonicalName());
}
public List<ImmutablePair<String, String>> evaluateExpressionsAndExecuteDeploymentIdMappingsList(CommandContext commandContext) {
validate();
evaluateExpressions();
return !hasExcludingConditions() ? executeDeploymentIdMappingsList(commandContext) : new ArrayList<>();
}
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
throw new UnsupportedOperationException("executeDeploymentIdMappingsList not supported by " + getClass().getCanonicalName()); | }
protected void checkMaxResultsLimit() {
if (maxResultsLimitEnabled) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(maxResults);
}
}
public void enableMaxResultsLimit() {
maxResultsLimitEnabled = true;
}
public void disableMaxResultsLimit() {
maxResultsLimitEnabled = false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CacheConfig {
/**
* 配置默认的缓存管理器
*/
@Primary
@Bean("defaultCacheManager")
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
// 设置最后一次写入后经过固定时间过期.
.expireAfterWrite(10, TimeUnit.SECONDS)
// 初始的缓存空间大小
.initialCapacity(100)
// 缓存的最大条数
.maximumSize(1000));
return cacheManager;
} | /**
* token放在本地缓存中
* 可以改造为放在redis中
*/
@Bean("tokenCacheManager")
public Cache<String, SessionUserInfo> caffeineCache() {
return Caffeine.newBuilder()
// 设置最后一次访问后经过固定时间过期.
.expireAfterAccess(30L, TimeUnit.MINUTES)
// 初始的缓存空间大小
.initialCapacity(100)
// 缓存的最大条数
.maximumSize(10000)
.build();
}
} | repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\system\CacheConfig.java | 2 |
请完成以下Java代码 | public boolean isActive() {
return isActive;
}
public String getInvolvedUser() {
return involvedUser;
}
public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser;
}
public Set<String> getProcessDefinitionIds() {
return processDefinitionIds;
}
public Set<String> getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getParentId() {
return parentId;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike; | }
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) {
this.nameLikeIgnoreCase = nameLikeIgnoreCase;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public boolean isObject()
{
return "Object".equals(javaCode);
}
public boolean isString()
{
return String.class.equals(typeClass);
}
public boolean isBoolean()
{
return boolean.class.equals(typeClass)
|| Boolean.class.equals(typeClass);
}
public boolean isInteger() | {
return int.class.equals(typeClass)
|| Integer.class.equals(typeClass);
}
public boolean isBigDecimal()
{
return java.math.BigDecimal.class.equals(typeClass);
}
public boolean isTimestamp()
{
return java.sql.Timestamp.class.equals(typeClass);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\DataTypeInfo.java | 1 |
请完成以下Java代码 | public void setMktInfrstrctrTxId(String value) {
this.mktInfrstrctrTxId = value;
}
/**
* Gets the value of the prcgId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrcgId() {
return prcgId;
}
/**
* Sets the value of the prcgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrcgId(String value) {
this.prcgId = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p> | * For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryReference1 }
*
*
*/
public List<ProprietaryReference1> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryReference1>();
}
return this.prtry;
}
} | 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\TransactionReferences3.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean setIsMember(String key, Object value) {
return setOperations.isMember(key, value);
}
public long setAdd(String key, Object... values) {
return setOperations.add(key, values);
}
public long setAdd(String key, long milliseconds, Object... values) {
Long count = setOperations.add(key, values);
if (milliseconds > 0) {
expire(key, milliseconds);
}
return count;
}
public long setSize(String key) {
return setOperations.size(key);
}
public long setRemove(String key, Object... values) {
return setOperations.remove(key, values);
}
//===============================list=================================
public List<Object> lGet(String key, long start, long end) {
return listOperations.range(key, start, end);
}
public long listSize(String key) {
return listOperations.size(key);
}
public Object listIndex(String key, long index) {
return listOperations.index(key, index);
}
public void listRightPush(String key, Object value) {
listOperations.rightPush(key, value);
}
public boolean listRightPush(String key, Object value, long milliseconds) {
listOperations.rightPush(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
} | public long listRightPushAll(String key, List<Object> value) {
return listOperations.rightPushAll(key, value);
}
public boolean listRightPushAll(String key, List<Object> value, long milliseconds) {
listOperations.rightPushAll(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public void listSet(String key, long index, Object value) {
listOperations.set(key, index, value);
}
public long listRemove(String key, long count, Object value) {
return listOperations.remove(key, count, value);
}
//===============================zset=================================
public boolean zsAdd(String key, Object value, double score) {
return zSetOperations.add(key, value, score);
}
} | repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RpAccountServiceImpl implements RpAccountService{
@Autowired
private RpAccountDao rpAccountDao;
@Override
public void saveData(RpAccount rpAccount) {
rpAccountDao.insert(rpAccount);
}
@Override
public void updateData(RpAccount rpAccount) {
rpAccountDao.update(rpAccount);
}
@Override
public RpAccount getDataById(String id) {
return rpAccountDao.getById(id); | }
@Override
public PageBean listPage(PageParam pageParam, RpAccount rpAccount) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("accountNo", rpAccount.getAccountNo());
return rpAccountDao.listPage(pageParam, paramMap);
}
@Override
public RpAccount getDataByUserNo(String userNo){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userNo", userNo);
return rpAccountDao.getBy(paramMap);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpAccountServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public IHUProductStorage getSingleHUProductStorage(@NonNull final HuId huId)
{
return handlingUnitsBL.getSingleHUProductStorage(huId);
}
public Quantity getProductQuantity(@NonNull final HuId huId, @NonNull ProductId productId)
{
return getHUProductStorage(huId, productId)
.map(IHUProductStorage::getQty)
.filter(Quantity::isPositive)
.orElseThrow(() -> new AdempiereException(PRODUCT_DOES_NOT_MATCH));
}
private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId)
{
final I_M_HU hu = handlingUnitsBL.getById(huId); | final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId));
}
public void assetHUContainsProduct(@NonNull final HUQRCode huQRCode, @NonNull final ProductId productId)
{
final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode);
getProductQuantity(huId, productId); // shall throw exception if no qty found
}
public void deleteReservationsByDocumentRefs(final ImmutableSet<HUReservationDocRef> huReservationDocRefs)
{
huReservationService.deleteReservationsByDocumentRefs(huReservationDocRefs);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\hu\DistributionHUService.java | 2 |
请完成以下Java代码 | public UsernamePasswordAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt)
throws JacksonException {
JsonNode jsonNode = ctxt.readTree(jp);
boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
JsonNode principalNode = readJsonNode(jsonNode, "principal");
Object principal = getPrincipal(ctxt, principalNode);
JsonNode credentialsNode = readJsonNode(jsonNode, "credentials");
Object credentials = getCredentials(credentialsNode);
JsonNode authoritiesNode = readJsonNode(jsonNode, "authorities");
List<GrantedAuthority> authorities = ctxt.readTreeAsValue(authoritiesNode,
ctxt.getTypeFactory().constructType(GRANTED_AUTHORITY_LIST));
UsernamePasswordAuthenticationToken token = (!authenticated)
? UsernamePasswordAuthenticationToken.unauthenticated(principal, credentials)
: UsernamePasswordAuthenticationToken.authenticated(principal, credentials, authorities);
JsonNode detailsNode = readJsonNode(jsonNode, "details");
if (detailsNode.isNull() || detailsNode.isMissingNode()) {
token.setDetails(null);
}
else {
Object details = ctxt.readTreeAsValue(detailsNode, Object.class);
token.setDetails(details);
}
return token;
}
private @Nullable Object getCredentials(JsonNode credentialsNode) {
if (credentialsNode.isNull() || credentialsNode.isMissingNode()) {
return null;
}
return credentialsNode.asString(); | }
private Object getPrincipal(DeserializationContext ctxt, JsonNode principalNode)
throws StreamReadException, DatabindException {
if (principalNode.isObject()) {
return ctxt.readTreeAsValue(principalNode, Object.class);
}
return principalNode.asString();
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\jackson\UsernamePasswordAuthenticationTokenDeserializer.java | 1 |
请完成以下Java代码 | public void addPropertyChangeListener(final PropertyChangeListener listener)
{
delegate.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(final PropertyChangeListener listener)
{
delegate.removePropertyChangeListener(listener);
}
public PropertyChangeListener[] getPropertyChangeListeners()
{
return delegate.getPropertyChangeListeners();
}
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{
delegate.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{
delegate.removePropertyChangeListener(propertyName, listener);
}
public PropertyChangeListener[] getPropertyChangeListeners(final String propertyName)
{
return delegate.getPropertyChangeListeners(propertyName);
}
public boolean hasListeners(final String propertyName)
{
return delegate.hasListeners(propertyName);
}
public final void firePropertyChange(final PropertyChangeEvent event)
{
if (delayedEvents != null)
{
delayedEvents.add(event);
}
else
{
delegate.firePropertyChange(event);
}
}
public void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
} | public void firePropertyChange(final String propertyName, final int oldValue, final int newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
}
public void firePropertyChange(final String propertyName, final boolean oldValue, final boolean newValue)
{
final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event);
}
public void fireIndexedPropertyChange(final String propertyName, final int index, final Object oldValue, final Object newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
public void fireIndexedPropertyChange(final String propertyName, final int index, final int oldValue, final int newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
public void fireIndexedPropertyChange(final String propertyName, final int index, final boolean oldValue, final boolean newValue)
{
final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index);
firePropertyChange(event);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\DelayedPropertyChangeSupport.java | 1 |
请完成以下Java代码 | public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
return this.delegate.canWrite(clazz, mediaType);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return this.delegate.getSupportedMediaTypes();
}
@Override
public List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
return this.delegate.getSupportedMediaTypes(clazz);
}
@Override
protected void writeInternal(T t, ResolvableType type, HttpOutputMessage outputMessage,
@Nullable Map<String, Object> hints) throws IOException, HttpMessageNotWritableException {
this.delegate.write(t, null, outputMessage);
} | @Override
public T read(ResolvableType type, HttpInputMessage inputMessage, @Nullable Map<String, Object> hints)
throws IOException, HttpMessageNotReadableException {
return this.delegate.read(type.getType(), null, inputMessage);
}
@Override
public boolean canWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType) {
return this.delegate.canWrite(targetType.getType(), valueClass, mediaType);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthenticationFilter.java | 1 |
请完成以下Java代码 | public static Optional<PaymentId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));}
public static int toRepoId(final PaymentId id)
{
return id != null ? id.getRepoId() : -1;
}
public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<PaymentId> ids)
{
if (ids.isEmpty())
{
return ImmutableSet.of();
}
return ids.stream().map(PaymentId::getRepoId).collect(ImmutableSet.toImmutableSet());
} | int repoId;
private PaymentId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable PaymentId id1, @Nullable PaymentId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\PaymentId.java | 1 |
请完成以下Java代码 | public class LoggerTrxItemExceptionHandler implements ITrxItemExceptionHandler
{
public static final LoggerTrxItemExceptionHandler instance = new LoggerTrxItemExceptionHandler();
private final transient Logger logger = LogManager.getLogger(getClass());
protected LoggerTrxItemExceptionHandler()
{
}
@Override
public void onNewChunkError(final Throwable e, final Object item)
{
logger.warn("Error while trying to create a new chunk for item: " + item, e);
}
@Override
public void onItemError(final Throwable e, final Object item)
{
logger.warn("Error while trying to process item: " + item, e);
}
@Override | public void onCompleteChunkError(final Throwable e)
{
logger.warn("Error while completing current chunk", e);
}
@Override
public void onCommitChunkError(final Throwable e)
{
logger.info("Processor failed to commit current chunk => rollback transaction", e);
}
@Override
public void afterCompleteChunkError(final Throwable e)
{
// nothing to do.
// error was already logged by onCompleteChunkError
}
@Override
public void onCancelChunkError(final Throwable e)
{
logger.warn("Error while cancelling current chunk. Ignored.", e);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\LoggerTrxItemExceptionHandler.java | 1 |
请完成以下Java代码 | public boolean seeksAfterHandling() {
return isSeekAfterError();
}
@Override
public boolean deliveryAttemptHeader() {
return true;
}
@Override
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer,
MessageListenerContainer container) {
try {
return getFailureTracker().recovered(record, thrownException, container, consumer);
}
catch (Exception ex) {
if (SeekUtils.isBackoffException(thrownException)) {
this.logger.debug(ex, "Failed to handle " + KafkaUtils.format(record) + " with " + thrownException);
}
else {
this.logger.error(ex, "Failed to handle " + KafkaUtils.format(record) + " with " + thrownException);
}
return false;
}
}
@Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records,
Consumer<?, ?> consumer, MessageListenerContainer container) {
SeekUtils.seekOrRecover(thrownException, records, consumer, container, isCommitRecovered(), // NOSONAR
getFailureTracker(), this.logger, getLogLevel());
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) {
doHandle(thrownException, data, consumer, container, invokeListener);
}
@Override
public <K, V> ConsumerRecords<K, V> handleBatchAndReturnRemaining(Exception thrownException,
ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, | Runnable invokeListener) {
return handle(thrownException, data, consumer, container, invokeListener);
}
@Override
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
if (thrownException instanceof SerializationException) {
throw new IllegalStateException("This error handler cannot process 'SerializationException's directly; "
+ "please consider configuring an 'ErrorHandlingDeserializer' in the value and/or key "
+ "deserializer", thrownException);
}
else {
throw new IllegalStateException("This error handler cannot process '"
+ thrownException.getClass().getName()
+ "'s; no record information is available", thrownException);
}
}
@Override
public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions,
Runnable publishPause) {
getFallbackBatchHandler().onPartitionsAssigned(consumer, partitions, publishPause);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\DefaultErrorHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public TopicBuilder assignReplicas(int partition, List<Integer> replicaList) {
if (this.replicasAssignments == null) {
this.replicasAssignments = new HashMap<>();
}
this.replicasAssignments.put(partition, new ArrayList<>(replicaList));
return this;
}
/**
* Set the configs.
* @param configProps the configs.
* @return the builder.
* @see NewTopic#configs()
*/
public TopicBuilder configs(Map<String, String> configProps) {
this.configs.putAll(configProps);
return this;
}
/**
* Set a configuration option.
* @param configName the name.
* @param configValue the value.
* @return the builder
* @see TopicConfig
*/
public TopicBuilder config(String configName, String configValue) {
this.configs.put(configName, configValue);
return this;
}
/**
* Set the {@link TopicConfig#CLEANUP_POLICY_CONFIG} to
* {@link TopicConfig#CLEANUP_POLICY_COMPACT}.
* @return the builder.
*/
public TopicBuilder compact() {
this.configs.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
return this;
} | public NewTopic build() {
NewTopic topic = this.replicasAssignments == null
? new NewTopic(this.name, this.partitions, this.replicas)
: new NewTopic(this.name, this.replicasAssignments);
if (!this.configs.isEmpty()) {
topic.configs(this.configs);
}
return topic;
}
/**
* Create a TopicBuilder with the supplied name.
* @param name the name.
* @return the builder.
*/
public static TopicBuilder name(String name) {
return new TopicBuilder(name);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\TopicBuilder.java | 2 |
请完成以下Java代码 | public boolean isHstsIncludeSubdomainsDisabled() {
return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
}
public String getHstsValue() {
return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() {
return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) {
this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled) | .add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请完成以下Java代码 | public class Customer {
@Id
private String id;
private Long storeId;
private Long number;
private String name;
public Customer() {
}
public Customer(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getStoreId() { | return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\unique\field\data\Customer.java | 1 |
请完成以下Java代码 | public Sentry getSentry() {
return sentryRefAttribute.getReferenceTargetElement(this);
}
public void setSentry(Sentry sentry) {
sentryRefAttribute.setReferenceTargetElement(this, sentry);
}
public ExitCriterion getExitCriterion() {
return exitCriterionRefAttribute.getReferenceTargetElement(this);
}
public void setExitCriterion(ExitCriterion exitCriterion) {
exitCriterionRefAttribute.setReferenceTargetElement(this, exitCriterion);
}
public PlanItem getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(PlanItem source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public PlanItemTransition getStandardEvent() {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(PlanItemTransition standardEvent) {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemOnPart.class, CMMN_ELEMENT_PLAN_ITEM_ON_PART)
.extendsType(OnPart.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemOnPart>() {
public PlanItemOnPart newInstance(ModelTypeInstanceContext instanceContext) { | return new PlanItemOnPartImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(PlanItem.class)
.build();
exitCriterionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERION_REF)
.idAttributeReference(ExitCriterion.class)
.build();
sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF)
.namespace(CMMN10_NS)
.idAttributeReference(Sentry.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemOnPartImpl.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Report Cube.
@param PA_ReportCube_ID
Define reporting cube for pre-calculation of summary accounting data.
*/
public void setPA_ReportCube_ID (int PA_ReportCube_ID)
{
if (PA_ReportCube_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, Integer.valueOf(PA_ReportCube_ID));
}
/** Get Report Cube.
@return Define reporting cube for pre-calculation of summary accounting data.
*/
public int getPA_ReportCube_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportCube.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getGithubRawContentUrl(String key, String path) {
if (path == null) {
return "";
}
RepositorySettings settings = getRepository(key).getSettings();
return StringUtils.removeEnd(settings.getRepositoryUri(), ".git") + "/blob/" + settings.getDefaultBranch() + "/" + path + "?raw=true";
}
private GitRepository getRepository(String key) {
GitRepository repository = repositories.get(key);
if (repository != null) {
if (!GitRepository.exists(repository.getDirectory())) {
// reinitializing the repository because folder was deleted
initRepository(key, repository.getSettings());
}
}
repository = repositories.get(key);
if (repository == null) {
throw new IllegalStateException(key + " repository is not initialized");
}
return repository;
}
private void initRepository(String key, RepositorySettings settings) {
try {
repositories.remove(key);
Path directory = getRepoDirectory(settings);
GitRepository repository = GitRepository.openOrClone(directory, settings, true);
repositories.put(key, repository);
log.info("[{}] Initialized repository", key);
onUpdate(key);
} catch (Throwable e) {
log.error("[{}] Failed to initialize repository with settings {}", key, settings, e);
}
}
private void onUpdate(String key) {
Runnable listener = updateListeners.get(key);
if (listener != null) {
log.debug("[{}] Handling repository update", key);
try { | listener.run();
} catch (Throwable e) {
log.error("[{}] Failed to handle repository update", key, e);
}
}
}
private Path getRepoDirectory(RepositorySettings settings) {
// using uri to define folder name in case repo url is changed
String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", "");
return Path.of(repositoriesFolder, name);
}
private String getBranchRef(GitRepository repository) {
return "refs/remotes/origin/" + repository.getSettings().getDefaultBranch();
}
@PreDestroy
private void preDestroy() {
executor.shutdownNow();
}
} | repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\DefaultGitSyncService.java | 2 |
请完成以下Java代码 | public String getAdminNickName() {
return adminNickName;
}
public void setAdminNickName(String adminNickName) {
this.adminNickName = adminNickName == null ? null : adminNickName.trim();
}
public Byte getLocked() {
return locked;
}
public void setLocked(Byte locked) {
this.locked = locked;
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", adminId=").append(adminId);
sb.append(", loginName=").append(loginName);
sb.append(", loginPassword=").append(loginPassword);
sb.append(", adminNickName=").append(adminNickName);
sb.append(", locked=").append(locked);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\Admin.java | 1 |
请完成以下Java代码 | public int getI_Postal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_I_Postal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set PLZ.
@param Postal
Postleitzahl
*/
@Override
public void setPostal (java.lang.String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
/** Get PLZ.
@return Postleitzahl
*/
@Override
public java.lang.String getPostal ()
{
return (java.lang.String)get_Value(COLUMNNAME_Postal);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Region.
@param RegionName
Name der Region
*/
@Override
public void setRegionName (java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name der Region
*/
@Override | public java.lang.String getRegionName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RegionName);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Postal.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getJobGroup() {
return jobGroup;
}
public void setJobGroup(int jobGroup) {
this.jobGroup = jobGroup;
}
public int getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
public String getExecutorAddress() {
return executorAddress;
}
public void setExecutorAddress(String executorAddress) {
this.executorAddress = executorAddress;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorShardingParam() {
return executorShardingParam;
}
public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
} | public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deleteByOrderId(@NonNull final OrderId orderId) {orderPayScheduleRepository.deleteByOrderId(orderId);}
@Nullable OrderSchedulingContext extractContext(final @NotNull org.compiere.model.I_C_Order orderRecord)
{
final Money grandTotal = orderBL.getGrandTotal(orderRecord);
if (grandTotal.isZero())
{
return null;
}
final PaymentTermId paymentTermId = orderBL.getPaymentTermId(orderRecord);
final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId);
if (!paymentTerm.isComplex())
{
return null;
}
return OrderSchedulingContext.builder()
.orderId(OrderId.ofRepoId(orderRecord.getC_Order_ID())) | .orderDate(TimeUtil.asLocalDate(orderRecord.getDateOrdered()))
.letterOfCreditDate(TimeUtil.asLocalDate(orderRecord.getLC_Date()))
.billOfLadingDate(TimeUtil.asLocalDate(orderRecord.getBLDate()))
.ETADate(TimeUtil.asLocalDate(orderRecord.getETA()))
.invoiceDate(TimeUtil.asLocalDate(orderRecord.getInvoiceDate()))
.grandTotal(grandTotal)
.precision(orderBL.getAmountPrecision(orderRecord))
.paymentTerm(paymentTerm)
.build();
}
public void create(@NonNull final OrderPayScheduleCreateRequest request)
{
orderPayScheduleRepository.create(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleService.java | 2 |
请完成以下Java代码 | private void setRecords(final Collection<TableRecordReference> records)
{
_records = new HashSet<>(records);
// Reset selection
_selection_AD_Table_ID = null;
_selection_pinstanceId = null;
}
public void addRecords(final Collection<TableRecordReference> records)
{
if (_records == null)
{
_records = new HashSet<>(records);
}
else
{
_records.addAll(records);
}
_selection_AD_Table_ID = null;
_selection_pinstanceId = null;
_filters = null;
}
public void setRecordsBySelection(final Class<?> modelClass, @NonNull final PInstanceId pinstanceId)
{
_selection_AD_Table_ID = InterfaceWrapperHelper.getAdTableId(modelClass);
_selection_pinstanceId = pinstanceId;
_records = null;
_filters = null;
}
public <T> void setRecordsByFilter(final Class<T> modelClass, final IQueryFilter<T> filters)
{
_filters = null;
addRecordsByFilter(modelClass, filters);
}
public <T> void addRecordsByFilter(@NonNull final Class<T> modelClass, @NonNull final IQueryFilter<T> filters)
{
_records = null;
_selection_AD_Table_ID = null;
if (_filters == null)
{
_filters = new ArrayList<>();
}
_filters.add(LockRecordsByFilter.of(modelClass, filters));
}
public List<LockRecordsByFilter> getSelection_Filters()
{ | return _filters;
}
public AdTableId getSelection_AD_Table_ID()
{
return _selection_AD_Table_ID;
}
public PInstanceId getSelection_PInstanceId()
{
return _selection_pinstanceId;
}
public Iterator<TableRecordReference> getRecordsIterator()
{
return _records == null ? null : _records.iterator();
}
public void addRecordByModel(final Object model)
{
final TableRecordReference record = TableRecordReference.of(model);
addRecords(Collections.singleton(record));
}
public void addRecordByModels(final Collection<?> models)
{
final Collection<TableRecordReference> records = convertModelsToRecords(models);
addRecords(records);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockRecords.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductValueSequenceProvider implements ValueSequenceInfoProvider
{
private final CCache<ProductCategoryId, Integer> productCategoryId2AD_Sequence_ID = CCache.newCache(I_M_Product_Category.Table_Name, 10, CCache.EXPIREMINUTES_Never);
@Override
public ProviderResult computeValueInfo(@NonNull final Object modelRecord)
{
if (!isInstanceOf(modelRecord, I_M_Product.class))
{
return ProviderResult.EMPTY;
}
final I_M_Product product = create(modelRecord, I_M_Product.class);
final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID());
final int adSequenceId = getSequenceId(productCategoryId);
if (adSequenceId <= 0)
{
return ProviderResult.EMPTY;
}
final IDocumentSequenceDAO documentSequenceDAO = Services.get(IDocumentSequenceDAO.class);
final DocumentSequenceInfo documentSequenceInfo = documentSequenceDAO.retriveDocumentSequenceInfo(adSequenceId);
return ProviderResult.of(documentSequenceInfo);
}
private int getSequenceId(@NonNull final ProductCategoryId productCategoryId)
{
return productCategoryId2AD_Sequence_ID.getOrLoad(
productCategoryId,
() -> extractSequenceId(productCategoryId, new HashSet<>()));
}
private int extractSequenceId(
@NonNull final ProductCategoryId productCategoryId,
@NonNull final Set<ProductCategoryId> seenIds)
{
final I_M_Product_Category productCategory = loadOutOfTrx(productCategoryId, I_M_Product_Category.class);
final int adSequenceId = productCategory.getAD_Sequence_ProductValue_ID();
if (adSequenceId > 0)
{
// return our result
return adSequenceId; | }
if (productCategory.getM_Product_Category_Parent_ID() > 0)
{
final ProductCategoryId productCategoryParentId = ProductCategoryId.ofRepoId(productCategory.getM_Product_Category_Parent_ID());
// first, guard against a loop
if (!seenIds.add(productCategoryParentId))
{
// there is no AD_Sequence_ID for us
return -1;
}
// recurse
return extractSequenceId(productCategoryParentId, seenIds);
}
// there is no AD_Sequence_ID for us
return -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\sequence\ProductValueSequenceProvider.java | 2 |
请完成以下Java代码 | public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
}
@Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode());
final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode);
final HUInfo pickFromHU = HUInfo.builder()
.id(huId)
.qrCode(qrCode)
.build();
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU) | );
}
private HUQRCode parseHUQRCode(final String scannedCode)
{
final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode);
if (huQRCode instanceof HUQRCode)
{
return (HUQRCode)huQRCode;
}
else
{
throw new AdempiereException("Invalid HU QR code: " + scannedCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java | 1 |
请完成以下Java代码 | public String toString()
{
return "MBPartnerLocation[ID=" + get_ID()
+ ",C_Location_ID=" + getC_Location_ID()
+ ",Name=" + getName()
+ "]";
}
@Override
protected boolean beforeSave(final boolean newRecord)
{
if (getC_Location_ID() <= 0)
{
throw new FillMandatoryException(COLUMNNAME_C_Location_ID);
}
// Set New Name only if new record
if (newRecord)
{
final int cBPartnerId = getC_BPartner_ID();
// gh12157: Please, keep in sync with de.metas.bpartner.quick_input.callout.C_BPartner_Location_QuickInput.onLocationChanged
setName(MakeUniqueLocationNameCommand.builder()
.name(getName())
.address(getC_Location())
.companyName(bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(cBPartnerId)))
.existingNames(getOtherLocationNames(cBPartnerId, getC_BPartner_Location_ID()))
.maxLength(getPOInfo().getFieldLength(I_C_BPartner_Location.COLUMNNAME_Name))
.build()
.execute());
} | return true;
}
private static List<String> getOtherLocationNames(
final int bpartnerId,
final int bpartnerLocationIdToExclude)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addNotEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, bpartnerLocationIdToExclude)
.create()
.listDistinct(I_C_BPartner_Location.COLUMNNAME_Name, String.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPartnerLocation.java | 1 |
请完成以下Java代码 | public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException
{
return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name)
.getPO(getGL_JournalBatch_ID(), get_TrxName()); }
/** Set Journal Batch.
@param GL_JournalBatch_ID
General Ledger Journal Batch
*/
public void setGL_JournalBatch_ID (int GL_JournalBatch_ID)
{ | if (GL_JournalBatch_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID));
}
/** Get Journal Batch.
@return General Ledger Journal Batch
*/
public int getGL_JournalBatch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring_Run.java | 1 |
请完成以下Java代码 | public FindPanelBuilder setEmbedded(final boolean embedded)
{
this.embedded = embedded;
return this;
}
/** @return true if the find panel will be embedded in the window */
public boolean isEmbedded()
{
return this.embedded;
}
public FindPanelBuilder setHideStatusBar(boolean hideStatusBar)
{
this.hideStatusBar = hideStatusBar;
return this;
}
public boolean isHideStatusBar()
{
return hideStatusBar;
}
public FindPanelBuilder setSearchPanelCollapsed(final boolean searchPanelCollapsed)
{
this.searchPanelCollapsed = searchPanelCollapsed;
return this; | }
public boolean isSearchPanelCollapsed()
{
return searchPanelCollapsed;
}
public FindPanelBuilder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab)
{
this.maxQueryRecordsPerTab = maxQueryRecordsPerTab;
return this;
}
public int getMaxQueryRecordsPerTab()
{
if (maxQueryRecordsPerTab != null)
{
return maxQueryRecordsPerTab;
}
else if (gridTab != null)
{
return gridTab.getMaxQueryRecords();
}
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindPanelBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public StatefulRetryInterceptorBuilder newMessageIdentifier(NewMessageIdentifier newMessageIdentifier) {
this.newMessageIdentifier = newMessageIdentifier;
return this;
}
@Override
public StatefulRetryOperationsInterceptor build() {
this.applyCommonSettings(this.factoryBean);
if (this.messageKeyGenerator != null) {
this.factoryBean.setMessageKeyGenerator(this.messageKeyGenerator);
}
if (this.newMessageIdentifier != null) {
this.factoryBean.setNewMessageIdentifier(this.newMessageIdentifier);
}
return this.factoryBean.getObject();
}
}
/**
* Builder for a stateless interceptor.
*/
public static final class StatelessRetryInterceptorBuilder | extends RetryInterceptorBuilder<StatelessRetryInterceptorBuilder, StatelessRetryOperationsInterceptor> {
private final StatelessRetryOperationsInterceptorFactoryBean factoryBean =
new StatelessRetryOperationsInterceptorFactoryBean();
StatelessRetryInterceptorBuilder() {
}
@Override
public StatelessRetryOperationsInterceptor build() {
this.applyCommonSettings(this.factoryBean);
return this.factoryBean.getObject();
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\RetryInterceptorBuilder.java | 2 |
请完成以下Java代码 | private PPOrderRouting getOrderRouting()
{
final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID());
return Services.get(IPPOrderRoutingRepository.class).getByOrderId(orderId);
}
@Override
public String toString()
{
return "MPPOrder[ID=" + get_ID()
+ "-DocumentNo=" + getDocumentNo()
+ ",IsSOTrx=" + isSOTrx()
+ ",C_DocType_ID=" + getC_DocType_ID()
+ "]";
}
/**
* Auto report the first Activity and Sub contracting if are Milestone Activity
*/
private void autoReportActivities()
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
if (activity.isMilestone()
&& (activity.isSubcontracting() || orderRouting.isFirstActivity(activity)))
{
ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder()
.order(this)
.orderActivity(activity) | .qtyMoved(activity.getQtyToDeliver())
.durationSetup(Duration.ZERO)
.duration(Duration.ZERO)
.build());
}
}
}
private void createVariances()
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
//
for (final I_PP_Order_BOMLine bomLine : getLines())
{
ppCostCollectorBL.createMaterialUsageVariance(this, bomLine);
}
//
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
ppCostCollectorBL.createResourceUsageVariance(this, activity);
}
}
} // MPPOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8082
spring:
application:
name: mall-demo
datasource:
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password: root
thymeleaf:
mode: HTML5
encoding: utf-8
servlet:
content-type: text/html
cache: false #开发时关闭缓存,不然没法看到实时页面
mvc:
pathmatch:
matching-strategy: ant_path_matcher
mybatis:
| mapper-locations:
- classpath:mapper/*.xml
- classpath*:com/**/mapper/*.xml
logging:
level:
root: info
com.macro.mall: debug
host:
mall:
admin: http://localhost:8080 | repos\mall-master\mall-demo\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the dateBegin property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateBegin() {
return dateBegin;
}
/**
* Sets the value of the dateBegin property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateBegin(XMLGregorianCalendar value) {
this.dateBegin = value;
}
/**
* Gets the value of the dateEnd property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateEnd() {
return dateEnd; | }
/**
* Sets the value of the dateEnd property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateEnd(XMLGregorianCalendar value) {
this.dateEnd = value;
}
/**
* Gets the value of the acid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAcid() {
return acid;
}
/**
* Sets the value of the acid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcid(String value) {
this.acid = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CaseDetailType.java | 1 |
请完成以下Java代码 | private boolean isRedirectToFile()
{
return redirectDirName != null && !redirectDirName.isEmpty();
}
public PrinterHWList createPrinterHW()
{
final List<PrinterHW> printerHWs = new ArrayList<>();
for (final PrintService printService : getPrintServices())
{
final PrinterHW printerHW = new PrinterHW();
printerHW.setName(printService.getName());
final List<PrinterHWMediaSize> printerHWMediaSizes = new ArrayList<>();
printerHW.setPrinterHWMediaSizes(printerHWMediaSizes);
final List<PrinterHWMediaTray> printerHWMediaTrays = new ArrayList<>();
printerHW.setPrinterHWMediaTrays(printerHWMediaTrays);
// 04005: detect the default media tray
final MediaTray defaultMediaTray = (MediaTray)printService.getDefaultAttributeValue(MediaTray.class);
final Media[] medias = (Media[])printService.getSupportedAttributeValues(Media.class, null, null); // flavor=null, attributes=null
for (final Media media : medias)
{
if (media instanceof MediaSizeName)
{
final String name = media.toString();
// final MediaSizeName mediaSize = (MediaSizeName)media;
final PrinterHWMediaSize printerHWMediaSize = new PrinterHWMediaSize();
printerHWMediaSize.setName(name);
// printerHWMediaSize.setIsDefault(isDefault);
printerHWMediaSizes.add(printerHWMediaSize);
}
else if (media instanceof MediaTray)
{
final MediaTray mediaTray = (MediaTray)media;
final String name = mediaTray.toString();
final String trayNumber = Integer.toString(mediaTray.getValue());
final PrinterHWMediaTray printerHWMediaTray = new PrinterHWMediaTray();
printerHWMediaTray.setName(name); | printerHWMediaTray.setTrayNumber(trayNumber);
// 04005: default media tray shall be first in the list
if (mediaTray.equals(defaultMediaTray))
{
printerHWMediaTrays.add(0, printerHWMediaTray);
}
else
{
printerHWMediaTrays.add(printerHWMediaTray);
}
}
}
printerHWs.add(printerHW);
}
final PrinterHWList list = new PrinterHWList();
list.setHwPrinters(printerHWs);
return list;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintingEngine.java | 1 |
请完成以下Java代码 | public int getA_Start_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Start_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document Date.
@param DateDoc
Date of the Document
*/
public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date.
@return Date of the Document
*/
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType); | }
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Forecast.java | 1 |
请完成以下Java代码 | public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDomainById(tenantId, new DomainId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(domainDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
@Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteDomainById(tenantId, (DomainId) id);
}
private DomainInfo getDomainInfo(Domain domain) {
if (domain == null) { | return null;
}
List<OAuth2ClientInfo> clients = oauth2ClientDao.findByDomainId(domain.getUuidId()).stream()
.map(OAuth2ClientInfo::new)
.sorted(Comparator.comparing(OAuth2ClientInfo::getTitle))
.collect(Collectors.toList());
return new DomainInfo(domain, clients);
}
@Override
public EntityType getEntityType() {
return EntityType.DOMAIN;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\domain\DomainServiceImpl.java | 1 |
请完成以下Java代码 | public void setES_FTS_Index_Queue_ID (final int ES_FTS_Index_Queue_ID)
{
if (ES_FTS_Index_Queue_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, ES_FTS_Index_Queue_ID);
}
@Override
public int getES_FTS_Index_Queue_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Index_Queue_ID);
}
/**
* EventType AD_Reference_ID=541373
* Reference name: ES_FTS_Index_Queue_EventType
*/
public static final int EVENTTYPE_AD_Reference_ID=541373;
/** Update = U */
public static final String EVENTTYPE_Update = "U";
/** Delete = D */
public static final String EVENTTYPE_Delete = "D";
@Override
public void setEventType (final java.lang.String EventType)
{
set_ValueNoCheck (COLUMNNAME_EventType, EventType);
}
@Override
public java.lang.String getEventType()
{
return get_ValueAsString(COLUMNNAME_EventType);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setProcessed (final boolean Processed)
{ | set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User login(String email, String password) {
if (email == null || email.isBlank()) {
throw new IllegalArgumentException("email is required.");
}
if (password == null || password.isBlank()) {
throw new IllegalArgumentException("password is required.");
}
return userRepository
.findByEmail(email)
.filter(user -> passwordEncoder.matches(password, user.getPassword()))
.orElseThrow(() -> new IllegalArgumentException("invalid email or password."));
}
/**
* Update user information.
*
* @param userId The user who requested the update
* @param email users email | * @param username users username
* @param password users password
* @param bio users bio
* @param imageUrl users imageUrl
* @return Returns the updated user
*/
public User updateUserDetails(
UUID userId, String email, String username, String password, String bio, String imageUrl) {
if (userId == null) {
throw new IllegalArgumentException("user id is required.");
}
return userRepository.updateUserDetails(userId, passwordEncoder, email, username, password, bio, imageUrl);
}
} | repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\UserService.java | 2 |
请完成以下Java代码 | public class DefinitionsRootExport implements BpmnXMLConstants {
/** default namespaces for definitions */
protected static final Set<String> defaultNamespaces = new HashSet<String>(
asList(
BPMN2_PREFIX,
XSI_PREFIX,
XSD_PREFIX,
ACTIVITI_EXTENSIONS_PREFIX,
BPMNDI_PREFIX,
OMGDC_PREFIX,
OMGDI_PREFIX
)
);
protected static final List<ExtensionAttribute> defaultAttributes = asList(
new ExtensionAttribute(TYPE_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE),
new ExtensionAttribute(TARGET_NAMESPACE_ATTRIBUTE)
);
@SuppressWarnings("unchecked")
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
xtw.writeStartDocument(encoding, "1.0");
// start definitions root element
xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_DEFINITIONS, BPMN2_NAMESPACE);
xtw.setDefaultNamespace(BPMN2_NAMESPACE);
xtw.writeDefaultNamespace(BPMN2_NAMESPACE);
xtw.writeNamespace(BPMN2_PREFIX, BPMN2_NAMESPACE);
xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE);
xtw.writeNamespace(ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE);
xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE);
xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
for (String prefix : model.getNamespaces().keySet()) {
if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix)) xtw.writeNamespace( | prefix,
model.getNamespaces().get(prefix)
);
}
xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE);
xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace());
} else {
xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE);
}
BpmnXMLUtil.writeCustomAttributes(
model.getDefinitionsAttributes().values(),
xtw,
model.getNamespaces(),
defaultAttributes
);
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\export\DefinitionsRootExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PriceRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(PriceRepository.class);
private final Map<Long, Price> priceMap = new HashMap<>();
public Price getPrice(Long productId){
LOGGER.info("Getting Price from Price Repo With Product Id {}", productId);
if(!priceMap.containsKey(productId)){
LOGGER.error("Price Not Found for Product Id {}", productId);
throw new PriceNotFoundException("Product Not Found");
}
return priceMap.get(productId);
}
@PostConstruct
private void setupRepo(){
Price price1 = getPrice(100001L, 12.5, 2.5);
priceMap.put(100001L, price1);
Price price2 = getPrice(100002L, 10.5, 2.1);
priceMap.put(100002L, price2); | Price price3 = getPrice(100003L, 18.5, 2.0);
priceMap.put(100003L, price3);
Price price4 = getPrice(100004L, 18.5, 2.0);
priceMap.put(100004L, price4);
}
private static Price getPrice(long productId, double priceAmount, double discount) {
Price price = new Price();
price.setProductId(productId);
price.setPriceAmount(priceAmount);
price.setDiscount(discount);
return price;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry2\src\main\java\com\baeldung\opentelemetry\repository\PriceRepository.java | 2 |
请完成以下Java代码 | public boolean isOpen() {
boolean isOpen = delegate.isOpen();
log.info("[I236] isOpen: " + isOpen);
return isOpen;
}
public EntityTransaction getTransaction() {
log.info("[I240] getTransaction()");
return delegate.getTransaction();
}
public EntityManagerFactory getEntityManagerFactory() {
return delegate.getEntityManagerFactory();
}
public CriteriaBuilder getCriteriaBuilder() {
return delegate.getCriteriaBuilder();
}
public Metamodel getMetamodel() {
return delegate.getMetamodel();
}
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return delegate.createEntityGraph(rootType); | }
public EntityGraph<?> createEntityGraph(String graphName) {
return delegate.createEntityGraph(graphName);
}
public EntityGraph<?> getEntityGraph(String graphName) {
return delegate.getEntityGraph(graphName);
}
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return delegate.getEntityGraphs(entityClass);
}
public EntityManagerWrapper(EntityManager delegate) {
this.delegate = delegate;
}
}
} | repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\CarsODataJPAServiceFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InsuranceContractRequiredTemplates templateId(String templateId) {
this.templateId = templateId;
return this;
}
/**
* Alberta-Id der Dokumentenvorlage - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /template
* @return templateId
**/
@Schema(example = "13e2a423-24e8-4844-b710-3d1e0ee60c92", description = "Alberta-Id der Dokumentenvorlage - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /template")
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public InsuranceContractRequiredTemplates careType(BigDecimal careType) {
this.careType = careType;
return this;
}
/**
* Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)
* @return careType
**/
@Schema(example = "1", description = "Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)")
public BigDecimal getCareType() {
return careType;
}
public void setCareType(BigDecimal careType) {
this.careType = careType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractRequiredTemplates insuranceContractRequiredTemplates = (InsuranceContractRequiredTemplates) o;
return Objects.equals(this.templateId, insuranceContractRequiredTemplates.templateId) && | Objects.equals(this.careType, insuranceContractRequiredTemplates.careType);
}
@Override
public int hashCode() {
return Objects.hash(templateId, careType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractRequiredTemplates {\n");
sb.append(" templateId: ").append(toIndentedString(templateId)).append("\n");
sb.append(" careType: ").append(toIndentedString(careType)).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\InsuranceContractRequiredTemplates.java | 2 |
请完成以下Java代码 | public java.sql.Timestamp getDatePromised()
{
return get_ValueAsTimestamp(COLUMNNAME_DatePromised);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{ | return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRemotePurchaseOrderId (final @Nullable java.lang.String RemotePurchaseOrderId)
{
set_Value (COLUMNNAME_RemotePurchaseOrderId, RemotePurchaseOrderId);
}
@Override
public java.lang.String getRemotePurchaseOrderId()
{
return get_ValueAsString(COLUMNNAME_RemotePurchaseOrderId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate_Alloc.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.