instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public static Object getFieldValue(Object object, String fieldName) {
//根据 对象和属性名通过反射 调用上面的方法获取 Field对象
Field field = getDeclaredField(object, fieldName);
//抑制Java对其的检查
field.setAccessible(true);
try {
//获取 object 中 field 所代表的属性值
return field.get(object);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
return null;
}
/**
* 获取 目标对象
*
* @param proxy 代理对象
* @return
* @throws Exception
*/
public static Object getTarget(Object proxy) throws Exception {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;//不是代理对象
}
if (AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { //cglib
return getCglibProxyTargetObject(proxy);
}
}
private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
|
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
}
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}
}
|
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\utils\ReflectionUtils.java
| 1
|
请完成以下Java代码
|
public IInvoiceHistoryTabHandler getInvoiceHistoryTabHandler()
{
return ihTabHandler;
}
public int getC_BPartner_ID()
{
return C_BPartner_ID;
}
public int getM_Product_ID()
{
return M_Product_ID;
}
public int getM_Warehouse_ID()
{
return M_Warehouse_ID;
}
public int getM_AttributeSetInstance_ID()
{
return M_AttributeSetInstance_ID;
}
public Timestamp getDatePromisedOrNull()
{
return DatePromised;
}
public boolean isRowSelectionAllowed()
{
return rowSelectionAllowed;
}
public static InvoiceHistoryContextBuilder builder()
{
return new InvoiceHistoryContextBuilder();
}
public static class InvoiceHistoryContextBuilder
{
public InvoiceHistoryContext build()
{
return new InvoiceHistoryContext(this);
}
private int C_BPartner_ID = -1;
private int M_Product_ID = -1;
private int M_Warehouse_ID = -1;
|
private int M_AttributeSetInstance_ID = -1;
private Timestamp DatePromised = null;
private boolean rowSelectionAllowed = false;
public InvoiceHistoryContextBuilder setC_BPartner_ID(final int c_BPartner_ID)
{
C_BPartner_ID = c_BPartner_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_Product_ID(final int m_Product_ID)
{
M_Product_ID = m_Product_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_Warehouse_ID(final int m_Warehouse_ID)
{
M_Warehouse_ID = m_Warehouse_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_AttributeSetInstance_ID(final int m_AttributeSetInstance_ID)
{
M_AttributeSetInstance_ID = m_AttributeSetInstance_ID;
return this;
}
public InvoiceHistoryContextBuilder setDatePromised(final Timestamp DatePromised)
{
this.DatePromised = DatePromised;
return this;
}
public InvoiceHistoryContextBuilder setRowSelectionAllowed(final boolean rowSelectionAllowed)
{
this.rowSelectionAllowed = rowSelectionAllowed;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\history\impl\InvoiceHistoryContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AcctSchemaElementId implements RepoIdAware
{
int repoId;
@JsonCreator
private AcctSchemaElementId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_AcctSchema_Element_ID");
}
public static AcctSchemaElementId ofRepoId(final int repoId)
{
return new AcctSchemaElementId(repoId);
}
@Nullable
public static AcctSchemaElementId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(final AcctSchemaElementId id)
{
|
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final AcctSchemaElementId id1, @Nullable final AcctSchemaElementId id2)
{
return Objects.equals(id1, id2);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaElementId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CategoryEntity implements Serializable{
/** 主键 */
private String id;
/** 分类名称 */
private String category;
/** 父分类id (一级分类的parentId为空) */
private String parentId;
/** 排序(权值越高,排名越前)*/
private int sort;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getSort() {
return sort;
}
|
public void setSort(int sort) {
this.sort = sort;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return "CategoryEntity{" +
"id='" + id + '\'' +
", category='" + category + '\'' +
", parentId='" + parentId + '\'' +
", sort=" + sort +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\CategoryEntity.java
| 2
|
请完成以下Java代码
|
public int getLeichMehl_PluFile_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_Config_ID);
}
@Override
public void setReplacement (final java.lang.String Replacement)
{
set_Value (COLUMNNAME_Replacement, Replacement);
}
@Override
public java.lang.String getReplacement()
{
return get_ValueAsString(COLUMNNAME_Replacement);
}
/**
* ReplacementSource AD_Reference_ID=541598
* Reference name: ReplacementSourceList
*/
public static final int REPLACEMENTSOURCE_AD_Reference_ID=541598;
/** Product = P */
public static final String REPLACEMENTSOURCE_Product = "P";
/** PPOrder = PP */
public static final String REPLACEMENTSOURCE_PPOrder = "PP";
/** CustomProcessResult = CP */
public static final String REPLACEMENTSOURCE_CustomProcessResult = "CP";
@Override
public void setReplacementSource (final java.lang.String ReplacementSource)
{
set_Value (COLUMNNAME_ReplacementSource, ReplacementSource);
}
@Override
public java.lang.String getReplacementSource()
{
return get_ValueAsString(COLUMNNAME_ReplacementSource);
}
@Override
public void setReplaceRegExp (final @Nullable java.lang.String ReplaceRegExp)
{
set_Value (COLUMNNAME_ReplaceRegExp, ReplaceRegExp);
}
@Override
public java.lang.String getReplaceRegExp()
{
return get_ValueAsString(COLUMNNAME_ReplaceRegExp);
}
@Override
public void setTargetFieldName (final java.lang.String TargetFieldName)
{
set_Value (COLUMNNAME_TargetFieldName, TargetFieldName);
}
@Override
public java.lang.String getTargetFieldName()
{
return get_ValueAsString(COLUMNNAME_TargetFieldName);
}
/**
|
* TargetFieldType AD_Reference_ID=541611
* Reference name: AttributeTypeList
*/
public static final int TARGETFIELDTYPE_AD_Reference_ID=541611;
/** textArea = textArea */
public static final String TARGETFIELDTYPE_TextArea = "textArea";
/** EAN13 = EAN13 */
public static final String TARGETFIELDTYPE_EAN13 = "EAN13";
/** EAN128 = EAN128 */
public static final String TARGETFIELDTYPE_EAN128 = "EAN128";
/** numberField = numberField */
public static final String TARGETFIELDTYPE_NumberField = "numberField";
/** date = date */
public static final String TARGETFIELDTYPE_Date = "date";
/** unitChar = unitChar */
public static final String TARGETFIELDTYPE_UnitChar = "unitChar";
/** graphic = graphic */
public static final String TARGETFIELDTYPE_Graphic = "graphic";
@Override
public void setTargetFieldType (final java.lang.String TargetFieldType)
{
set_Value (COLUMNNAME_TargetFieldType, TargetFieldType);
}
@Override
public java.lang.String getTargetFieldType()
{
return get_ValueAsString(COLUMNNAME_TargetFieldType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java
| 1
|
请完成以下Java代码
|
private static IStringExpression buildSqlOrderBy(
@NonNull final MLookupInfo.SqlQuery lookupInfoSqlQuery,
boolean orderByLevenshteinDistance)
{
final CompositeStringExpression.Builder builder = IStringExpression.composer();
//
// 1. LEVENSHTEIN distance from user typed string to display name
if (orderByLevenshteinDistance)
{
final TranslatableParameterizedString displayColumnSql = lookupInfoSqlQuery.getDisplayColumnSql();
builder.append("levenshtein(")
.append(DBConstants.FUNCNAME_unaccent_string).append("(").append(LookupDataSourceContext.PARAM_FilterSqlWithoutWildcards).append(", 1)")
.append(", ")
.append(DBConstants.FUNCNAME_unaccent_string).append("(").append(displayColumnSql).append(", 1)")
.append(")");
}
//
// 2. Display Name
if (!builder.isEmpty())
{
builder.append(", ");
}
builder.append(StringUtils.trimBlankToOptional(lookupInfoSqlQuery.getSqlOrderBy())
.orElse(String.valueOf(MLookupInfo.SqlQuery.COLUMNINDEX_DisplayName)));
|
//
return builder.build();
}
public SqlForFetchingLookups withSqlWhere_ValidationRules(@Nullable IStringExpression sqlWhere_ValidationRules)
{
return !Objects.equals(this.sqlWhere_ValidationRules, sqlWhere_ValidationRules)
? toBuilder().sqlWhere_ValidationRules(sqlWhere_ValidationRules).build()
: this;
}
public String toOneLineString()
{
return sql.toOneLineString();
}
public Set<CtxName> getParameters()
{
return sql.getParameters();
}
public String evaluate(final LookupDataSourceContext evalCtx)
{
return sql.evaluate(evalCtx, OnVariableNotFound.Fail);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlForFetchingLookups.java
| 1
|
请完成以下Java代码
|
public IPaymentStringDataProvider getDataProvider(final Properties ctx, final IPaymentStringParser paymentStringParser, final String paymentStringText) throws PaymentStringParseException
{
Check.assumeNotNull(paymentStringParser, "paymentStringParser not null");
Check.assumeNotEmpty(paymentStringText, "paymentStringText not empty");
final PaymentString paymentString;
try
{
paymentString = paymentStringParser.parse(paymentStringText);
}
catch (final IndexOutOfBoundsException ex)
{
throw new PaymentStringParseException(ERR_InvalidPaymentStringLength, ex);
}
final List<String> collectedErrors = paymentString.getCollectedErrors();
if (!collectedErrors.isEmpty())
{
final StringBuilder exceptions = new StringBuilder();
for (final String exception : collectedErrors)
{
exceptions.append(exception)
.append("\n");
}
throw new PaymentStringParseException(exceptions.toString());
}
final IPaymentStringDataProvider dataProvider = paymentString.getDataProvider();
return dataProvider;
}
@Override
public IPaymentStringDataProvider getQRDataProvider(@NonNull final String qrCode) throws PaymentStringParseException
{
Check.assumeNotEmpty(qrCode, "paymentStringText not empty");
final IPaymentStringParser paymentStringParser = paymentStringParserFactory.getParser(PaymentParserType.QRCode.getType());
|
final PaymentString paymentString;
try
{
paymentString = paymentStringParser.parse(qrCode);
}
catch (final IndexOutOfBoundsException ex)
{
throw new PaymentStringParseException(ERR_InvalidPaymentStringLength, ex);
}
final List<String> collectedErrors = paymentString.getCollectedErrors();
if (!collectedErrors.isEmpty())
{
final StringBuilder exceptions = new StringBuilder();
for (final String exception : collectedErrors)
{
exceptions.append(exception)
.append("\n");
}
throw new PaymentStringParseException(exceptions.toString());
}
final IPaymentStringDataProvider dataProvider = paymentString.getDataProvider();
return dataProvider;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaymentStringBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public WarehouseInfo getWarehouseInfoByRepoId(final int warehouseRepoId)
{
return warehouseService.getWarehouseInfoByRepoId(warehouseRepoId);
}
public LocatorInfo getLocatorInfoByRepoId(final int locatorRepoId)
{
return warehouseService.getLocatorInfoByRepoId(locatorRepoId);
}
public Stream<I_DD_Order> stream(@NonNull final DDOrderQuery query)
{
return ddOrderService.streamDDOrders(query);
}
public I_DD_Order getDDOrderById(final DDOrderId ddOrderId)
{
return ddOrderService.getById(ddOrderId);
}
public Map<DDOrderId, List<I_DD_OrderLine>> getLinesByDDOrderIds(final Set<DDOrderId> ddOrderIds)
{
return ddOrderService.streamLinesByDDOrderIds(ddOrderIds)
.collect(Collectors.groupingBy(ddOrderLine -> DDOrderId.ofRepoId(ddOrderLine.getDD_Order_ID()), Collectors.toList()));
}
public Map<DDOrderLineId, List<DDOrderMoveSchedule>> getSchedulesByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds)
{
if (ddOrderLineIds.isEmpty()) {return ImmutableMap.of();}
final Map<DDOrderLineId, List<DDOrderMoveSchedule>> map = ddOrderMoveScheduleService.getByDDOrderLineIds(ddOrderLineIds)
.stream()
.collect(Collectors.groupingBy(DDOrderMoveSchedule::getDdOrderLineId, Collectors.toList()));
return CollectionUtils.fillMissingKeys(map, ddOrderLineIds, ImmutableList.of());
}
public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleService.hasInTransitSchedules(inTransitLocatorId);
}
public ZoneId getTimeZone(final OrgId orgId)
{
return orgDAO.getTimeZone(orgId);
|
}
public HUInfo getHUInfo(final HuId huId) {return huService.getHUInfoById(huId);}
@Nullable
public SalesOrderRef getSalesOderRef(@NonNull final I_DD_Order ddOrder)
{
final OrderId salesOrderId = OrderId.ofRepoIdOrNull(ddOrder.getC_Order_ID());
return salesOrderId != null ? sourceDocService.getSalesOderRef(salesOrderId) : null;
}
@Nullable
public ManufacturingOrderRef getManufacturingOrderRef(@NonNull final I_DD_Order ddOrder)
{
final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID());
return ppOrderId != null ? sourceDocService.getManufacturingOrderRef(ppOrderId) : null;
}
@NonNull
public PlantInfo getPlantInfo(@NonNull final ResourceId plantId)
{
return sourceDocService.getPlantInfo(plantId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoaderSupportingServices.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<PmsProductCategory> getList(Long parentId, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum, pageSize);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.setOrderByClause("sort desc");
example.createCriteria().andParentIdEqualTo(parentId);
return productCategoryMapper.selectByExample(example);
}
@Override
public int delete(Long id) {
return productCategoryMapper.deleteByPrimaryKey(id);
}
@Override
public PmsProductCategory getItem(Long id) {
return productCategoryMapper.selectByPrimaryKey(id);
}
@Override
public int updateNavStatus(List<Long> ids, Integer navStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setNavStatus(navStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
public int updateShowStatus(List<Long> ids, Integer showStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setShowStatus(showStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
|
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
public List<PmsProductCategoryWithChildrenItem> listWithChildren() {
return productCategoryDao.listWithChildren();
}
/**
* 根据分类的parentId设置分类的level
*/
private void setCategoryLevel(PmsProductCategory productCategory) {
//没有父分类时为一级分类
if (productCategory.getParentId() == 0) {
productCategory.setLevel(0);
} else {
//有父分类时选择根据父分类level设置
PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
if (parentCategory != null) {
productCategory.setLevel(parentCategory.getLevel() + 1);
} else {
productCategory.setLevel(0);
}
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductCategoryServiceImpl.java
| 2
|
请完成以下Java代码
|
public PickingSlotView getByIdOrNull(final ViewId pickingSlotViewId)
{
final boolean create = true;
return getOrCreatePickingSlotView(pickingSlotViewId, create);
}
private PickingSlotView getOrCreatePickingSlotView(@NonNull final ViewId pickingSlotViewId, final boolean create)
{
final PackageableView packageableView = getPackageableViewByPickingSlotViewId(pickingSlotViewId);
final DocumentId packageableRowId = extractRowId(pickingSlotViewId);
if (create)
{
return packageableView.computePickingSlotViewIfAbsent(
packageableRowId,
() -> {
final PackageableRow packageableRow = packageableView.getById(packageableRowId);
final CreateViewRequest createViewRequest = CreateViewRequest
.builder(PickingConstants.WINDOWID_PickingSlotView, JSONViewDataType.includedView)
.setParentViewId(packageableView.getViewId())
.setParentRowId(packageableRow.getId())
.build();
// provide all pickingView's M_ShipmentSchedule_IDs to the factory, because we want to show the same picking slots and picked HU-rows for all of them.
final Set<ShipmentScheduleId> allShipmentScheduleIds = packageableView
.streamByIds(DocumentIdsSelection.ALL)
.map(PackageableRow::cast)
.map(PackageableRow::getShipmentScheduleId)
.collect(ImmutableSet.toImmutableSet());
return pickingSlotViewFactory.createView(createViewRequest, allShipmentScheduleIds);
});
}
else
{
return packageableView.getPickingSlotViewOrNull(packageableRowId);
}
}
@Override
public void closeById(@NonNull final ViewId pickingSlotViewId, @NonNull final ViewCloseAction closeAction)
{
final DocumentId rowId = extractRowId(pickingSlotViewId);
final PackageableView packageableView = getPackageableViewByPickingSlotViewId(pickingSlotViewId);
packageableView.removePickingSlotView(rowId, closeAction);
}
@Override
public void invalidateView(final ViewId pickingSlotViewId)
{
final PickingSlotView pickingSlotView = getOrCreatePickingSlotView(pickingSlotViewId, false/* create */);
if (pickingSlotView == null)
{
return;
}
|
final PackageableView packageableView = getPackageableViewByPickingSlotViewId(pickingSlotViewId);
if (packageableView != null)
{
//we have to invalidate all the related pickingSlotViews in order to make sure the
//changes available in UI when selecting different `packageableRows`
packageableView.invalidatePickingSlotViews();
}
pickingSlotView.invalidateAll();
ViewChangesCollector.getCurrentOrAutoflush()
.collectFullyChanged(pickingSlotView);
}
@Override
public Stream<IView> streamAllViews()
{
// Do we really have to implement this?
return Stream.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewsIndexStorage.java
| 1
|
请完成以下Java代码
|
protected @NonNull Map<String, String> getSource() {
return source;
}
protected @NonNull Map<String, Object> getTarget() {
return target;
}
@SuppressWarnings("all")
public Source from(@NonNull String... keys) {
String[] resolvedKeys = Arrays.stream(ArrayUtils.nullSafeArray(keys, String.class))
.filter(StringUtils::hasText)
.collect(Collectors.toList())
.toArray(new String[0]);
return new Source(resolvedKeys);
}
protected interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
public class Source {
private final String[] keys;
private Source(@NonNull String[] keys) {
Assert.notNull(keys, "The String array of keys must not be null");
this.keys = keys;
}
public void to(String key) {
to(key, v -> v);
}
public void to(@NonNull String key, @NonNull Function<String, Object> function) {
|
String[] keys = this.keys;
Assert.state(keys.length == 1,
String.format("Source size [%d] cannot be transformed as one argument", keys.length));
Map<String, String> source = getSource();
if (Arrays.stream(keys).allMatch(source::containsKey)) {
getTarget().put(key, function.apply(source.get(keys[0])));
}
}
public void to(String key, TriFunction<String, String, String, Object> function) {
String[] keys = this.keys;
Assert.state(keys.length == 3,
String.format("Source size [%d] cannot be consumed as three arguments", keys.length));
Map<String, String> source = getSource();
if (Arrays.stream(keys).allMatch(source::containsKey)) {
getTarget().put(key, function.apply(source.get(keys[0]), source.get(keys[1]), source.get(keys[2])));
}
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-cloud\src\main\java\org\springframework\geode\cloud\bindings\MapMapper.java
| 1
|
请完成以下Java代码
|
protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(final @NonNull BPartnerId bPartnerId)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId);
final Set<UserGroupId> assignedUserGroupIds = userGroupRepository.getAssignedGroupIdsByUserId(UserId.ofRepoId(bPartner.getCreatedBy()));
if (Check.isEmpty(assignedUserGroupIds))
{
return Optional.empty();
}
return Optional.of(externalSystemConfigRepo.getActiveByType(getExternalSystemType())
.stream()
.filter(ExternalSystemParentConfig::isActive)
.map(ExternalSystemParentConfig::getChildConfig)
.map(ExternalSystemRabbitMQConfig::cast)
.filter(ExternalSystemRabbitMQConfig::isSyncBPartnerToRabbitMQ)
.filter(config -> config.shouldExportBasedOnUserGroup(assignedUserGroupIds))
.map(ExternalSystemRabbitMQConfig::getId)
.collect(ImmutableSet.toImmutableSet()));
}
@Override
@NonNull
protected Map<String, String> buildParameters(final @NonNull IExternalSystemChildConfig childConfig, final @NonNull BPartnerId bPartnerId)
{
final ExternalSystemRabbitMQConfig rabbitMQConfig = ExternalSystemRabbitMQConfig.cast(childConfig);
final Map<String, String> parameters = new HashMap<>();
parameters.put(ExternalSystemConstants.PARAM_RABBITMQ_HTTP_URL, rabbitMQConfig.getRemoteUrl());
parameters.put(ExternalSystemConstants.PARAM_RABBITMQ_HTTP_ROUTING_KEY, rabbitMQConfig.getRoutingKey());
parameters.put(ExternalSystemConstants.PARAM_BPARTNER_ID, String.valueOf(BPartnerId.toRepoId(bPartnerId)));
parameters.put(ExternalSystemConstants.PARAM_RABBIT_MQ_AUTH_TOKEN, rabbitMQConfig.getAuthToken());
return parameters;
}
@Override
|
protected boolean isSyncBPartnerEnabled(final @NonNull IExternalSystemChildConfig childConfig)
{
final ExternalSystemRabbitMQConfig rabbitMQConfig = ExternalSystemRabbitMQConfig.cast(childConfig);
return rabbitMQConfig.isSyncBPartnerToRabbitMQ();
}
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.RabbitMQ;
}
@Override
protected String getExternalCommand()
{
return EXTERNAL_SYSTEM_COMMAND_EXPORT_BPARTNER;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\ExportBPartnerToRabbitMQService.java
| 1
|
请完成以下Java代码
|
private <T> T get(final String key, Class<T> aClass) {
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
return redisTemplate.execute((RedisConnection connection) -> {
Object nativeConnection = connection.getNativeConnection();
Object result = null;
if (nativeConnection instanceof JedisCommands) {
result = ((JedisCommands) nativeConnection).get(key);
}
return (T) result;
});
}
/**
* @param millis 毫秒
* @param nanos 纳秒
* @Title: seleep
* @Description: 线程等待时间
* @author yuhao.wang
*/
private void seleep(long millis, int nanos) {
try {
Thread.sleep(millis, random.nextInt(nanos));
} catch (InterruptedException e) {
logger.info("获取分布式锁休眠被中断:", e);
}
}
public String getLockKeyLog() {
return lockKeyLog;
}
public void setLockKeyLog(String lockKeyLog) {
this.lockKeyLog = lockKeyLog;
}
|
public int getExpireTime() {
return expireTime;
}
public void setExpireTime(int expireTime) {
this.expireTime = expireTime;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
}
|
repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\redis\lock\RedisLock3.java
| 1
|
请完成以下Java代码
|
public void setAvailabilityInfoRow(@NonNull final PurchaseRow availabilityResultRow)
{
setAvailabilityInfoRows(ImmutableList.of(availabilityResultRow));
}
public void setAvailabilityInfoRows(@NonNull final List<PurchaseRow> availabilityResultRows)
{
assertRowType(PurchaseRowType.LINE);
availabilityResultRows.forEach(availabilityResultRow -> availabilityResultRow.assertRowType(PurchaseRowType.AVAILABILITY_DETAIL));
// If there is at least one "available on vendor" row,
// we shall order directly and not aggregate later on a Purchase Order.
final boolean allowPOAggregation = availabilityResultRows
.stream()
.noneMatch(row -> row.getRowId().isAvailableOnVendor());
setIncludedRows(ImmutableList.copyOf(availabilityResultRows));
setPurchaseCandidatesGroup(getPurchaseCandidatesGroup().allowingPOAggregation(allowPOAggregation));
}
|
public Stream<PurchaseCandidatesGroup> streamPurchaseCandidatesGroup()
{
final Stream<PurchaseCandidatesGroup> includedRowsStream = getIncludedRows()
.stream()
.flatMap(PurchaseRow::streamPurchaseCandidatesGroup);
final PurchaseCandidatesGroup candidatesGroup = getPurchaseCandidatesGroup();
if (candidatesGroup == null)
{
return includedRowsStream;
}
else
{
return Stream.concat(Stream.of(candidatesGroup), includedRowsStream);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class PriceListFilter implements Predicate<I_M_PriceList>
{
ImmutableSet<CountryId> countryIds;
boolean acceptNoCountry;
SOTrx soTrx;
CurrencyId currencyId;
@Override
public boolean test(final I_M_PriceList priceList)
{
return isCountryMatching(priceList)
&& isSOTrxMatching(priceList)
&& isCurrencyMatching(priceList)
;
}
private boolean isCurrencyMatching(final I_M_PriceList priceList)
{
if (currencyId == null)
{
return true;
}
else
{
return currencyId.equals(CurrencyId.ofRepoId(priceList.getC_Currency_ID()));
}
}
private boolean isCountryMatching(final I_M_PriceList priceList)
{
if (countryIds == null)
{
return true;
}
final CountryId priceListCountryId = CountryId.ofRepoIdOrNull(priceList.getC_Country_ID());
if (priceListCountryId == null && acceptNoCountry)
|
{
return true;
}
if (countryIds.isEmpty())
{
return priceListCountryId == null;
}
else
{
return countryIds.contains(priceListCountryId);
}
}
private boolean isSOTrxMatching(final I_M_PriceList priceList)
{
return soTrx == null || soTrx.isSales() == priceList.isSOPriceList();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\PriceListsCollection.java
| 2
|
请完成以下Java代码
|
protected ArrayKey extractCurrentHUKey(final IAllocationRequest request)
{
// NOTE: in case of maxHUsToCreate == 1 try to load all products in one HU
return maxHUsToCreate == 1
? SHARED_CurrentHUKey
: super.extractCurrentHUKey(request);
}
@Override
public boolean isAllowCreateNewHU()
{
// Check if we already reached the maximum number of HUs that we are allowed to create
return getCreatedHUsCount() < maxHUsToCreate;
}
public HUProducerDestination setMaxHUsToCreate(final int maxHUsToCreate)
{
Check.assumeGreaterOrEqualToZero(maxHUsToCreate, "maxHUsToCreate");
this.maxHUsToCreate = maxHUsToCreate;
return this;
}
|
/**
* Then this producer creates a new HU, than i uses the given {@code parentHUItem} for the new HU's {@link I_M_HU#COLUMN_M_HU_Item_Parent_ID}.
*
* @param parentHUItem
*/
public HUProducerDestination setParent_HU_Item(final I_M_HU_Item parentHUItem)
{
this.parentHUItem = parentHUItem;
return this;
}
@Override
protected I_M_HU_Item getParent_HU_Item()
{
return parentHUItem;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUProducerDestination.java
| 1
|
请完成以下Java代码
|
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public boolean isInheritBusinessKey() {
return inheritBusinessKey;
}
public void setInheritBusinessKey(boolean inheritBusinessKey) {
this.inheritBusinessKey = inheritBusinessKey;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) {
this.fallbackToDefaultTenant = fallbackToDefaultTenant;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
|
}
public String getCaseInstanceIdVariableName() {
return caseInstanceIdVariableName;
}
public void setCaseInstanceIdVariableName(String caseInstanceIdVariableName) {
this.caseInstanceIdVariableName = caseInstanceIdVariableName;
}
@Override
public CaseServiceTask clone() {
CaseServiceTask clone = new CaseServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(CaseServiceTask otherElement) {
super.setValues(otherElement);
setCaseDefinitionKey(otherElement.getCaseDefinitionKey());
setCaseInstanceName(otherElement.getCaseInstanceName());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
setSameDeployment(otherElement.isSameDeployment());
setFallbackToDefaultTenant(otherElement.isFallbackToDefaultTenant());
setCaseInstanceIdVariableName(otherElement.getCaseInstanceIdVariableName());
inParameters = new ArrayList<>();
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CaseServiceTask.java
| 1
|
请完成以下Java代码
|
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
JavaType javaType = determineJavaType(message, conversionHint);
Object value = message.getPayload();
if (value instanceof Bytes) {
value = ((Bytes) value).get();
}
if (value instanceof String) {
try {
return getObjectMapper().readValue((String) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", message, e);
}
}
else if (value instanceof byte[]) {
try {
return getObjectMapper().readValue((byte[]) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", message, e);
}
}
else {
throw new IllegalStateException("Only String, Bytes, or byte[] supported");
}
}
private JavaType determineJavaType(Message<?> message, @Nullable Object hint) {
JavaType javaType = null;
Type type = null;
if (hint instanceof Type) {
|
type = (Type) hint;
Headers nativeHeaders = message.getHeaders().get(KafkaHeaders.NATIVE_HEADERS, Headers.class);
if (nativeHeaders != null) {
javaType = this.typeMapper.getTypePrecedence()
.equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED)
? TypeFactory.defaultInstance().constructType(type)
: this.typeMapper.toJavaType(nativeHeaders);
}
}
if (javaType == null) { // no headers
if (type != null) {
javaType = TypeFactory.defaultInstance().constructType(type);
}
else {
javaType = OBJECT;
}
}
return javaType;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\MappingJacksonParameterizedConverter.java
| 1
|
请完成以下Java代码
|
public void setIsMembershipContact (final boolean IsMembershipContact)
{
set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact);
}
@Override
public boolean isMembershipContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact);
}
@Override
public void setIsNewsletter (final boolean IsNewsletter)
{
set_Value (COLUMNNAME_IsNewsletter, IsNewsletter);
}
@Override
public boolean isNewsletter()
{
return get_ValueAsBoolean(COLUMNNAME_IsNewsletter);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
|
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setTotalExpend(BigDecimal totalExpend) {
this.totalExpend = totalExpend;
}
public BigDecimal getTodayIncome() {
return todayIncome;
}
public void setTodayIncome(BigDecimal todayIncome) {
this.todayIncome = todayIncome;
}
public BigDecimal getTodayExpend() {
return todayExpend;
}
public void setTodayExpend(BigDecimal todayExpend) {
this.todayExpend = todayExpend;
}
public String getAccountType() {
return accountType;
|
}
public void setAccountType(String accountType) {
this.accountType = accountType == null ? null : accountType.trim();
}
public BigDecimal getSettAmount() {
return settAmount;
}
public void setSettAmount(BigDecimal settAmount) {
this.settAmount = settAmount;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class TaxAccounts
{
@NonNull AcctSchemaId acctSchemaId;
@NonNull Account T_Due_Acct;
@NonNull Account T_Liability_Acct;
@NonNull Account T_Credit_Acct;
@NonNull Account T_Receivables_Acct;
@NonNull Account T_Expense_Acct;
/**
* i.e. C_Tax_Acct.T_Revenue_Acct
*/
@NonNull Optional<Account> T_Revenue_Acct;
@NonNull Optional<Account> T_PayDiscount_Exp_Acct;
@NonNull Optional<Account> T_PayDiscount_Rev_Acct;
@NonNull
public Optional<Account> getAccount(final TaxAcctType acctType)
{
if (TaxAcctType.TaxDue == acctType)
{
return Optional.of(T_Due_Acct);
}
else if (TaxAcctType.TaxLiability == acctType)
{
return Optional.of(T_Liability_Acct);
}
else if (TaxAcctType.TaxCredit == acctType)
{
return Optional.of(T_Credit_Acct);
}
else if (TaxAcctType.TaxReceivables == acctType)
{
return Optional.of(T_Receivables_Acct);
|
}
else if (TaxAcctType.TaxExpense == acctType)
{
return Optional.of(T_Expense_Acct);
}
else if (TaxAcctType.T_Revenue_Acct == acctType)
{
return T_Revenue_Acct;
}
else if (TaxAcctType.T_PayDiscount_Exp_Acct == acctType)
{
return T_PayDiscount_Exp_Acct;
}
else if (TaxAcctType.T_PayDiscount_Rev_Acct == acctType)
{
return T_PayDiscount_Rev_Acct;
}
else
{
throw new AdempiereException("Unknown tax account type: " + acctType);
}
}
public Optional<Account> getPayDiscountAccount(final boolean isExpense)
{
final TaxAcctType acctType = isExpense ? TaxAcctType.T_PayDiscount_Exp_Acct : TaxAcctType.T_PayDiscount_Rev_Acct;
return getAccount(acctType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\TaxAccounts.java
| 2
|
请完成以下Java代码
|
public class ExternalSystemMap
{
private static final ExternalSystemMap EMPTY = new ExternalSystemMap(ImmutableList.of());
private final ImmutableMap<ExternalSystemId, ExternalSystem> byId;
private final ImmutableMap<ExternalSystemType, ExternalSystem> byType;
private ExternalSystemMap(@NonNull final List<ExternalSystem> list)
{
this.byId = Maps.uniqueIndex(list, ExternalSystem::getId);
this.byType = Maps.uniqueIndex(list, ExternalSystem::getType);
}
public static ExternalSystemMap ofList(final List<ExternalSystem> list)
{
return list.isEmpty() ? EMPTY : new ExternalSystemMap(list);
}
public static Collector<ExternalSystem, ?, ExternalSystemMap> collect()
{
return GuavaCollectors.collectUsingListAccumulator(ExternalSystemMap::ofList);
}
@Nullable
public ExternalSystem getByTypeOrNull(@NonNull final ExternalSystemType type)
{
return byType.get(type);
}
public Optional<ExternalSystem> getOptionalByType(@NonNull final ExternalSystemType type)
{
return Optional.ofNullable(getByTypeOrNull(type));
}
|
@NonNull
public ExternalSystem getByType(@NonNull final ExternalSystemType type)
{
return getOptionalByType(type)
.orElseThrow(() -> new AdempiereException("Unknown external system type: " + type));
}
public @NonNull ExternalSystem getById(final @NonNull ExternalSystemId id)
{
final ExternalSystem externalSystem = byId.get(id);
if (externalSystem == null)
{
throw new AdempiereException("No active external system found for id: " + id);
}
return externalSystem;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemMap.java
| 1
|
请完成以下Java代码
|
public B tokenType(OAuth2TokenType tokenType) {
return put(OAuth2TokenType.class, tokenType);
}
/**
* Sets the {@link AuthorizationGrantType authorization grant type}.
* @param authorizationGrantType the {@link AuthorizationGrantType}
* @return the {@link AbstractBuilder} for further configuration
*/
public B authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
return put(AuthorizationGrantType.class, authorizationGrantType);
}
/**
* Sets the {@link Authentication} representing the authorization grant.
* @param authorizationGrant the {@link Authentication} representing the
* authorization grant
* @return the {@link AbstractBuilder} for further configuration
*/
public B authorizationGrant(Authentication authorizationGrant) {
return put(AUTHORIZATION_GRANT_AUTHENTICATION_KEY, authorizationGrant);
}
/**
* Associates an attribute.
* @param key the key for the attribute
* @param value the value of the attribute
* @return the {@link AbstractBuilder} for further configuration
*/
public B put(Object key, Object value) {
Assert.notNull(key, "key cannot be null");
Assert.notNull(value, "value cannot be null");
this.context.put(key, value);
return getThis();
}
/**
* A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
* replace, or remove.
* @param contextConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B context(Consumer<Map<Object, Object>> contextConsumer) {
contextConsumer.accept(this.context);
return getThis();
}
@SuppressWarnings("unchecked")
|
protected <V> V get(Object key) {
return (V) this.context.get(key);
}
protected Map<Object, Object> getContext() {
return this.context;
}
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
/**
* Builds a new {@link OAuth2TokenContext}.
* @return the {@link OAuth2TokenContext}
*/
public abstract T build();
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenContext.java
| 1
|
请完成以下Java代码
|
public class S3Storage extends BaseEntity implements Serializable {
@Id
@Column(name = "storage_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@ApiModelProperty(value = "文件名称")
private String fileName;
@NotBlank
@ApiModelProperty(value = "真实存储的名称")
private String fileRealName;
@NotBlank
@ApiModelProperty(value = "文件大小")
private String fileSize;
@NotBlank
|
@ApiModelProperty(value = "文件MIME 类型")
private String fileMimeType;
@NotBlank
@ApiModelProperty(value = "文件类型")
private String fileType;
@NotBlank
@ApiModelProperty(value = "文件路径")
private String filePath;
public void copy(S3Storage source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\domain\S3Storage.java
| 1
|
请完成以下Java代码
|
public void setRfq_BidEndDate (java.sql.Timestamp Rfq_BidEndDate)
{
set_Value (COLUMNNAME_Rfq_BidEndDate, Rfq_BidEndDate);
}
/** Get Bid end date.
@return Bid end date */
@Override
public java.sql.Timestamp getRfq_BidEndDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Rfq_BidEndDate);
}
/** Set Bid start date.
@param Rfq_BidStartDate Bid start date */
@Override
public void setRfq_BidStartDate (java.sql.Timestamp Rfq_BidStartDate)
{
set_Value (COLUMNNAME_Rfq_BidStartDate, Rfq_BidStartDate);
}
/** Get Bid start date.
@return Bid start date */
@Override
public java.sql.Timestamp getRfq_BidStartDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Rfq_BidStartDate);
}
/**
* RfQType AD_Reference_ID=540661
* Reference name: RfQType
*/
public static final int RFQTYPE_AD_Reference_ID=540661;
/** Default = D */
public static final String RFQTYPE_Default = "D";
/** Procurement = P */
public static final String RFQTYPE_Procurement = "P";
/** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */
@Override
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
|
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ.java
| 1
|
请完成以下Java代码
|
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setMobileUI_UserProfile_Picking_BPartner_ID (final int MobileUI_UserProfile_Picking_BPartner_ID)
{
if (MobileUI_UserProfile_Picking_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID, MobileUI_UserProfile_Picking_BPartner_ID);
}
@Override
public int getMobileUI_UserProfile_Picking_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_BPartner_ID);
}
@Override
public org.compiere.model.I_MobileUI_UserProfile_Picking getMobileUI_UserProfile_Picking()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class);
}
@Override
public void setMobileUI_UserProfile_Picking(final org.compiere.model.I_MobileUI_UserProfile_Picking MobileUI_UserProfile_Picking)
{
set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class, MobileUI_UserProfile_Picking);
}
@Override
public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID)
{
if (MobileUI_UserProfile_Picking_ID < 1)
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null);
else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID);
}
@Override
|
public int getMobileUI_UserProfile_Picking_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID);
}
@Override
public org.compiere.model.I_MobileUI_UserProfile_Picking_Job getMobileUI_UserProfile_Picking_Job()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class);
}
@Override
public void setMobileUI_UserProfile_Picking_Job(final org.compiere.model.I_MobileUI_UserProfile_Picking_Job MobileUI_UserProfile_Picking_Job)
{
set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class, MobileUI_UserProfile_Picking_Job);
}
@Override
public void setMobileUI_UserProfile_Picking_Job_ID (final int MobileUI_UserProfile_Picking_Job_ID)
{
if (MobileUI_UserProfile_Picking_Job_ID < 1)
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, null);
else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, MobileUI_UserProfile_Picking_Job_ID);
}
@Override
public int getMobileUI_UserProfile_Picking_Job_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking_BPartner.java
| 1
|
请完成以下Java代码
|
public static void parsePattern(List<NS> nsList, List<Vertex> vertexList, final WordNet wordNetOptimum, final WordNet wordNetAll)
{
// ListIterator<Vertex> listIterator = vertexList.listIterator();
StringBuilder sbPattern = new StringBuilder(nsList.size());
for (NS ns : nsList)
{
sbPattern.append(ns.toString());
}
String pattern = sbPattern.toString();
final Vertex[] wordArray = vertexList.toArray(new Vertex[0]);
trie.parseText(pattern, new AhoCorasickDoubleArrayTrie.IHit<String>()
{
@Override
public void hit(int begin, int end, String value)
{
StringBuilder sbName = new StringBuilder();
for (int i = begin; i < end; ++i)
{
sbName.append(wordArray[i].realWord);
}
String name = sbName.toString();
// 对一些bad case做出调整
if (isBadCase(name)) return;
// 正式算它是一个名字
if (HanLP.Config.DEBUG)
{
System.out.printf("识别出地名:%s %s\n", name, value);
}
|
int offset = 0;
for (int i = 0; i < begin; ++i)
{
offset += wordArray[i].realWord.length();
}
wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PLACE, name, ATTRIBUTE, WORD_ID), wordNetAll);
}
});
}
/**
* 因为任何算法都无法解决100%的问题,总是有一些bad case,这些bad case会以“盖公章 A 1”的形式加入词典中<BR>
* 这个方法返回是否是bad case
*
* @param name
* @return
*/
static boolean isBadCase(String name)
{
EnumItem<NS> nrEnumItem = dictionary.get(name);
if (nrEnumItem == null) return false;
return nrEnumItem.containsLabel(NS.Z);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ns\PlaceDictionary.java
| 1
|
请完成以下Java代码
|
public boolean isID()
{
// ID columns are considered numbers - teo_sarca [ 1673363 ]
if (DisplayType.ID == m_displayType)
return false;
return DisplayType.isID(m_displayType);
} // isID
/**
* Is Value boolean
* @return true if value is a boolean
*/
public boolean isYesNo()
{
if (m_displayType == 0)
return m_value instanceof Boolean;
return DisplayType.YesNo == m_displayType;
} // isYesNo
/**
* Is Value the primary key of row
* @return true if value is the PK
*/
public boolean isPKey()
{
return m_isPKey;
} // isPKey
/**
* Column value forces page break
* @return true if page break
*/
public boolean isPageBreak()
{
return m_isPageBreak;
} // isPageBreak
/*************************************************************************/
/**
* HashCode
* @return hash code
*/
public int hashCode()
{
if (m_value == null)
return m_columnName.hashCode();
return m_columnName.hashCode() + m_value.hashCode();
} // hashCode
/**
* Equals
* @param compare compare object
* @return true if equals
*/
public boolean equals (Object compare)
{
if (compare instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)compare;
if (pde.getColumnName().equals(m_columnName))
{
if (pde.getValue() != null && pde.getValue().equals(m_value))
return true;
|
if (pde.getValue() == null && m_value == null)
return true;
}
}
return false;
} // equals
/**
* String representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value);
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
} // toString
/**
* Value Has Key
* @return true if value has a key
*/
public boolean hasKey()
{
return m_value instanceof NamePair;
} // hasKey
/**
* String representation with key info
* @return info
*/
public String toStringX()
{
if (m_value instanceof NamePair)
{
NamePair pp = (NamePair)m_value;
StringBuffer sb = new StringBuffer(m_columnName);
sb.append("(").append(pp.getID()).append(")")
.append("=").append(pp.getName());
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
}
else
return toString();
} // toStringX
public String getM_formatPattern() {
return m_formatPattern;
}
public void setM_formatPattern(String pattern) {
m_formatPattern = pattern;
}
} // PrintDataElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "2")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "http://localhost:8081/cmmn-repository/deployments/2")
public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "Examples")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setResource(String resource) {
this.resource = resource;
|
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testCase.cmmn", value = "Contains the actual deployed CMMN 1.1 xml.")
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a case for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.")
public String getDiagramResource() {
return diagramResource;
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
}
@ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).")
public boolean isGraphicalNotationDefined() {
return graphicalNotationDefined;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MailServiceInstance {
private String instanceId;
private String serviceDefinitionId;
private String planId;
private String dashboardUrl;
public MailServiceInstance(String instanceId, String serviceDefinitionId, String planId, String dashboardUrl) {
this.instanceId = instanceId;
this.serviceDefinitionId = serviceDefinitionId;
this.planId = planId;
this.dashboardUrl = dashboardUrl;
}
public String getInstanceId() {
|
return instanceId;
}
public String getServiceDefinitionId() {
return serviceDefinitionId;
}
public String getPlanId() {
return planId;
}
public String getDashboardUrl() {
return dashboardUrl;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-open-service-broker\src\main\java\com\baeldung\spring\cloud\openservicebroker\mail\MailServiceInstance.java
| 2
|
请完成以下Java代码
|
public Set<String> getDocTableNames()
{
return docProviders.getDocTableNames();
}
public boolean isAccountingTable(final String docTableName)
{
return docProviders.isAccountingTable(docTableName);
}
//
//
//
// ------------------------------------------------------------------------
//
//
//
@ToString
private static class AggregatedAcctDocProvider implements IAcctDocProvider
{
private final ImmutableMap<String, IAcctDocProvider> providersByDocTableName;
private AggregatedAcctDocProvider(final List<IAcctDocProvider> providers)
{
final ImmutableMap.Builder<String, IAcctDocProvider> mapBuilder = ImmutableMap.builder();
for (final IAcctDocProvider provider : providers)
{
for (final String docTableName : provider.getDocTableNames())
{
mapBuilder.put(docTableName, provider);
}
}
this.providersByDocTableName = mapBuilder.build();
}
public boolean isAccountingTable(final String docTableName)
{
return getDocTableNames().contains(docTableName);
}
@Override
public Set<String> getDocTableNames()
|
{
return providersByDocTableName.keySet();
}
@Override
public Doc<?> getOrNull(
@NonNull final AcctDocRequiredServicesFacade services,
@NonNull final List<AcctSchema> acctSchemas,
@NonNull final TableRecordReference documentRef)
{
try
{
final String docTableName = documentRef.getTableName();
final IAcctDocProvider provider = providersByDocTableName.get(docTableName);
if (provider == null)
{
return null;
}
return provider.getOrNull(services, acctSchemas, documentRef);
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw PostingExecutionException.wrapIfNeeded(ex);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\AcctDocRegistry.java
| 1
|
请完成以下Java代码
|
private TbMsgMetaData getActionMetaData(RuleNodeId ruleNodeId) {
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("ruleNodeId", ruleNodeId.toString());
return metaData;
}
@Override
public void schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
mainCtx.getScheduler().schedule(runnable, delay, timeUnit);
}
@Override
public void checkTenantEntity(EntityId entityId) throws TbNodeException {
TenantId actualTenantId = TenantIdLoader.findTenantId(this, entityId);
if (!getTenantId().equals(actualTenantId)) {
throw new TbNodeException("Entity with id: '" + entityId + "' specified in the configuration doesn't belong to the current tenant.", true);
}
}
@Override
public <E extends HasId<I> & HasTenantId, I extends EntityId> void checkTenantOrSystemEntity(E entity) throws TbNodeException {
TenantId actualTenantId = entity.getTenantId();
if (!getTenantId().equals(actualTenantId) && !actualTenantId.isSysTenantId()) {
throw new TbNodeException("Entity with id: '" + entity.getId() + "' specified in the configuration doesn't belong to the current or system tenant.", true);
}
}
private static String getFailureMessage(Throwable th) {
String failureMessage;
if (th != null) {
if (!StringUtils.isEmpty(th.getMessage())) {
failureMessage = th.getMessage();
} else {
failureMessage = th.getClass().getSimpleName();
}
} else {
failureMessage = null;
}
return failureMessage;
}
|
private void persistDebugOutput(TbMsg msg, String relationType) {
persistDebugOutput(msg, Set.of(relationType));
}
private void persistDebugOutput(TbMsg msg, Set<String> relationTypes) {
persistDebugOutput(msg, relationTypes, null, null);
}
private void persistDebugOutput(TbMsg msg, Set<String> relationTypes, Throwable error, String failureMessage) {
RuleNode ruleNode = nodeCtx.getSelf();
if (DebugModeUtil.isDebugAllAvailable(ruleNode)) {
relationTypes.forEach(relationType -> mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, relationType, error, failureMessage));
} else if (DebugModeUtil.isDebugFailuresAvailable(ruleNode, relationTypes)) {
mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, TbNodeConnectionType.FAILURE, error, failureMessage);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\DefaultTbContext.java
| 1
|
请完成以下Java代码
|
public String toString() {
return this.namespace.getValue() + ":" + this.value;
}
/**
* Creates an {@link AdditionalHealthEndpointPath} from the given input. The input
* must contain a prefix and value separated by a `:`. The value must be limited to
* one path segment. For example, `server:/healthz`.
* @param value the value to parse
* @return the new instance
*/
public static AdditionalHealthEndpointPath from(String value) {
Assert.hasText(value, "'value' must not be null");
String[] values = value.split(":");
Assert.isTrue(values.length == 2, "'value' must contain a valid namespace and value separated by ':'.");
Assert.isTrue(StringUtils.hasText(values[0]), "'value' must contain a valid namespace.");
WebServerNamespace namespace = WebServerNamespace.from(values[0]);
validateValue(values[1]);
return new AdditionalHealthEndpointPath(namespace, values[1]);
}
/**
|
* Creates an {@link AdditionalHealthEndpointPath} from the given
* {@link WebServerNamespace} and value.
* @param webServerNamespace the server namespace
* @param value the value
* @return the new instance
*/
public static AdditionalHealthEndpointPath of(WebServerNamespace webServerNamespace, String value) {
Assert.notNull(webServerNamespace, "'webServerNamespace' must not be null.");
Assert.notNull(value, "'value' must not be null.");
validateValue(value);
return new AdditionalHealthEndpointPath(webServerNamespace, value);
}
private static void validateValue(String value) {
Assert.isTrue(StringUtils.countOccurrencesOf(value, "/") <= 1 && value.indexOf("/") <= 0,
"'value' must contain only one segment.");
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\AdditionalHealthEndpointPath.java
| 1
|
请完成以下Java代码
|
public String getMessage() {
return message;
}
public Builder setMessage(String message) {
if(message == null){
throw new NullPointerException("message");
}
this.message = message;
return this;
}
public boolean isRetain() {
return retain;
}
public Builder setRetain(boolean retain) {
this.retain = retain;
return this;
}
public MqttQoS getQos() {
return qos;
}
public Builder setQos(MqttQoS qos) {
if(qos == null){
throw new NullPointerException("qos");
}
this.qos = qos;
return this;
}
public MqttLastWill build(){
return new MqttLastWill(topic, message, retain, qos);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MqttLastWill that = (MqttLastWill) o;
if (retain != that.retain) return false;
|
if (!topic.equals(that.topic)) return false;
if (!message.equals(that.message)) return false;
return qos == that.qos;
}
@Override
public int hashCode() {
int result = topic.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (retain ? 1 : 0);
result = 31 * result + qos.hashCode();
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MqttLastWill{");
sb.append("topic='").append(topic).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append(", retain=").append(retain);
sb.append(", qos=").append(qos.name());
sb.append('}');
return sb.toString();
}
}
|
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttLastWill.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void restore(QueueKey queueKey, Set<TopicPartitionInfo> partitions) {
stateService.update(queueKey, partitions, new QueueStateService.RestoreCallback() {
@Override
public void onAllPartitionsRestored() {
}
@Override
public void onPartitionRestored(TopicPartitionInfo partition) {
partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME);
actorSystemContext.tellWithHighPriority(new CalculatedFieldStatePartitionRestoreMsg(partition));
}
});
}
@Override
|
public void delete(Set<TopicPartitionInfo> partitions) {
stateService.delete(partitions);
}
@Override
public Set<TopicPartitionInfo> getPartitions() {
return stateService.getPartitions().values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
}
@Override
public void stop() {
stateService.stop();
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\AbstractCalculatedFieldStateService.java
| 2
|
请完成以下Java代码
|
public String getClientSoftwareKennung() {
return clientSoftwareKennung;
}
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
/**
* Gets the value of the lieferavisBestaetigenType property.
*
* @return
* possible object is
* {@link LieferavisBestaetigenType }
*
*/
public LieferavisBestaetigenType getLieferavisBestaetigenType() {
|
return lieferavisBestaetigenType;
}
/**
* Sets the value of the lieferavisBestaetigenType property.
*
* @param value
* allowed object is
* {@link LieferavisBestaetigenType }
*
*/
public void setLieferavisBestaetigenType(LieferavisBestaetigenType value) {
this.lieferavisBestaetigenType = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisBestaetigen.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setVersion(int version) {
this.version = version;
}
@ApiModelProperty(example = "SimpleSourceName")
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@ApiModelProperty(example = "818e4703-f1d2-11e6-8549-acde48001121")
public String getDeploymentId() {
return deploymentId;
|
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDefinitionResponse.java
| 2
|
请完成以下Java代码
|
public static String getApplicationPathByCaseDefinitionId(ProcessEngine engine, String caseDefinitionId) {
CaseDefinition caseDefinition = engine.getRepositoryService().getCaseDefinition(caseDefinitionId);
if (caseDefinition == null) {
return null;
}
return getApplicationPathForDeployment(engine, caseDefinition.getDeploymentId());
}
public static String getApplicationPathForDeployment(ProcessEngine engine, String deploymentId) {
// get the name of the process application that made the deployment
String processApplicationName = null;
IdentityService identityService = engine.getIdentityService();
Authentication currentAuthentication = identityService.getCurrentAuthentication();
|
try {
identityService.clearAuthentication();
processApplicationName = engine.getManagementService().getProcessApplicationForDeployment(deploymentId);
} finally {
identityService.setAuthentication(currentAuthentication);
}
if (processApplicationName == null) {
// no a process application deployment
return null;
} else {
ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService();
ProcessApplicationInfo processApplicationInfo = processApplicationService.getProcessApplicationInfo(processApplicationName);
return processApplicationInfo.getProperties().get(ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\util\ApplicationContextPathUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop111V other = (Cctop111V)obj;
if (cOrderID == null)
{
if (other.cOrderID != null)
{
return false;
}
}
else if (!cOrderID.equals(other.cOrderID))
{
return false;
}
if (dateOrdered == null)
{
if (other.dateOrdered != null)
{
return false;
}
}
else if (!dateOrdered.equals(other.dateOrdered))
{
return false;
}
if (mInOutID == null)
{
if (other.mInOutID != null)
{
return false;
}
}
else if (!mInOutID.equals(other.mInOutID))
{
return false;
|
}
if (movementDate == null)
{
if (other.movementDate != null)
{
return false;
}
}
else if (!movementDate.equals(other.movementDate))
{
return false;
}
if (poReference == null)
{
if (other.poReference != null)
{
return false;
}
}
else if (!poReference.equals(other.poReference))
{
return false;
}
if (shipmentDocumentno == null)
{
if (other.shipmentDocumentno != null)
{
return false;
}
}
else if (!shipmentDocumentno.equals(other.shipmentDocumentno))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop111V [cOrderID=" + cOrderID + ", mInOutID=" + mInOutID + ", dateOrdered=" + dateOrdered + ", movementDate=" + movementDate + ", poReference="
+ poReference
+ ", shipmentDocumentno=" + shipmentDocumentno + "]";
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop111V.java
| 2
|
请完成以下Java代码
|
public frameset removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
/**
The onload event occurs when the user agent finishes loading a window
or all frames within a frameset. This attribute may be used with body
and frameset elements.
@param The script
*/
public void setOnLoad(String script)
{
addAttribute ( "onload", script );
|
}
/**
The onunload event occurs when the user agent removes a document from a
window or frame. This attribute may be used with body and frameset
elements.
@param The script
*/
public void setOnUnload(String script)
{
addAttribute ( "onunload", script );
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java
| 1
|
请完成以下Java代码
|
public void setRegistryPort(Integer registryPort) {
this.registryPort = registryPort;
}
public String getServiceUrlPath() {
return serviceUrlPath;
}
public void setServiceUrlPath(String serviceUrlPath) {
this.serviceUrlPath = serviceUrlPath;
}
public Integer getConnectorPort() {
return connectorPort;
}
public void setConnectorPort(Integer connectorPort) {
this.connectorPort = connectorPort;
}
@Override
|
public void beforeInit(AbstractEngineConfiguration engineConfiguration) {
// nothing to do
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
try {
this.processEngineConfig = (ProcessEngineConfiguration) engineConfiguration;
if (!disabled) {
managementAgent = new DefaultManagementAgent(this);
managementAgent.doStart();
managementAgent.findAndRegisterMbeans();
}
} catch (Exception e) {
LOGGER.warn("error in initializing jmx. Continue with partial or no JMX configuration", e);
}
}
}
|
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\JMXConfigurator.java
| 1
|
请完成以下Java代码
|
public class UserDO {
/**
* ID 主键
*/
@Id
private Integer id;
/**
* 账号
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 创建时间
*/
private Date createTime;
public Integer getId() {
return id;
}
public UserDO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
|
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
@Override
public String toString() {
return "UserDO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-elasticsearch\src\main\java\cn\iocoder\springboot\lab27\springwebflux\dataobject\UserDO.java
| 1
|
请完成以下Java代码
|
public class HeaderParser {
/**
* Parse a given OSGi header into a list of paths
*
* @param header the OSGi header to parse
* @return the list of paths extracted from this header
*/
public static List<PathElement> parseHeader(String header) {
List<PathElement> elements = new ArrayList<>();
if (header == null || header.trim().length() == 0) {
return elements;
}
String[] clauses = header.split(",");
for (String clause : clauses) {
String[] tokens = clause.split(";");
if (tokens.length < 1) {
throw new IllegalArgumentException("Invalid header clause: " + clause);
}
PathElement elem = new PathElement(tokens[0].trim());
elements.add(elem);
for (int i = 1; i < tokens.length; i++) {
int pos = tokens[i].indexOf('=');
if (pos != -1) {
if (pos > 0 && tokens[i].charAt(pos - 1) == ':') {
String name = tokens[i].substring(0, pos - 1).trim();
String value = tokens[i].substring(pos + 1).trim();
elem.addDirective(name, value);
} else {
String name = tokens[i].substring(0, pos).trim();
String value = tokens[i].substring(pos + 1).trim();
elem.addAttribute(name, value);
}
} else {
elem = new PathElement(tokens[i].trim());
elements.add(elem);
}
}
}
return elements;
}
public static class PathElement {
private String path;
private Map<String, String> attributes;
private Map<String, String> directives;
public PathElement(String path) {
this.path = path;
this.attributes = new HashMap<>();
|
this.directives = new HashMap<>();
}
public String getName() {
return this.path;
}
public Map<String, String> getAttributes() {
return attributes;
}
public String getAttribute(String name) {
return attributes.get(name);
}
public void addAttribute(String name, String value) {
attributes.put(name, value);
}
public Map<String, String> getDirectives() {
return directives;
}
public String getDirective(String name) {
return directives.get(name);
}
public void addDirective(String name, String value) {
directives.put(name, value);
}
}
}
|
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\HeaderParser.java
| 1
|
请完成以下Java代码
|
public int getM_ForecastLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ForecastLine_ID);
}
@Override
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setPlannedQty (java.math.BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty);
}
@Override
public java.math.BigDecimal getPlannedQty()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Demand_Detail.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String dataimport(){
// 1、清空索引,生产环境不建议这样使用,可以保存文件新建及更新时间,增量创建索引
try {
solrService.deleteAll(file_core);
} catch (Exception e) {
e.printStackTrace();
}
// 2、创建索引
Mono<String> result = WebClient.create(solrHost)
.get()
.uri(fileDataImport)
.retrieve()
.bodyToMono(String.class);
System.out.println(result.block());
return "success";
}
/**
* 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息
|
* @return
*/
@RequestMapping("doc/search/{q}")
public SolrDocumentList docSearch(@PathVariable String q){
SolrDocumentList results = null;
try {
results = solrService.querySolr(file_core,q,"keyword");
} catch (IOException e) {
e.printStackTrace();
} catch (SolrServerException e) {
e.printStackTrace();
}
return results;
}
}
|
repos\springboot-demo-master\solr\src\main\java\demo\et59\solr\controller\SolrController.java
| 2
|
请完成以下Java代码
|
public void setNamespacePrefix(String namespacePrefix) {
this.namespacePrefix = namespacePrefix;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public Map<String, List<DmnExtensionElement>> getChildElements() {
return childElements;
}
public void addChildElement(DmnExtensionElement childElement) {
if (childElement != null && childElement.getName() != null && !childElement.getName().trim().isEmpty()) {
List<DmnExtensionElement> elementList = null;
if (!this.childElements.containsKey(childElement.getName())) {
elementList = new ArrayList<>();
this.childElements.put(childElement.getName(), elementList);
}
this.childElements.get(childElement.getName()).add(childElement);
}
}
public void setChildElements(Map<String, List<DmnExtensionElement>> childElements) {
this.childElements = childElements;
}
|
@Override
public DmnExtensionElement clone() {
DmnExtensionElement clone = new DmnExtensionElement();
clone.setValues(this);
return clone;
}
public void setValues(DmnExtensionElement otherElement) {
setName(otherElement.getName());
setNamespacePrefix(otherElement.getNamespacePrefix());
setNamespace(otherElement.getNamespace());
setElementText(otherElement.getElementText());
setAttributes(otherElement.getAttributes());
childElements = new LinkedHashMap<>();
if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) {
for (String key : otherElement.getChildElements().keySet()) {
List<DmnExtensionElement> otherElementList = otherElement.getChildElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<DmnExtensionElement> elementList = new ArrayList<>();
for (DmnExtensionElement dmnExtensionElement : otherElementList) {
elementList.add(dmnExtensionElement.clone());
}
childElements.put(key, elementList);
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionElement.java
| 1
|
请完成以下Java代码
|
public TransportPayloadType getTransportPayloadType() {
return TransportPayloadType.PROTOBUF;
}
public Descriptors.Descriptor getTelemetryDynamicMessageDescriptor(String deviceTelemetryProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceTelemetryProtoSchema, TELEMETRY_PROTO_SCHEMA);
}
public Descriptors.Descriptor getAttributesDynamicMessageDescriptor(String deviceAttributesProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceAttributesProtoSchema, ATTRIBUTES_PROTO_SCHEMA);
}
public Descriptors.Descriptor getRpcResponseDynamicMessageDescriptor(String deviceRpcResponseProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceRpcResponseProtoSchema, RPC_RESPONSE_PROTO_SCHEMA);
}
public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder(String deviceRpcRequestProtoSchema) {
return DynamicProtoUtils.getDynamicMessageBuilder(deviceRpcRequestProtoSchema, RPC_REQUEST_PROTO_SCHEMA);
}
public String getDeviceRpcResponseProtoSchema() {
if (StringUtils.isNotEmpty(deviceRpcResponseProtoSchema)) {
return deviceRpcResponseProtoSchema;
} else {
return "syntax =\"proto3\";\n" +
"package rpc;\n" +
"\n" +
|
"message RpcResponseMsg {\n" +
" optional string payload = 1;\n" +
"}";
}
}
public String getDeviceRpcRequestProtoSchema() {
if (StringUtils.isNotEmpty(deviceRpcRequestProtoSchema)) {
return deviceRpcRequestProtoSchema;
} else {
return "syntax =\"proto3\";\n" +
"package rpc;\n" +
"\n" +
"message RpcRequestMsg {\n" +
" optional string method = 1;\n" +
" optional int32 requestId = 2;\n" +
" optional string params = 3;\n" +
"}";
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\profile\ProtoTransportPayloadConfiguration.java
| 1
|
请完成以下Java代码
|
public void setESR_Control_Amount (final @Nullable BigDecimal ESR_Control_Amount)
{
set_Value (COLUMNNAME_ESR_Control_Amount, ESR_Control_Amount);
}
@Override
public BigDecimal getESR_Control_Amount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Amount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Control_Trx_Qty (final @Nullable BigDecimal ESR_Control_Trx_Qty)
{
set_Value (COLUMNNAME_ESR_Control_Trx_Qty, ESR_Control_Trx_Qty);
}
@Override
public BigDecimal getESR_Control_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
@Override
public void setESR_Trx_Qty (final @Nullable BigDecimal ESR_Trx_Qty)
{
throw new IllegalArgumentException ("ESR_Trx_Qty is virtual column"); }
@Override
public BigDecimal getESR_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setHash (final @Nullable java.lang.String Hash)
{
set_Value (COLUMNNAME_Hash, Hash);
}
@Override
public java.lang.String getHash()
{
return get_ValueAsString(COLUMNNAME_Hash);
}
@Override
public void setIsArchiveFile (final boolean IsArchiveFile)
{
set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile);
}
@Override
public boolean isArchiveFile()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile);
}
|
@Override
public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
@Override
public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
| 1
|
请完成以下Java代码
|
public class InsertFieldIntoFilter {
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
private static String collectionName;
private static String databaseName;
public static void setUp() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
databaseName = "baeldung";
collectionName = "pet";
database = mongoClient.getDatabase(databaseName);
collection = database.getCollection(collectionName);
}
}
public static void addFieldToExistingBsonFilter() {
Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
Bson newFilter = and(existingFilter, gt("age", 5));
FindIterable<Document> documents = collection.find(newFilter);
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void addFieldToExistingBsonFilterUsingBsonDocument() {
Bson existingFilter = eq("type", "Dog");
BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
|
Bson newFilter = gt("age", 5);
BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
existingBsonDocument.append("age", newBsonDocument.get("age"));
FindIterable<Document> documents = collection.find(existingBsonDocument);
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void main(String args[]) {
setUp();
addFieldToExistingBsonFilter();
addFieldToExistingBsonFilterUsingBsonDocument();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\insert\InsertFieldIntoFilter.java
| 1
|
请完成以下Java代码
|
public void appendStructure(StringBuilder builder, Bindings bindings) {
lambdaNode.appendStructure(builder, bindings);
params.appendStructure(builder, bindings);
}
@Override
public Object eval(Bindings bindings, ELContext context) {
// Evaluate the lambda expression
Object lambdaObj = lambdaNode.eval(bindings, context);
if (!(lambdaObj instanceof LambdaExpression)) {
throw new ELException("Expected LambdaExpression but got: " +
(lambdaObj == null ? "null" : lambdaObj.getClass().getName()));
}
LambdaExpression lambda = (LambdaExpression) lambdaObj;
// Evaluate the arguments
Object[] args = params.eval(bindings, context);
// Invoke the lambda
Object result = lambda.invoke(context, args);
return result;
}
|
@Override
public int getCardinality() {
return 2;
}
@Override
public AstNode getChild(int i) {
return i == 0 ? lambdaNode : i == 1 ? params : null;
}
@Override
public String toString() {
return lambdaNode.toString() + params.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaInvocation.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8080
spring.application.name=spring-boot-rabbitmq
rabbitmq.host=60.205.191.82
rabbitmq.port=5673
rabbitmq.username=guest
rabbitmq.passwo
|
rd=guest
rabbitmq.publisher-confirms=true
rabbitmq.virtual-host=/
|
repos\spring-boot-quick-master\quick-rabbitmq\src\main\resources\application.properties
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 8085
spring:
pulsar:
client:
service-url: pulsar://localhost:6650
defaults:
type-mappings:
- message-type: com.baeldun
|
g.springpulsar.User
schema-info:
schema-type: JSON
|
repos\tutorials-master\spring-pulsar\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext2) {
String resultAsJsonString = prepareResultAsJsonString(exceptionMessage, e);
batchService.completeBatchPart(batchPartId, CaseInstanceBatchMigrationResult.RESULT_FAIL, resultAsJsonString);
return null;
}
});
}
});
FlowableBatchPartMigrationException wrappedException = new FlowableBatchPartMigrationException(e.getMessage(), e);
wrappedException.setIgnoreFailedJob(true);
throw wrappedException;
}
String resultAsJsonString = prepareResultAsJsonString();
batchService.completeBatchPart(batchPartId, CaseInstanceBatchMigrationResult.RESULT_SUCCESS, resultAsJsonString);
}
protected String prepareResultAsJsonString(String exceptionMessage, Exception e) {
ObjectNode objectNode = getObjectMapper().createObjectNode();
objectNode.put(BATCH_RESULT_STATUS_LABEL, CaseInstanceBatchMigrationResult.RESULT_FAIL);
objectNode.put(BATCH_RESULT_MESSAGE_LABEL, exceptionMessage);
objectNode.put(BATCH_RESULT_STACKTRACE_LABEL, getExceptionStacktrace(e));
|
return objectNode.toString();
}
protected String prepareResultAsJsonString() {
ObjectNode objectNode = getObjectMapper().createObjectNode();
objectNode.put(BATCH_RESULT_STATUS_LABEL, CaseInstanceBatchMigrationResult.RESULT_SUCCESS);
return objectNode.toString();
}
protected String getExceptionStacktrace(Throwable exception) {
StringWriter stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\HistoricCaseInstanceMigrationJobHandler.java
| 1
|
请完成以下Java代码
|
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_AUDITER() {
return F_AUDITER;
}
public void setF_AUDITER(String f_AUDITER) {
F_AUDITER = f_AUDITER;
}
public String getF_AUDITTIME() {
return F_AUDITTIME;
}
public void setF_AUDITTIME(String f_AUDITTIME) {
F_AUDITTIME = f_AUDITTIME;
}
public String getF_ISAUDIT() {
return F_ISAUDIT;
}
public void setF_ISAUDIT(String f_ISAUDIT) {
F_ISAUDIT = f_ISAUDIT;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
|
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public Integer getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISPRINTBILL() {
return F_ISPRINTBILL;
}
public void setF_ISPRINTBILL(String f_ISPRINTBILL) {
F_ISPRINTBILL = f_ISPRINTBILL;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
| 1
|
请完成以下Java代码
|
public IQueryBuilder<I_C_AggregationItem> retrieveAllItemsQuery(final I_C_Aggregation aggregation)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_C_AggregationItem> queryBuilder = queryBL
.createQueryBuilder(I_C_AggregationItem.class, aggregation)
.addEqualsFilter(I_C_AggregationItem.COLUMN_C_Aggregation_ID, aggregation.getC_Aggregation_ID())
// .addOnlyActiveRecordsFilter() // NOTE: we are retrieving all
;
// we want to have a predictable order
queryBuilder.orderBy()
.addColumn(I_C_AggregationItem.COLUMN_C_AggregationItem_ID);
return queryBuilder;
}
List<I_C_AggregationItem> retrieveAllItems(final I_C_Aggregation aggregation)
{
return retrieveAllItemsQuery(aggregation)
.create()
.list();
}
@Override
@Cached(cacheName = I_C_Aggregation.Table_Name + "#IAggregation", expireMinutes = 0)
public Aggregation retrieveAggregation(@CacheCtx final Properties ctx, @NonNull final AggregationId aggregationId)
{
//
// Load aggregation definition
final I_C_Aggregation aggregationDef = InterfaceWrapperHelper.create(ctx, AggregationId.toRepoId(aggregationId), I_C_Aggregation.class, ITrx.TRXNAME_None);
if (aggregationDef == null)
{
throw new AdempiereException("@NotFound@ @C_Aggregation_ID@ (ID=" + aggregationId + ")");
}
return new C_Aggregation2AggregationBuilder(this)
.setC_Aggregation(aggregationDef)
.build();
}
@Override
public void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef)
{
|
final Map<Integer, I_C_Aggregation> trace = new LinkedHashMap<>();
checkIncludedAggregationCycles(aggregationItemDef, trace);
}
private final void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef, final Map<Integer, I_C_Aggregation> trace)
{
Check.assumeNotNull(aggregationItemDef, "aggregationItemDef not null");
final String itemType = aggregationItemDef.getType();
if (!X_C_AggregationItem.TYPE_IncludedAggregation.equals(itemType))
{
return;
}
final int includedAggregationId = aggregationItemDef.getIncluded_Aggregation_ID();
if (includedAggregationId <= 0)
{
return;
}
if (trace.containsKey(includedAggregationId))
{
throw new AdempiereException("Cycle detected: " + trace.values());
}
final I_C_Aggregation includedAggregationDef = aggregationItemDef.getC_Aggregation();
trace.put(includedAggregationId, includedAggregationDef);
final List<I_C_AggregationItem> includedAggregationItemsDef = retrieveAllItems(includedAggregationDef);
for (final I_C_AggregationItem includedAggregationItemDef : includedAggregationItemsDef)
{
checkIncludedAggregationCycles(includedAggregationItemDef, trace);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\AggregationDAO.java
| 1
|
请完成以下Java代码
|
public PIAttributes retrievePIAttributes(@NonNull final HuPackingInstructionsVersionId piVersionId)
{
//
// Retrieve and add Direct Attributes
// NOTE: we want to make use of caching, that's why we are retrieving out of transaction.
// Anyway, this is master data and this method is not supposed to be used when you want to retrieve master data for modifying it.
PIAttributes piAttributes = retrieveDirectPIAttributes(Env.getCtx(), piVersionId);
//
// Retrieve an add template attributes (from NoPI)
// only if given version is not of NoPI
if (!piVersionId.isTemplate())
{
final PIAttributes templatePIAttributes = retrieveDirectPIAttributes(Env.getCtx(), HuPackingInstructionsVersionId.TEMPLATE);
piAttributes = piAttributes.addIfAbsent(templatePIAttributes);
}
return piAttributes;
}
@Override
public PIAttributes retrievePIAttributesByIds(@NonNull final Set<Integer> piAttributeIds)
{
if (piAttributeIds.isEmpty())
{
return PIAttributes.EMPTY;
}
List<I_M_HU_PI_Attribute> piAttributesList = loadByIdsOutOfTrx(piAttributeIds, I_M_HU_PI_Attribute.class);
return PIAttributes.of(piAttributesList);
}
@Override
public boolean isTemplateAttribute(final I_M_HU_PI_Attribute huPIAttribute)
{
logger.trace("Checking if {} is a template attribute", huPIAttribute);
//
// If the PI attribute is from template then it's a template attribute
final HuPackingInstructionsVersionId piVersionId = HuPackingInstructionsVersionId.ofRepoId(huPIAttribute.getM_HU_PI_Version_ID());
if (piVersionId.isTemplate())
{
if (!huPIAttribute.isActive())
{
|
logger.trace("Considering {} NOT a template attribute because even if it is direct template attribute it's INACTIVE", huPIAttribute);
return false;
}
else
{
logger.trace("Considering {} a template attribute because it is direct template attribute", huPIAttribute);
return true;
}
}
//
// Get the Template PI attributes and search if this attribute is defined there.
final AttributeId attributeId = AttributeId.ofRepoId(huPIAttribute.getM_Attribute_ID());
final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute);
final PIAttributes templatePIAttributes = retrieveDirectPIAttributes(ctx, HuPackingInstructionsVersionId.TEMPLATE);
if (templatePIAttributes.hasActiveAttribute(attributeId))
{
logger.trace("Considering {} a template attribute because we found M_Attribute_ID={} in template attributes", huPIAttribute, attributeId);
return true;
}
//
// Not a template attribute
logger.trace("Considering {} NOT a template attribute", huPIAttribute);
return false;
}
@Override
public void deleteByVersionId(@NonNull final HuPackingInstructionsVersionId versionId)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_PI_Attribute.class)
.addEqualsFilter(I_M_HU_PI_Attribute.COLUMN_M_HU_PI_Version_ID, versionId)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUPIAttributesDAO.java
| 1
|
请完成以下Java代码
|
protected OpenOption[] getOpenOptions() {
return ArrayUtils.asArray(
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE
);
}
/**
* Returns an {@link Optional} reference to the target {@link Resource}.
*
* @return an {@link Optional} reference to the target {@link Resource}.
* @see org.springframework.core.io.Resource
* @see java.util.Optional
*/
protected Optional<Resource> getResource() {
return Optional.ofNullable(this.resource.get());
}
/**
* Decorates the given {@link OutputStream} by adding buffering capabilities.
*
* @param outputStream {@link OutputStream} to decorate.
* @return the decorated {@link OutputStream}.
* @see #newFileOutputStream()
* @see java.io.OutputStream
*/
protected @NonNull OutputStream decorate(@Nullable OutputStream outputStream) {
return outputStream instanceof BufferedOutputStream ? outputStream
: outputStream != null ? new BufferedOutputStream(outputStream, getBufferSize())
: newFileOutputStream();
}
/**
* Tries to construct a new {@link File} based {@link OutputStream} from the {@literal target} {@link Resource}.
|
*
* By default, the constructed {@link OutputStream} is also buffered (e.g. {@link BufferedOutputStream}).
*
* @return a {@link OutputStream} writing to a {@link File} identified by the {@literal target} {@link Resource}.
* @throws IllegalStateException if the {@literal target} {@link Resource} cannot be handled as a {@link File}.
* @throws DataAccessResourceFailureException if the {@link OutputStream} could not be created.
* @see java.io.BufferedOutputStream
* @see java.io.OutputStream
* @see #getBufferSize()
* @see #getOpenOptions()
* @see #getResource()
*/
protected OutputStream newFileOutputStream() {
return getResource()
.filter(this::isAbleToHandle)
.map(resource -> {
try {
OutputStream fileOutputStream =
Files.newOutputStream(resource.getFile().toPath(), getOpenOptions());
return new BufferedOutputStream(fileOutputStream, getBufferSize());
}
catch (IOException cause) {
String message = String.format("Failed to access the Resource [%s] as a file",
resource.getDescription());
throw new ResourceDataAccessException(message, cause);
}
})
.orElseThrow(() -> newIllegalStateException("Resource [%s] is not a file based resource",
getResource().map(Resource::getDescription).orElse(null)));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\FileResourceWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Options without(Option option) {
return copy((options) -> options.remove(option));
}
/**
* Create a new {@link Options} instance that contains the options in this set
* including the given option.
* @param option the option to include
* @return a new {@link Options} instance
*/
public Options with(Option option) {
return copy((options) -> options.add(option));
}
private Options copy(Consumer<EnumSet<Option>> processor) {
EnumSet<Option> options = (!this.options.isEmpty()) ? EnumSet.copyOf(this.options)
: EnumSet.noneOf(Option.class);
processor.accept(options);
return new Options(options);
}
/**
* Create a new instance with the given {@link Option} values.
* @param options the options to include
* @return a new {@link Options} instance
*/
public static Options of(Option... options) {
Assert.notNull(options, "'options' must not be null");
if (options.length == 0) {
return NONE;
}
return new Options(EnumSet.copyOf(Arrays.asList(options)));
}
|
}
/**
* Option flags that can be applied.
*/
public enum Option {
/**
* Ignore all imports properties from the source.
*/
IGNORE_IMPORTS,
/**
* Ignore all profile activation and include properties.
* @since 2.4.3
*/
IGNORE_PROFILES,
/**
* Indicates that the source is "profile specific" and should be included after
* profile specific sibling imports.
* @since 2.4.5
*/
PROFILE_SPECIFIC
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigData.java
| 2
|
请完成以下Java代码
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
|
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Override
public String toString() {
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
}
}
|
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\annotation\pojo\CustomerOmitField.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_Issue getAD_Issue()
{
return get_ValueAsPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class);
}
@Override
public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue)
{
set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue);
}
@Override
public void setAD_Issue_ID (int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID));
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setErrorMsg (java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg);
}
@Override
public void setImportStatus (java.lang.String ImportStatus)
{
set_Value (COLUMNNAME_ImportStatus, ImportStatus);
}
@Override
public java.lang.String getImportStatus()
{
return (java.lang.String)get_Value(COLUMNNAME_ImportStatus);
}
@Override
public void setJsonRequest (java.lang.String JsonRequest)
{
set_ValueNoCheck (COLUMNNAME_JsonRequest, JsonRequest);
}
@Override
public java.lang.String getJsonRequest()
{
return (java.lang.String)get_Value(COLUMNNAME_JsonRequest);
}
@Override
public void setJsonResponse (java.lang.String JsonResponse)
|
{
set_Value (COLUMNNAME_JsonResponse, JsonResponse);
}
@Override
public java.lang.String getJsonResponse()
{
return (java.lang.String)get_Value(COLUMNNAME_JsonResponse);
}
@Override
public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID)
{
if (PP_Cost_Collector_ImportAudit_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID));
}
@Override
public int getPP_Cost_Collector_ImportAudit_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID);
}
@Override
public void setTransactionIdAPI (java.lang.String TransactionIdAPI)
{
set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI);
}
@Override
public java.lang.String getTransactionIdAPI()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
| 1
|
请完成以下Java代码
|
public List<JobDto> getJobs(UriInfo uriInfo, Integer firstResult,
Integer maxResults) {
JobQueryDto queryDto = new JobQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryJobs(queryDto, firstResult, maxResults);
}
@Override
public List<JobDto> queryJobs(JobQueryDto queryDto, Integer firstResult,
Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
JobQuery query = queryDto.toQuery(engine);
List<Job> matchingJobs = QueryUtil.list(query, firstResult, maxResults);
List<JobDto> jobResults = new ArrayList<>();
for (Job job : matchingJobs) {
JobDto resultJob = JobDto.fromJob(job);
jobResults.add(resultJob);
}
return jobResults;
}
@Override
public CountResultDto getJobsCount(UriInfo uriInfo) {
JobQueryDto queryDto = new JobQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryJobsCount(queryDto);
}
@Override
public CountResultDto queryJobsCount(JobQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
JobQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public BatchDto setRetries(SetJobRetriesDto setJobRetriesDto) {
try {
EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto);
EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries());
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
|
JobQuery jobQuery = null;
if (setJobRetriesDto.getJobQuery() != null) {
JobQueryDto jobQueryDto = setJobRetriesDto.getJobQuery();
jobQueryDto.setObjectMapper(getObjectMapper());
jobQuery = jobQueryDto.toQuery(getProcessEngine());
}
try {
SetJobRetriesByJobsAsyncBuilder builder = getProcessEngine().getManagementService()
.setJobRetriesByJobsAsync(setJobRetriesDto.getRetries().intValue())
.jobIds(setJobRetriesDto.getJobIds())
.jobQuery(jobQuery);
if(setJobRetriesDto.isDueDateSet()) {
builder.dueDate(setJobRetriesDto.getDueDate());
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public void updateSuspensionState(JobSuspensionStateDto dto) {
if (dto.getJobId() != null) {
String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
dto.updateSuspensionState(getProcessEngine());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\JobRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public IAsyncBatchBuilder setCountExpected(final int expected)
{
_countExpected = expected;
return this;
}
private final int getCountExpected()
{
return _countExpected;
}
@Override
public IAsyncBatchBuilder setAD_PInstance_Creator_ID(final PInstanceId adPInstanceId)
{
this.adPInstanceId = adPInstanceId;
return this;
}
private final PInstanceId getAD_PInstance_Creator_ID()
{
return adPInstanceId;
}
private AsyncBatchId getParentAsyncBatchId()
{
return Optional.ofNullable(_parentAsyncBatchId)
.orElse(contextFactory.getThreadInheritedWorkpackageAsyncBatch());
}
@Override
public IAsyncBatchBuilder setParentAsyncBatchId(final AsyncBatchId parentAsyncBatchId)
{
_parentAsyncBatchId = parentAsyncBatchId;
return this;
}
@Override
public IAsyncBatchBuilder setName(final String name)
{
_name = name;
return this;
}
public String getName()
{
return _name;
}
@Override
public IAsyncBatchBuilder setDescription(final String description)
{
_description = description;
return this;
}
|
private String getDescription()
{
return _description;
}
private OrgId getOrgId()
{
return orgId;
}
@Override
public IAsyncBatchBuilder setC_Async_Batch_Type(final String internalName)
{
_asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), internalName);
return this;
}
public I_C_Async_Batch_Type getC_Async_Batch_Type()
{
Check.assumeNotNull(_asyncBatchType, "_asyncBatchType not null");
return _asyncBatchType;
}
@Override
public IAsyncBatchBuilder setOrgId(final OrgId orgId)
{
this.orgId = orgId;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<String> getTableIdColumnName(final String tableName, final String recordIdColumnName)
{
Check.assumeNotEmpty(tableName, "Paramter 'tableName' is empty; recordColumnName={}", tableName, recordIdColumnName);
Check.assumeNotEmpty(recordIdColumnName, "Paramter 'recordColumnName' is empty; tableName={}", recordIdColumnName, tableName);
final String prefix = extractPrefixFromRecordColumn(recordIdColumnName);
if (Adempiere.isUnitTestMode())
{
return Optional.of(prefix + ITableRecordReference.COLUMNNAME_AD_Table_ID);
}
final POInfo poInfo = POInfo.getPOInfo(tableName);
// Try with Prefix_AD_Table_ID
String tableColumnName = prefix + ITableRecordReference.COLUMNNAME_AD_Table_ID;
if (poInfo.hasColumnName(tableColumnName))
{
return Optional.of(tableColumnName);
}
// try with Prefix_Table_ID
tableColumnName = prefix + "Table_ID";
if (poInfo.hasColumnName(tableColumnName))
{
return Optional.of(tableColumnName);
}
return Optional.empty();
}
private String extractPrefixFromRecordColumn(final String columnName)
{
final int recordStringIndex = columnName.indexOf(ITableRecordReference.COLUMNNAME_Record_ID);
final String prefix = columnName.substring(0, recordStringIndex);
return prefix;
}
@Override
public String getSingleKeyColumn(final String tableName)
{
if (Adempiere.isUnitTestMode())
{
return InterfaceWrapperHelper.getKeyColumnName(tableName);
}
final POInfo poInfo = POInfo.getPOInfo(tableName);
final List<String> keyColumnNames = poInfo.getKeyColumnNames();
|
if (keyColumnNames.size() != 1)
{
throw new NoSingleKeyColumnException(poInfo);
}
return keyColumnNames.get(0);
}
@Override
public boolean getDefaultAllowLoggingByColumnName(@NonNull final String columnName)
{
if (columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Created)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_CreatedBy)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Updated)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_UpdatedBy))
{
return false;
}
return true;
}
@Override
public boolean getDefaultIsCalculatedByColumnName(@NonNull final String columnName)
{
return columnName.equalsIgnoreCase("Value")
|| columnName.equalsIgnoreCase("DocumentNo")
|| columnName.equalsIgnoreCase("DocStatus")
|| columnName.equalsIgnoreCase("Docaction")
|| columnName.equalsIgnoreCase("Processed")
|| columnName.equalsIgnoreCase("Processing")
|| StringUtils.containsIgnoreCase(columnName, "ExternalID")
|| columnName.equalsIgnoreCase("ExternalHeaderId")
|| columnName.equalsIgnoreCase("ExternalLineId")
|| columnName.equalsIgnoreCase("IsReconciled")
;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\service\impl\ColumnBL.java
| 2
|
请完成以下Java代码
|
public class FruitResource {
@GET
public Viewable get() {
return new Viewable("/index.ftl", "Fruit Index Page");
}
@GET
@Template(name = "/all.ftl")
@Path("/all")
@Produces(MediaType.TEXT_HTML)
public Map<String, Object> getAllFruit() {
final List<Fruit> fruits = new ArrayList<>();
fruits.add(new Fruit("banana", "yellow"));
fruits.add(new Fruit("apple", "red"));
fruits.add(new Fruit("kiwi", "green"));
final Map<String, Object> model = new HashMap<String, Object>();
model.put("items", fruits);
return model;
}
@GET
@ErrorTemplate(name = "/error.ftl")
@Template(name = "/named.ftl")
@Path("{name}")
@Produces(MediaType.TEXT_HTML)
public String getFruitByName(@PathParam("name") String name) {
if (!"banana".equalsIgnoreCase(name)) {
throw new IllegalArgumentException("Fruit not found: " + name);
}
return name;
}
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void createFruit(
@NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
@NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) {
Fruit fruit = new Fruit(name, colour);
SimpleStorageService.storeFruit(fruit);
}
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void updateFruit(@SerialNumber @FormParam("serial") String serial) {
Fruit fruit = new Fruit();
fruit.setSerial(serial);
SimpleStorageService.storeFruit(fruit);
}
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
public void createFruit(@Valid Fruit fruit) {
SimpleStorageService.storeFruit(fruit);
|
}
@POST
@Path("/created")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewFruit(@Valid Fruit fruit) {
String result = "Fruit saved : " + fruit;
return Response.status(Response.Status.CREATED.getStatusCode())
.entity(result)
.build();
}
@GET
@Valid
@Produces(MediaType.APPLICATION_JSON)
@Path("/search/{name}")
public Fruit findFruitByName(@PathParam("name") String name) {
return SimpleStorageService.findByName(name);
}
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/exception")
@Valid
public Fruit exception() {
Fruit fruit = new Fruit();
fruit.setName("a");
fruit.setColour("b");
return fruit;
}
}
|
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\rest\FruitResource.java
| 1
|
请完成以下Java代码
|
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
// Void and delete all responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
voidAndDelete(rfqResponse);
}
rfq.setIsRfQResponseAccepted(false);
rfq.setDocAction(IDocument.ACTION_Complete);
rfq.setProcessed(false);
}
|
private void voidAndDelete(final I_C_RfQResponse rfqResponse)
{
// Prevent deleting/voiding an already closed RfQ response
if (rfqBL.isClosed(rfqResponse))
{
throw new RfQDocumentClosedException(rfqBL.getSummary(rfqResponse));
}
// TODO: FRESH-402 shall we throw exception if the rfqResponse was published?
rfqResponse.setProcessed(false);
InterfaceWrapperHelper.delete(rfqResponse);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQDocumentHandler.java
| 1
|
请完成以下Java代码
|
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(LocalDate registeredDate) {
this.registeredDate = registeredDate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
|
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
}
|
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonb\Person.java
| 1
|
请完成以下Java代码
|
private String calculateTotalPrice(OrderInsertReq orderInsertReq) {
// 获取prodEntityCountMap
Map<ProductEntity, Integer> prodEntityCountMap = orderInsertReq.getProdEntityCountMap();
// 计算订单总价
BigDecimal orderTotalPrice = new BigDecimal("0");
for (ProductEntity productEntity : prodEntityCountMap.keySet()) {
// 本店单价
BigDecimal shopPrice = new BigDecimal(productEntity.getShopPrice());
// 购买数量
BigDecimal count = new BigDecimal(prodEntityCountMap.get(productEntity));
// 单品总价(本店单价*购买数量)
BigDecimal prodTotalPrice = shopPrice.multiply(count);
// 订单总价
orderTotalPrice = orderTotalPrice.add(prodTotalPrice);
}
// 保留两位小数 & 四舍五入
return orderTotalPrice.setScale(2).toString();
}
/**
* 检查产品ID列表对应的卖家是否是同一个
* @param prodIdCountMap 产品ID-数量 的map
*/
private void checkIsSameSeller(Map<String, Integer> prodIdCountMap) {
// 获取prodcutID集合
Set<String> productIdSet = prodIdCountMap.keySet();
// 构造查询请求
List<ProdQueryReq> prodQueryReqList = buildOrderQueryReq(productIdSet);
// 查询
List<ProductEntity> productEntityList = query(prodQueryReqList);
// 校验 TODO lamada表达式还要检查
Map<UserEntity, List<ProductEntity>> companyMap = productEntityList.stream().collect(groupingBy(ProductEntity::getCompanyEntity));
if (companyMap.size() > 1) {
throw new CommonBizException(ExpCodeEnum.SELLER_DIFFERENT);
}
}
/**
* 根据产品ID查询产品列表
* @param prodQueryReqList 产品查询请求
* @return 产品列表
|
*/
private List<ProductEntity> query(List<ProdQueryReq> prodQueryReqList) {
List<ProductEntity> productEntityList = Lists.newArrayList();
for (ProdQueryReq prodQueryReq : prodQueryReqList) {
ProductEntity productEntity = productService.findProducts(prodQueryReq).getData().get(0);
productEntityList.add(productEntity);
}
return productEntityList;
}
/**
* 构造查询请求
* @param productIdSet 产品ID集合
* @return 查询请求列表
*/
private List<ProdQueryReq> buildOrderQueryReq(Set<String> productIdSet) {
List<ProdQueryReq> prodQueryReqList = Lists.newArrayList();
for (String productId : productIdSet) {
ProdQueryReq prodQueryReq = new ProdQueryReq();
prodQueryReq.setId(productId);
prodQueryReqList.add(prodQueryReq);
}
return prodQueryReqList;
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\createorder\CreateOrderComponent.java
| 1
|
请完成以下Java代码
|
public JsonPOSOrder checkoutPayment(@RequestBody JsonPOSPaymentCheckoutRequest request)
{
final POSOrder order = posService.checkoutPayment(POSPaymentCheckoutRequest.builder()
.posTerminalId(request.getPosTerminalId())
.posOrderExternalId(request.getOrder_uuid())
.posPaymentExternalId(request.getPayment_uuid())
.userId(getLoggedUserId())
.cardPayAmount(request.getCardPayAmount())
.cashTenderedAmount(request.getCashTenderedAmount())
.build());
return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
}
@PostMapping("/orders/refundPayment")
public JsonPOSOrder refundPayment(@RequestBody JsonPOSPaymentRefundRequest request)
{
final POSOrder order = posService.refundPayment(request.getPosTerminalId(), request.getOrder_uuid(), request.getPayment_uuid(), getLoggedUserId());
return JsonPOSOrder.from(order, newJsonContext()::getCurrencySymbol);
}
@GetMapping("/orders/receipt/{filename:.*}")
@PostMapping("/orders/receipt/{filename:.*}")
public ResponseEntity<Resource> getReceiptPdf(
@PathVariable("filename") final String filename,
@RequestParam(value = "id") final String idStr)
{
final POSOrderExternalId posOrderExternalId = POSOrderExternalId.ofString(idStr);
|
return posService.getReceiptPdf(posOrderExternalId)
.map(resource -> createPDFResponseEntry(resource, filename))
.orElseGet(() -> ResponseEntity.notFound().build());
}
private static ResponseEntity<Resource> createPDFResponseEntry(@NonNull final Resource resource, @NonNull final String filename)
{
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MimeType.getMediaType(filename));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\POSRestController.java
| 1
|
请完成以下Java代码
|
public static ContextVariablesExpression ofLookupDescriptor(@NonNull final LookupDescriptor lookupDescriptor)
{
final HashSet<String> requiredContextVariables = new HashSet<>();
if (lookupDescriptor instanceof SqlLookupDescriptor)
{
// NOTE: don't add lookupDescriptor.getDependsOnFieldNames() because that collection contains the postQueryPredicate's required params,
// which in case they are missing it's hard to determine if that's a problem or not.
// e.g. FilterWarehouseByDocTypeValidationRule requires C_DocType_ID but behaves OK/expected when the C_DocType_ID context var is missing.
final SqlLookupDescriptor sqlLookupDescriptor = (SqlLookupDescriptor)lookupDescriptor;
final GenericSqlLookupDataSourceFetcher lookupDataSourceFetcher = sqlLookupDescriptor.getLookupDataSourceFetcher();
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookups().getParameters()));
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookupById().getParameters()));
}
else
{
|
requiredContextVariables.addAll(lookupDescriptor.getDependsOnFieldNames());
}
return new ContextVariablesExpression(lookupDescriptor, requiredContextVariables);
}
@Override
public String toString()
{
return String.valueOf(actualExpression);
}
public boolean isConstant()
{
return requiredContextVariables.isEmpty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariablesExpression.java
| 1
|
请完成以下Spring Boot application配置
|
# Make the application available at http://localhost:8080
# These are default settings, but we add them for clarity.
server:
port: 8080
servlet:
context-path: /
# Configure the Authorization Server and User Info Resource Server details
spring:
security:
oauth2:
client:
registration:
baeldung:
client-id: authserver
client-secret: passwordforauthserver
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
baeldung:
token-uri: http://localhost:7070/authserver/oauth/token
authorization-uri: http://localhost:7070/authserver/oauth/authorize
user-info-uri: http://localhost:9000/user
person:
url: http://localhost:9000/person
# Proxies the calls to http://localhost:8080/api/* to our REST service at http://localhost:8081/*
# and automatically incl
|
udes our OAuth2 token in the request headers
zuul:
sensitiveHeaders: Cookie,Set-Cookie
routes:
resource:
path: /api/**
url: http://localhost:9000
user:
path: /user/**
url: http://localhost:9000/user
# Make sure the OAuth2 token is only relayed when using the internal API,
# do not pass any authentication to the external API
proxy:
auth:
routes:
api: oauth2
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-security\auth-client\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public static String secondsToHmm(final long seconds)
{
final long hours = seconds / 3600;
final long hoursRemainder = seconds - (hours * 3600);
final long mins = hoursRemainder < 0 ? -( hoursRemainder / 60 ) : hoursRemainder / 60;
return hours + ":" + (mins < 10L ? "0" + mins : mins);
}
public static long hmmToSeconds(@NonNull final String hmm)
{
if (!matches(hmm))
{
throw new RuntimeException("Wrong format! Was expecting a value in format: " + hmmPattern.toString() + ", but received: " + hmm);
}
|
final String[] parts = hmm.split(":");
final long hours = Long.parseLong(parts[0]);
final long minutes = Long.parseLong(parts[1]);
return (hours * 3600) + (minutes * 60);
}
public static boolean matches(@NonNull final String hmmValue)
{
final Matcher matcher = hmmPattern.matcher(hmmValue);
return matcher.matches();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\HmmUtils.java
| 1
|
请完成以下Java代码
|
class BankAccountParameterizedConstructor extends BankAccount {
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
}
class BankAccountCopyConstructor extends BankAccount {
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountCopyConstructor(BankAccount other) {
this.name = other.name;
|
this.opened = LocalDateTime.now();
this.balance = 0.0f;
}
}
class BankAccountChainedConstructors extends BankAccount {
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountChainedConstructors(String name) {
this(name, LocalDateTime.now(), 0.0f);
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\constructors\BankAccount.java
| 1
|
请完成以下Java代码
|
public class SpringCacheBasedUserCache implements UserCache {
private static final Log logger = LogFactory.getLog(SpringCacheBasedUserCache.class);
private final Cache cache;
public SpringCacheBasedUserCache(Cache cache) {
Assert.notNull(cache, "cache mandatory");
this.cache = cache;
}
@Override
public @Nullable UserDetails getUserFromCache(String username) {
Cache.ValueWrapper element = (username != null) ? this.cache.get(username) : null;
logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; username: " + username));
return (element != null) ? (UserDetails) element.get() : null;
}
@Override
public void putUserInCache(UserDetails user) {
|
logger.debug(LogMessage.of(() -> "Cache put: " + user.getUsername()));
this.cache.put(user.getUsername(), user);
}
public void removeUserFromCache(UserDetails user) {
logger.debug(LogMessage.of(() -> "Cache remove: " + user.getUsername()));
this.removeUserFromCache(user.getUsername());
}
@Override
public void removeUserFromCache(String username) {
this.cache.evict(username);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\cache\SpringCacheBasedUserCache.java
| 1
|
请完成以下Java代码
|
public void setRequireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher) {
Assert.notNull(requireCsrfProtectionMatcher, "requireCsrfProtectionMatcher cannot be null");
this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher;
}
/**
* Specifies a {@link AccessDeniedHandler} that should be used when CSRF protection
* fails.
*
* <p>
* The default is to use AccessDeniedHandlerImpl with no arguments.
* </p>
* @param accessDeniedHandler the {@link AccessDeniedHandler} to use
*/
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.accessDeniedHandler = accessDeniedHandler;
}
/**
* Specifies a {@link CsrfTokenRequestHandler} that is used to make the
* {@link CsrfToken} available as a request attribute.
*
* <p>
* The default is {@link XorCsrfTokenRequestAttributeHandler}.
* </p>
* @param requestHandler the {@link CsrfTokenRequestHandler} to use
* @since 5.8
*/
public void setRequestHandler(CsrfTokenRequestHandler requestHandler) {
Assert.notNull(requestHandler, "requestHandler cannot be null");
this.requestHandler = requestHandler;
}
/**
* Constant time comparison to prevent against timing attacks.
* @param expected
* @param actual
* @return
*/
private static boolean equalsConstantTime(String expected, @Nullable String actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
|
return false;
}
// Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected);
byte[] actualBytes = Utf8.encode(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
@Override
public String toString() {
return "IsNotHttpMethod " + this.allowedMethods;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private List<ReactiveOAuth2AuthorizedClientProvider> getAdditionalAuthorizedClientProviders(
Collection<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders) {
List<ReactiveOAuth2AuthorizedClientProvider> additionalAuthorizedClientProviders = new ArrayList<>(
authorizedClientProviders);
additionalAuthorizedClientProviders
.removeIf((provider) -> KNOWN_AUTHORIZED_CLIENT_PROVIDERS.contains(provider.getClass()));
return additionalAuthorizedClientProviders;
}
private <T extends ReactiveOAuth2AuthorizedClientProvider> T getAuthorizedClientProviderByType(
Collection<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders, Class<T> providerClass) {
T authorizedClientProvider = null;
for (ReactiveOAuth2AuthorizedClientProvider current : authorizedClientProviders) {
if (providerClass.isInstance(current)) {
assertAuthorizedClientProviderIsNull(authorizedClientProvider);
authorizedClientProvider = providerClass.cast(current);
}
}
return authorizedClientProvider;
}
private static void assertAuthorizedClientProviderIsNull(
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) {
if (authorizedClientProvider != null) {
// @formatter:off
|
throw new BeanInitializationException(String.format(
"Unable to create a %s bean. Expected one bean of type %s, but found multiple. " +
"Please consider defining only a single bean of this type, or define a %s bean yourself.",
ReactiveOAuth2AuthorizedClientManager.class.getName(),
authorizedClientProvider.getClass().getName(),
ReactiveOAuth2AuthorizedClientManager.class.getName()));
// @formatter:on
}
}
private <T> String[] getBeanNamesForType(Class<T> beanClass) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, true, true);
}
private <T> T getBeanOfType(ResolvableType resolvableType) {
ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true);
return objectProvider.getIfAvailable();
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\ReactiveOAuth2ClientConfiguration.java
| 2
|
请完成以下Java代码
|
public Date getStartedBefore() {
return startedBefore;
}
@CamundaQueryParam(value="startedBefore", converter = DateConverter.class)
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
@CamundaQueryParam(value="startedAfter", converter = DateConverter.class)
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public Boolean getWithIncident() {
return withIncident;
}
@CamundaQueryParam(value="withIncident", converter = BooleanConverter.class)
public void setWithIncident(Boolean withIncident) {
this.withIncident = withIncident;
}
@Override
protected String getOrderByValue(String sortBy) {
return ORDER_BY_VALUES.get(sortBy);
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
public String getOuterOrderBy() {
String outerOrderBy = getOrderBy();
if (outerOrderBy == null || outerOrderBy.isEmpty()) {
return "ID_ asc";
}
else if (outerOrderBy.contains(".")) {
return outerOrderBy.substring(outerOrderBy.lastIndexOf(".") + 1);
}
else {
|
return outerOrderBy;
}
}
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>();
if (variables == null) {
return values;
}
for (VariableQueryParameterDto variable : variables) {
QueryVariableValue value = new QueryVariableValue(
variable.getName(),
resolveVariableValue(variable.getValue()),
ConditionQueryParameterDto.getQueryOperator(variable.getOperator()),
false);
value.initialize(variableTypes, dbType);
values.add(value);
}
return values;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\AbstractProcessInstanceQueryDto.java
| 1
|
请完成以下Java代码
|
ClassPathIndexFile getClassPathIndex(Archive archive) throws IOException {
if (!archive.isExploded()) {
return null; // Regular archives already have a defined order
}
String location = getClassPathIndexFileLocation(archive);
return ClassPathIndexFile.loadIfPossible(archive.getRootDirectory(), location);
}
private String getClassPathIndexFileLocation(Archive archive) throws IOException {
Manifest manifest = archive.getManifest();
Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null;
String location = (attributes != null) ? attributes.getValue(BOOT_CLASSPATH_INDEX_ATTRIBUTE) : null;
return (location != null) ? location : getEntryPathPrefix() + DEFAULT_CLASSPATH_INDEX_FILE_NAME;
}
/**
* Return the archive being launched or {@code null} if there is no archive.
* @return the launched archive
*/
protected abstract Archive getArchive();
/**
* Returns the main class that should be launched.
* @return the name of the main class
* @throws Exception if the main class cannot be obtained
*/
protected abstract String getMainClass() throws Exception;
/**
* Returns the archives that will be used to construct the class path.
* @return the class path archives
* @throws Exception if the class path archives cannot be obtained
*/
protected abstract Set<URL> getClassPathUrls() throws Exception;
|
/**
* Return the path prefix for relevant entries in the archive.
* @return the entry path prefix
*/
protected String getEntryPathPrefix() {
return "BOOT-INF/";
}
/**
* Determine if the specified entry is a nested item that should be added to the
* classpath.
* @param entry the entry to check
* @return {@code true} if the entry is a nested item (jar or directory)
*/
protected boolean isIncludedOnClassPath(Archive.Entry entry) {
return isLibraryFileOrClassesDirectory(entry);
}
protected boolean isLibraryFileOrClassesDirectory(Archive.Entry entry) {
String name = entry.name();
if (entry.isDirectory()) {
return name.equals("BOOT-INF/classes/");
}
return name.startsWith("BOOT-INF/lib/");
}
protected boolean isIncludedOnClassPathAndNotIndexed(Entry entry) {
if (!isIncludedOnClassPath(entry)) {
return false;
}
return (this.classPathIndex == null) || !this.classPathIndex.containsEntry(entry.name());
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\Launcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AD_UI_Element
{
@Init
public void init()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE )
public void onBeforeElementDelete(@NonNull final I_AD_UI_Element uiElement)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
queryBL.createQueryBuilder(I_AD_UI_ElementField.class)
.addEqualsFilter(I_AD_UI_ElementField.COLUMN_AD_UI_Element_ID, uiElement.getAD_UI_Element_ID())
.create()
.delete();
}
@CalloutMethod(columnNames = I_AD_UI_Element.COLUMNNAME_AD_Field_ID)
public void calloutOnFieldIdChanged(@NonNull final I_AD_UI_Element uiElement)
{
if (uiElement.getAD_Field_ID() > 0)
{
updateNameFromElement(uiElement);
}
}
private void updateNameFromElement(@NonNull final I_AD_UI_Element uiElement)
{
final I_AD_Field field = uiElement.getAD_Field();
final AdElementId fieldElementId = getFieldElementId(field);
final I_AD_Element fieldElement = Services.get(IADElementDAO.class).getById(fieldElementId.getRepoId());
|
uiElement.setName(fieldElement.getName());
uiElement.setDescription(fieldElement.getDescription());
uiElement.setHelp(fieldElement.getHelp());
}
private AdElementId getFieldElementId(final I_AD_Field field)
{
if (field.getAD_Name_ID() > 0)
{
return AdElementId.ofRepoId(field.getAD_Name_ID());
}
else
{
final I_AD_Column fieldColumn = field.getAD_Column();
return AdElementId.ofRepoId(fieldColumn.getAD_Element_ID());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\model\interceptor\AD_UI_Element.java
| 2
|
请完成以下Java代码
|
private Document getAddressDocumentForWriting(final DocumentId addressDocId, final IDocumentChangesCollector changesCollector)
{
return getInnerAddressDocument(addressDocId).copy(CopyMode.CheckOutWritable, changesCollector);
}
public void processAddressDocumentChanges(final int addressDocIdInt, final List<JSONDocumentChangedEvent> events, final IDocumentChangesCollector changesCollector)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, changesCollector);
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit().newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> putAddressDocument(addressDoc));
}
public LookupValue complete(final int addressDocIdInt, @Nullable final List<JSONDocumentChangedEvent> events)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, NullDocumentChangesCollector.instance);
if (events != null && !events.isEmpty())
{
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
}
|
final I_C_Location locationRecord = createC_Location(addressDoc);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> removeAddressDocumentById(addressDocId));
final String locationStr = locationBL.mkAddress(locationRecord);
return IntegerLookupValue.of(locationRecord.getC_Location_ID(), locationStr);
}
private I_C_Location createC_Location(final Document locationDoc)
{
final I_C_Location locationRecord = InterfaceWrapperHelper.create(Env.getCtx(), I_C_Location.class, ITrx.TRXNAME_ThreadInherited);
locationDoc.getFieldViews()
.forEach(locationField -> locationField
.getDescriptor()
.getDataBindingNotNull(AddressFieldBinding.class)
.writeValue(locationRecord, locationField));
locationDAO.save(locationRecord);
return locationRecord;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
private Long id;
private String firstName;
private String secondName;
public User() {
}
public User(final Long id, final String firstName, final String secondName) {
this.id = id;
this.firstName = firstName;
this.secondName = secondName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(final String secondName) {
this.secondName = secondName;
}
public void setId(final Long id) {
this.id = id;
}
public Long getId() {
return id;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
|
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final User user = (User) o;
if (!Objects.equals(id, user.id)) {
return false;
}
if (!Objects.equals(firstName, user.firstName)) {
return false;
}
return Objects.equals(secondName, user.secondName);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (secondName != null ? secondName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", secondName='" + secondName + '\'' +
'}';
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\xml\controller\User.java
| 2
|
请完成以下Java代码
|
public static IAllocationRequestBuilder derive(@NonNull final IAllocationRequest request)
{
return builder().setBaseAllocationRequest(request);
}
@Nullable
private static BPartnerId getBPartnerId(final IAllocationRequest request)
{
final Object referencedModel = AllocationUtils.getReferencedModel(request);
if (referencedModel == null)
{
return null;
}
final Integer bpartnerId = InterfaceWrapperHelper.getValueOrNull(referencedModel, I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID);
return BPartnerId.ofRepoIdOrNull(bpartnerId);
}
/**
* Creates and configures an {@link IHUBuilder} based on the given <code>request</code> (bPartner and date).
|
*
* @return HU builder
*/
public static IHUBuilder createHUBuilder(final IAllocationRequest request)
{
final IHUContext huContext = request.getHuContext();
final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext);
huBuilder.setDate(request.getDate());
huBuilder.setBPartnerId(getBPartnerId(request));
// TODO: huBuilder.setC_BPartner_Location if any
// TODO: set the HU Storage from context to builder
return huBuilder;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationUtils.java
| 1
|
请完成以下Java代码
|
private static DocBaseAndSubType getDocBaseAndSubType(@Nullable final HUAggregationType huAggregationType)
{
if (huAggregationType == null)
{
// #10656 There is no inventory doctype without a subtype. Consider the AggregatedHUInventory as a default
return AggregationType.MULTIPLE_HUS.getDocBaseAndSubType();
}
else
{
return AggregationType.getByHUAggregationType(huAggregationType).getDocBaseAndSubType();
}
}
public void distributeQuantityToHUs(@NonNull final I_M_InventoryLine inventoryLineRecord)
{
inventoryRepository.updateInventoryLineByRecord(inventoryLineRecord, InventoryLine::distributeQtyCountToHUs);
}
public void deleteInventoryLineHUs(@NonNull final InventoryLineId inventoryLineId)
{
inventoryRepository.deleteInventoryLineHUs(inventoryLineId);
}
public InventoryLine toInventoryLine(final I_M_InventoryLine inventoryLineRecord)
{
return inventoryRepository.toInventoryLine(inventoryLineRecord);
}
public Collection<I_M_InventoryLine> retrieveAllLinesForHU(final HuId huId)
{
return inventoryRepository.retrieveAllLinesForHU(huId);
}
public void saveInventoryLineHURecords(final InventoryLine inventoryLine, final @NonNull InventoryId inventoryId)
{
inventoryRepository.saveInventoryLineHURecords(inventoryLine, inventoryId);
}
public Stream<InventoryReference> streamReferences(@NonNull final InventoryQuery query)
{
return inventoryRepository.streamReferences(query);
|
}
public Inventory updateById(@NonNull final InventoryId inventoryId, @NonNull final UnaryOperator<Inventory> updater)
{
return inventoryRepository.updateById(inventoryId, updater);
}
public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater)
{
inventoryRepository.updateByQuery(query, updater);
}
public DraftInventoryLinesCreateResponse createDraftLines(@NonNull final DraftInventoryLinesCreateRequest request)
{
return DraftInventoryLinesCreateCommand.builder()
.inventoryRepository(inventoryRepository)
.huForInventoryLineFactory(huForInventoryLineFactory)
.request(request)
.build()
.execute();
}
public void setQtyCountToQtyBookForInventory(@NonNull final InventoryId inventoryId)
{
inventoryRepository.setQtyCountToQtyBookForInventory(inventoryId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryService.java
| 1
|
请完成以下Java代码
|
public String getVerwendungszweck() {
return verwendungszweck;
}
public void setVerwendungszweck(String verwendungszweck) {
this.verwendungszweck = verwendungszweck;
}
public String getPartnerBlz() {
return partnerBlz;
}
public void setPartnerBlz(String partnerBlz) {
this.partnerBlz = partnerBlz;
}
public String getPartnerKtoNr() {
return partnerKtoNr;
}
public void setPartnerKtoNr(String partnerKtoNr) {
this.partnerKtoNr = partnerKtoNr;
}
public String getPartnerName() {
return partnerName;
|
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
public String getTextschluessel() {
return textschluessel;
}
public void setTextschluessel(String textschluessel) {
this.textschluessel = textschluessel;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
| 1
|
请完成以下Java代码
|
protected void prepare ()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("R_Request_ID"))
p_R_Request_ID = para[i].getParameterAsInt();
else
log.error("prepare - Unknown Parameter: " + name);
}
} // prepare
/**
* Process It
* @return message
* @throws Exception
|
*/
protected String doIt () throws Exception
{
MRequest request = new MRequest (getCtx(), p_R_Request_ID, get_TrxName());
log.info(request.toString());
if (request.get_ID() == 0)
throw new AdempiereUserError("@NotFound@ @R_Request_ID@ " + p_R_Request_ID);
request.setR_Status_ID(); // set default status
request.setProcessed(false);
if (request.save() && !request.isProcessed())
return "@OK@";
return "@Error@";
} // doUt
} // RequestReOpen
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\RequestReOpen.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<String> doubleNumber(@RequestHeader("my-number") int myNumber) {
return new ResponseEntity<>(
String.format("%d * 2 = %d", myNumber, (myNumber * 2)),
HttpStatus.OK);
}
@GetMapping("/listHeaders")
public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, value)));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}
@GetMapping("/multiValue")
public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, String.join("|", value))));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}
@GetMapping("/getBaseUrl")
|
public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) {
InetSocketAddress host = headers.getHost();
String url = "http://" + host.getHostName() + ":" + host.getPort();
return new ResponseEntity<>(String.format("Base URL = %s", url), HttpStatus.OK);
}
@GetMapping("/nonRequiredHeader")
public ResponseEntity<String> evaluateNonRequiredHeader(
@RequestHeader(value = "optional-header", required = false) String optionalHeader) {
return new ResponseEntity<>(
String.format("Was the optional header present? %s!", (optionalHeader == null ? "No" : "Yes")),
HttpStatus.OK);
}
@GetMapping("/default")
public ResponseEntity<String> evaluateDefaultHeaderValue(
@RequestHeader(value = "optional-header", defaultValue = "3600") int optionalHeader) {
return new ResponseEntity<>(String.format("Optional Header is %d", optionalHeader), HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\headers\controller\ReadHeaderRestController.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
|
public ZonedDateTime getPublishDate() {
return publishDate;
}
public void setPublishDate(ZonedDateTime publishDate) {
this.publishDate = publishDate;
}
public String getHtmlContent() {
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-arangodb\src\main\java\com\baeldung\arangodb\model\Article.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JsonExternalSystemShopware6ConfigMapping getMatchingShopware6Mapping()
{
if (shopware6ConfigMappings == null
|| Check.isEmpty(shopware6ConfigMappings.getJsonExternalSystemShopware6ConfigMappingList())
|| bPartnerCustomerGroup == null)
{
return null;
}
return shopware6ConfigMappings.getJsonExternalSystemShopware6ConfigMappingList()
.stream()
.filter(mapping -> mapping.isGroupMatching(bPartnerCustomerGroup.getName()))
.min(Comparator.comparingInt(JsonExternalSystemShopware6ConfigMapping::getSeqNo))
.orElse(null);
}
@NonNull
public ExternalIdentifier getBPExternalIdentifier()
{
final Customer customer = getOrderNotNull().getCustomer();
return customer.getExternalIdentifier(metasfreshIdJsonPath, shopwareIdJsonPath);
}
@NonNull
public ExternalIdentifier getUserId()
{
final Customer customer = getOrderNotNull().getCustomer();
return customer.getShopwareId(shopwareIdJsonPath);
}
@Nullable
public String getExtendedShippingLocationBPartnerName()
{
if (orderShippingAddress == null)
{
throw new RuntimeException("orderShippingAddress cannot be null at this stage!");
}
|
final BiFunction<String, String, String> prepareNameSegment = (segment, separator) -> Optional.ofNullable(segment)
.map(StringUtils::trimBlankToNull)
.map(s -> s + separator)
.orElse("");
final String locationBPartnerName =
prepareNameSegment.apply(orderShippingAddress.getCompany(), "\n")
+ prepareNameSegment.apply(orderShippingAddress.getDepartment(), "\n")
+ prepareNameSegment.apply(getSalutationDisplayNameById(orderShippingAddress.getSalutationId()), " ")
+ prepareNameSegment.apply(orderShippingAddress.getTitle(), " ")
+ prepareNameSegment.apply(orderShippingAddress.getFirstName(), " ")
+ prepareNameSegment.apply(orderShippingAddress.getLastName(), "");
return StringUtils.trimBlankToNull(locationBPartnerName);
}
@NonNull
public JsonAddress getOrderShippingAddressNotNull()
{
return Check.assumeNotNull(orderShippingAddress, "orderShippingAddress cannot be null at this stage!");
}
@Nullable
private String getSalutationDisplayNameById(@Nullable final String salutationId)
{
if (Check.isBlank(salutationId))
{
return null;
}
return salutationInfoProvider.getDisplayNameBySalutationId(salutationId);
}
public void incrementPageIndex()
{
this.ordersResponsePageIndex++;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\ImportOrdersRouteContext.java
| 2
|
请完成以下Java代码
|
public final class MDocTime extends PlainDocument
{
/**
*
*/
private static final long serialVersionUID = 5359545674957190259L;
/**
* Constructor
* @param isHour Hour field
* @param is12Hour 12 hour format
*/
public MDocTime(boolean isHour, boolean is12Hour)
{
super();
m_isHour = isHour;
m_is12Hour = is12Hour;
} // MDocTime
private boolean m_isHour;
private boolean m_is12Hour;
/** Logger */
private static Logger log = LogManager.getLogger(MDocTime.class);
/**
* Insert String
* @param offset offset
* @param string string
* @param attr attributes
* @throws BadLocationException
*/
public void insertString (int offset, String string, AttributeSet attr)
throws BadLocationException
{
// log.debug( "MDocTime.insertString - Offset=" + offset
// + ", String=" + string + ", Attr=" + attr + ", Text=" + getText() + ", Length=" + getText().length());
// manual entry
// DBTextDataBinder.updateText sends stuff at once
if (string != null && string.length() == 1)
{
// ignore if too long
if (offset > 2)
return;
// is it a digit ?
if (!Character.isDigit(string.charAt(0)))
{
log.info("No Digit=" + string);
return;
}
// resulting string
char[] cc = getText().toCharArray();
cc[offset] = string.charAt(0);
String result = new String(cc);
int i = 0;
try
{
i = Integer.parseInt(result.trim());
}
catch (Exception e)
{
log.error(e.toString());
}
if (i < 0)
{
log.info("Invalid value: " + i);
return;
}
// Minutes
if (!m_isHour && i > 59)
{
log.info("Invalid minute value: " + i);
return;
|
}
// Hour
if (m_isHour && m_is12Hour && i > 12)
{
log.info("Invalid 12 hour value: " + i);
return;
}
if (m_isHour && !m_is12Hour && i > 24)
{
log.info("Invalid 24 hour value: " + i);
return;
}
//
// super.remove(offset, 1); // replace current position
}
// Set new character
super.insertString(offset, string, attr);
} // insertString
/**
* Delete String
* @param offset offset
* @param length length
* @throws BadLocationException
*/
public void remove (int offset, int length)
throws BadLocationException
{
// log.debug( "MDocTime.remove - Offset=" + offset + ", Length=" + length);
super.remove(offset, length);
} // deleteString
/**
* Get Full Text (always two character)
* @return text
*/
private String getText()
{
StringBuffer sb = new StringBuffer();
try
{
sb.append(getContent().getString(0, getContent().length()-1)); // cr at end
}
catch (Exception e)
{
}
while (sb.length() < 2)
sb.insert(0, ' ');
return sb.toString();
} // getString
} // MDocTime
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocTime.java
| 1
|
请完成以下Java代码
|
public int getAD_Org_ID()
{
return inoutLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
final I_M_InOut inout = getM_InOut();
return inout.isSOTrx();
}
@Override
public I_C_Country getC_Country()
{
final I_M_InOut inout = getM_InOut();
final I_C_BPartner_Location bpLocation = InterfaceWrapperHelper.load(inout.getC_BPartner_Location_ID(), I_C_BPartner_Location.class);
if (bpLocation == null)
{
|
return null;
}
return bpLocation.getC_Location().getC_Country();
}
private I_M_InOut getM_InOut()
{
final I_M_InOut inout = inoutLine.getM_InOut();
if (inout == null)
{
throw new AdempiereException("M_InOut_ID was not set in " + inoutLine);
}
return inout;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\InOutLineCountryAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class KryoHttpMessageConverter extends
AbstractHttpMessageConverter<Object> {
public static final MediaType KRYO = new MediaType("application", "x-kryo");
private static final ThreadLocal<Kryo> kryoThreadLocal = new ThreadLocal<Kryo>() {
@Override
protected Kryo initialValue() {
final Kryo kryo = new Kryo();
kryo.register(Foo.class, 1);
return kryo;
}
};
public KryoHttpMessageConverter() {
super(KRYO);
}
@Override
protected boolean supports(final Class<?> clazz) {
return Object.class.isAssignableFrom(clazz);
}
|
@Override
protected Object readInternal(final Class<? extends Object> clazz,
final HttpInputMessage inputMessage) throws IOException {
final Input input = new Input(inputMessage.getBody());
return kryoThreadLocal.get().readClassAndObject(input);
}
@Override
protected void writeInternal(final Object object,
final HttpOutputMessage outputMessage) throws IOException {
final Output output = new Output(outputMessage.getBody());
kryoThreadLocal.get().writeClassAndObject(output, object);
output.flush();
}
@Override
protected MediaType getDefaultContentType(final Object object) {
return KRYO;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\config\converter\KryoHttpMessageConverter.java
| 2
|
请完成以下Spring Boot application配置
|
#服务器端口
server:
port: 8501
#数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/seata_order?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
username: root
password: root
# seata配置
seata:
#registry:
# type: nacos
# nacos:
# server-addr: localhost
#config:
# type: nacos
# nacos:
# server-addr: localhost
tx-service-group: bla
|
de-seata-order-group
service:
grouplist:
default: 127.0.0.1:8091
vgroup-mapping:
blade-seata-order-group: default
disable-global-transaction: false
client:
rm:
report-success-enable: false
|
repos\SpringBlade-master\blade-ops\blade-seata-order\src\main\resources\application-dev.yml
| 2
|
请完成以下Java代码
|
public <T> ILockCommand setRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.setRecordsByFilter(clazz, filters);
return this;
}
@Override
public <T> ILockCommand addRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.addRecordsByFilter(clazz, filters);
return this;
}
@Override
public List<LockRecordsByFilter> getSelectionToLock_Filters()
{
return _recordsToLock.getSelection_Filters();
}
@Override
public final AdTableId getSelectionToLock_AD_Table_ID()
{
return _recordsToLock.getSelection_AD_Table_ID();
}
@Override
public final PInstanceId getSelectionToLock_AD_PInstance_ID()
{
return _recordsToLock.getSelection_PInstanceId();
|
}
@Override
public final Iterator<TableRecordReference> getRecordsToLockIterator()
{
return _recordsToLock.getRecordsIterator();
}
@Override
public LockCommand addRecordByModel(final Object model)
{
_recordsToLock.addRecordByModel(model);
return this;
}
@Override
public LockCommand addRecordsByModel(final Collection<?> models)
{
_recordsToLock.addRecordByModels(models);
return this;
}
@Override
public ILockCommand addRecord(@NonNull final TableRecordReference record)
{
_recordsToLock.addRecords(ImmutableSet.of(record));
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
# 对应 RedisProperties 类
redis:
host: 127.0.0.1
port: 6379
# password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码!
database: 0 # Redis 数据库号,默认为 0 。
timeout: 0 # Redis 连接超时时间,单位:毫秒。
# 对应 RedissonProperti
|
es 类
# redisson:
# config: classpath:redisson.yml # 具体的每个配置项,见 org.redisson.config.Config 类。
|
repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-unit-test\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public CostDetailCreateRequest withAmountAndTypeAndQty(@NonNull final CostAmountAndQty amtAndQty, @NonNull final CostAmountType amtType)
{
return withAmountAndTypeAndQty(amtAndQty.getAmt(), amtType, amtAndQty.getQty());
}
public CostDetailCreateRequest withAmountAndQty(
@NonNull final CostAmount amt,
@NonNull final Quantity qty)
{
if (Objects.equals(this.amt, amt)
&& Objects.equals(this.qty, qty))
{
return this;
}
return toBuilder().amt(amt).qty(qty).build();
}
public CostDetailCreateRequest withProductId(@NonNull final ProductId productId)
{
if (ProductId.equals(this.productId, productId))
{
return this;
}
return toBuilder().productId(productId).build();
}
public CostDetailCreateRequest withProductIdAndQty(
@NonNull final ProductId productId,
@NonNull final Quantity qty)
{
if (ProductId.equals(this.productId, productId)
&& Objects.equals(this.qty, qty))
{
return this;
}
return toBuilder().productId(productId).qty(qty).build();
}
public CostDetailCreateRequest withQty(@NonNull final Quantity qty)
|
{
if (Objects.equals(this.qty, qty))
{
return this;
}
return toBuilder().qty(qty).build();
}
public CostDetailCreateRequest withQtyZero()
{
return withQty(qty.toZero());
}
public CostDetailBuilder toCostDetailBuilder()
{
final CostDetailBuilder costDetail = CostDetail.builder()
.clientId(getClientId())
.orgId(getOrgId())
.acctSchemaId(getAcctSchemaId())
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
//
.amtType(getAmtType())
.amt(getAmt())
.qty(getQty())
//
.documentRef(getDocumentRef())
.description(getDescription())
.dateAcct(getDate());
if (isExplicitCostElement())
{
costDetail.costElementId(getCostElementId());
}
return costDetail;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateRequest.java
| 1
|
请完成以下Java代码
|
public Optional<Quantity> retrieveQtyPickedPlanned(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_Packageable_V record = retrievePackageableRecordByShipmentScheduleId(shipmentScheduleId);
if (record == null)
{
return Optional.empty();
}
final I_C_UOM uom = uomsRepo.getById(record.getC_UOM_ID());
final Quantity qtyPickedPlanned = Quantity.of(record.getQtyPickedPlanned(), uom);
return Optional.of(qtyPickedPlanned);
}
private List<I_M_Packageable_V> retrievePackageableRecordsByShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds)
{
if (shipmentScheduleIds.isEmpty())
{
return ImmutableList.of();
}
|
return queryBL
.createQueryBuilder(I_M_Packageable_V.class)
.addInArrayFilter(I_M_Packageable_V.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleIds)
.create()
.list(I_M_Packageable_V.class);
}
@Nullable
private I_M_Packageable_V retrievePackageableRecordByShipmentScheduleId(final ShipmentScheduleId shipmentScheduleId)
{
return queryBL
.createQueryBuilder(I_M_Packageable_V.class)
.addEqualsFilter(I_M_Packageable_V.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId)
.create()
.firstOnly(I_M_Packageable_V.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PackagingDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8080/flowable-rest/dmn-api/dmn-repository/decisions/46b0379c-c0a1-11e6-bc93-6ab56fad108a")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "dmnTest")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "Decision Table One")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "DecisionTableOne")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@ApiModelProperty(example = "This is a simple description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
|
@ApiModelProperty(example = "3")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@ApiModelProperty(example = "dmn-DecisionTableOne.dmn")
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@ApiModelProperty(example = "46aa6b3a-c0a1-11e6-bc93-6ab56fad108a")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "decision_table")
public String getDecisionType() {
return decisionType;
}
public void setDecisionType(String decisionType) {
this.decisionType = decisionType;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DecisionResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public HomepageForwardingFilterConfig homepageForwardingFilterConfig() throws IOException {
String homepage = normalizeHomepageUrl(this.adminServer.path("/"));
List<String> extensionRoutes = new UiRoutesScanner(this.applicationContext)
.scan(this.adminUi.getExtensionResourceLocations());
List<String> routesIncludes = Stream
.concat(DEFAULT_UI_ROUTES.stream(), Stream.concat(extensionRoutes.stream(), Stream.of("/")))
.map(this.adminServer::path)
.toList();
List<String> routesExcludes = Stream
.concat(DEFAULT_UI_ROUTE_EXCLUDES.stream(), this.adminUi.getAdditionalRouteExcludes().stream())
.map(this.adminServer::path)
.toList();
return new HomepageForwardingFilterConfig(homepage, routesIncludes, routesExcludes);
}
@Override
public void addResourceHandlers(
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry registry) {
registry.addResourceHandler(this.adminServer.path("/**"))
.addResourceLocations(this.adminUi.getResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
|
registry.addResourceHandler(this.adminServer.path("/extensions/**"))
.addResourceLocations(this.adminUi.getExtensionResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
}
@Bean
@ConditionalOnMissingBean
public de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter homepageForwardFilter(
HomepageForwardingFilterConfig homepageForwardingFilterConfig) {
return new de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter(
homepageForwardingFilterConfig);
}
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public Collection<DataSource> getAttachments() {
return attachments;
}
public void setAttachments(Collection<DataSource> attachments) {
this.attachments = attachments;
}
public void addAttachment(DataSource attachment) {
if (attachments == null) {
attachments = new ArrayList<>();
}
|
attachments.add(attachment);
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public void addHeader(String name, String value) {
if (headers == null) {
headers = new LinkedHashMap<>();
}
headers.put(name, value);
}
}
|
repos\flowable-engine-main\modules\flowable-mail\src\main\java\org\flowable\mail\common\api\MailMessage.java
| 1
|
请完成以下Java代码
|
public void setMovementDate (final java.sql.Timestamp MovementDate)
{
set_Value (COLUMNNAME_MovementDate, MovementDate);
}
@Override
public java.sql.Timestamp getMovementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MovementDate);
}
@Override
public void setMovementQty (final BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
@Override
public BigDecimal getMovementQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPosted (final boolean Posted)
{
set_Value (COLUMNNAME_Posted, Posted);
}
@Override
public boolean isPosted()
{
return get_ValueAsBoolean(COLUMNNAME_Posted);
}
@Override
public void setPostingError_Issue_ID (final int PostingError_Issue_ID)
{
if (PostingError_Issue_ID < 1)
set_Value (COLUMNNAME_PostingError_Issue_ID, null);
else
set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID);
}
@Override
public int getPostingError_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine()
{
return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class);
}
@Override
public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine)
{
set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine);
}
@Override
public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID);
}
@Override
public int getS_TimeExpenseLine_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
| 1
|
请完成以下Java代码
|
public boolean isLoaded() {
return isLoaded;
}
@Override
public InputStream getValue() {
if (!isLoaded()) {
load();
}
return super.getValue();
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
|
public void setExecutionId(String executionId){
this.executionId = executionId;
};
public String getExecutionId() {
return executionId;
}
@Override
public String toString() {
return "DeferredFileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", "
+ "isTransient=" + isTransient + ", isLoaded=" + isLoaded + "]";
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\value\DeferredFileValueImpl.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.