instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class UserProduct extends AbstractEntity { public static UserProduct build(final User user, final Product product) { final UserProduct userProduct = new UserProduct(); userProduct.setUser(user); userProduct.setProduct(product); return userProduct; } @ManyToOne(fetch = FetchType.LAZY) @NonNull private User user; @ManyToOne @NonNull private Product product; public User getUser() {
return user; } private void setUser(final User user) { this.user = user; } public Product getProduct() { return product; } private void setProduct(final Product product) { this.product = product; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\UserProduct.java
2
请完成以下Java代码
public UserAuthToken createNew(@NonNull final CreateUserAuthTokenRequest request) { final I_AD_User_AuthToken record = newInstanceOutOfTrx(I_AD_User_AuthToken.class); record.setAD_User_ID(request.getUserId().getRepoId()); InterfaceWrapperHelper.setValue(record, I_AD_User_AuthToken.COLUMNNAME_AD_Client_ID, request.getClientId().getRepoId()); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setAD_Role_ID(request.getRoleId().getRepoId()); record.setDescription(request.getDescription()); record.setAuthToken(generateAuthTokenString()); InterfaceWrapperHelper.saveRecord(record); return fromRecord(record); } public void deleteUserAuthTokenByUserId(@NonNull final UserId userId) { queryBL.createQueryBuilder(I_AD_User_AuthToken.class) .addEqualsFilter(I_AD_User_AuthToken.COLUMN_AD_User_ID, userId)
.create() .delete(); } @NonNull public UserAuthToken getById(@NonNull final UserAuthTokenId id) { final I_AD_User_AuthToken record = queryBL.createQueryBuilder(I_AD_User_AuthToken.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_User_AuthToken_ID, id) .create() .firstOnlyNotNull(I_AD_User_AuthToken.class); return fromRecord(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserAuthTokenRepository.java
1
请完成以下Java代码
public void setA_Purchase_Price (BigDecimal A_Purchase_Price) { set_Value (COLUMNNAME_A_Purchase_Price, A_Purchase_Price); } /** Get Option Purchase Price. @return Option Purchase Price */ public BigDecimal getA_Purchase_Price () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Purchase_Price); if (bd == null) return Env.ZERO; return bd; } /** Set Business Partner . @param C_BPartner_ID Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Fin.java
1
请完成以下Java代码
public StockDetailsView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } @Override public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } @Override public Stream<IView> streamAllViews() { return Stream.empty(); } @Override public void invalidateView(final ViewId viewId) { final StockDetailsView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public IView createView(@NonNull final CreateViewRequest request) { final StockDetailsRowsData stockDetailsRowData = createStockDetailsRowData(request); return new StockDetailsView( request.getViewId(), request.getParentViewId(), stockDetailsRowData, ImmutableDocumentFilterDescriptorsProvider.of(createEmptyFilterDescriptor())); } private DocumentFilterDescriptor createEmptyFilterDescriptor() { return ProductFilterUtil.createFilterDescriptor(); } private StockDetailsRowsData createStockDetailsRowData(@NonNull final CreateViewRequest request) { final DocumentFilterList filters = request.getStickyFilters(); final HUStockInfoQueryBuilder query = HUStockInfoQuery.builder(); for (final DocumentFilter filter : filters.toList()) { final HUStockInfoSingleQueryBuilder singleQuery = HUStockInfoSingleQuery.builder(); final int productRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Product_ID, -1);
singleQuery.productId(ProductId.ofRepoIdOrNull(productRepoId)); final int attributeRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Attribute_ID, -1); singleQuery.attributeId(AttributeId.ofRepoIdOrNull(attributeRepoId)); final String attributeValue = filter.getParameterValueAsString(I_M_HU_Stock_Detail_V.COLUMNNAME_AttributeValue, null); if (MaterialCockpitUtil.DONT_FILTER.equals(attributeValue)) { singleQuery.attributeValue(AttributeValue.DONT_FILTER); } else { singleQuery.attributeValue(AttributeValue.NOT_EMPTY); } query.singleQuery(singleQuery.build()); } final Stream<HUStockInfo> huStockInfos = huStockInfoRepository.getByQuery(query.build()); return StockDetailsRowsData.of(huStockInfos); } @Override public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(windowId) // .caption(caption) .setFilters(ImmutableList.of(createEmptyFilterDescriptor())) .addElementsFromViewRowClass(StockDetailsRow.class, viewDataType) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsViewFactory.java
1
请完成以下Java代码
public void setAD_OrgType_ID (int AD_OrgType_ID) { if (AD_OrgType_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_OrgType_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_OrgType_ID, Integer.valueOf(AD_OrgType_ID)); } /** Get Organization Type. @return Organization Type */ public int getAD_OrgType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgType_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_PrintColor getAD_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getAD_PrintColor_ID(), get_TrxName()); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_Value (COLUMNNAME_AD_PrintColor_ID, null); else set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record
*/ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgType.java
1
请在Spring Boot框架中完成以下Java代码
class NoDslContextBeanFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchBeanDefinitionException> implements Ordered { private final BeanFactory beanFactory; NoDslContextBeanFailureAnalyzer(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override protected @Nullable FailureAnalysis analyze(Throwable rootFailure, NoSuchBeanDefinitionException cause) { if (DSLContext.class.equals(cause.getBeanType()) && hasR2dbcAutoConfiguration()) { return new FailureAnalysis( "jOOQ has not been auto-configured as R2DBC has been auto-configured in favor of JDBC and jOOQ " + "auto-configuration does not yet support R2DBC. ", "To use jOOQ with JDBC, exclude R2dbcAutoConfiguration. To use jOOQ with R2DBC, define your own " + "jOOQ configuration.", cause); } return null; }
private boolean hasR2dbcAutoConfiguration() { try { this.beanFactory.getBean(R2dbcAutoConfiguration.class); return true; } catch (Exception ex) { return false; } } @Override public int getOrder() { return 0; } }
repos\spring-boot-4.0.1\module\spring-boot-jooq\src\main\java\org\springframework\boot\jooq\autoconfigure\NoDslContextBeanFailureAnalyzer.java
2
请完成以下Java代码
public de.metas.handlingunits.model.I_M_HU_PI getM_HU_PI() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class); } @Override public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI) { set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_Value (COLUMNNAME_M_HU_PI_ID, null); else set_Value (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setM_HU_Process_ID (final int M_HU_Process_ID) { if (M_HU_Process_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, M_HU_Process_ID); } @Override public int getM_HU_Process_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Process_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Process.java
1
请完成以下Java代码
public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isInterrupting() { return isInterrupting; } public void setInterrupting(boolean isInterrupting) { this.isInterrupting = isInterrupting; } public List<FormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<FormProperty> formProperties) { this.formProperties = formProperties; } public String getValidateFormFields() { return validateFormFields; } public void setValidateFormFields(String validateFormFields) { this.validateFormFields = validateFormFields; } @Override public StartEvent clone() { StartEvent clone = new StartEvent(); clone.setValues(this); return clone;
} public void setValues(StartEvent otherEvent) { super.setValues(otherEvent); setInitiator(otherEvent.getInitiator()); setFormKey(otherEvent.getFormKey()); setSameDeployment(otherEvent.isInterrupting); setInterrupting(otherEvent.isInterrupting); setValidateFormFields(otherEvent.validateFormFields); formProperties = new ArrayList<>(); if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) { for (FormProperty property : otherEvent.getFormProperties()) { formProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\StartEvent.java
1
请完成以下Java代码
private ViewResult getPage(final PageIndex pageIndex) { try { return cache.get(pageIndex); } catch (final ExecutionException e) { throw AdempiereException.wrapIfNeeded(e); } } @Override @Nullable public IViewRow getRow(final int rowIndex) { final ViewResult page = getPage(PageIndex.getPageContainingRow(rowIndex, pageSize)); final int rowIndexInPage = rowIndex - page.getFirstRow(); if (rowIndexInPage < 0) { // shall not happen return null; } final List<IViewRow> rows = page.getPage(); if (rowIndexInPage >= rows.size()) { return null; } return rows.get(rowIndexInPage); } @Override public int getRowCount() { return (int)view.size(); } } private static class ListRowsSupplier implements RowsSupplier { private final ImmutableList<IViewRow> rows; private ListRowsSupplier(@NonNull final IView view, @NonNull final DocumentIdsSelection rowIds) { Check.assume(!rowIds.isAll(), "rowIds is not ALL"); this.rows = view.streamByIds(rowIds).collect(ImmutableList.toImmutableList()); } @Override public IViewRow getRow(final int rowIndex) { Check.assume(rowIndex >= 0, "rowIndex >= 0"); final int rowsCount = rows.size();
Check.assume(rowIndex < rowsCount, "rowIndex < {}", rowsCount); return rows.get(rowIndex); } @Override public int getRowCount() { return rows.size(); } } @Override protected List<CellValue> getNextRow() { final ArrayList<CellValue> result = new ArrayList<>(); for (int i = 0; i < getColumnCount(); i++) { result.add(getValueAt(rowNumber, i)); } rowNumber++; return result; } @Override protected boolean hasNextRow() { return rowNumber < getRowCount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewExcelExporter.java
1
请完成以下Java代码
public IDataSet load(String folderPath, String charsetName) throws IllegalArgumentException, IOException { return load(folderPath, charsetName, 1.); } @Override public IDataSet load(String folderPath) throws IllegalArgumentException, IOException { return load(folderPath, "UTF-8"); } @Override public boolean isTestingDataSet() { return testingDataSet; } @Override public IDataSet load(String folderPath, String charsetName, double percentage) throws IllegalArgumentException, IOException { if (folderPath == null) throw new IllegalArgumentException("参数 folderPath == null"); File root = new File(folderPath); if (!root.exists()) throw new IllegalArgumentException(String.format("目录 %s 不存在", root.getAbsolutePath())); if (!root.isDirectory()) throw new IllegalArgumentException(String.format("目录 %s 不是一个目录", root.getAbsolutePath())); if (percentage > 1.0 || percentage < -1.0) throw new IllegalArgumentException("percentage 的绝对值必须介于[0, 1]之间"); File[] folders = root.listFiles(); if (folders == null) return null; ConsoleLogger.logger.start("模式:%s\n文本编码:%s\n根目录:%s\n加载中...\n", testingDataSet ? "测试集" : "训练集", charsetName, folderPath); for (File folder : folders) { if (folder.isFile()) continue; File[] files = folder.listFiles(); if (files == null) continue; String category = folder.getName(); ConsoleLogger.logger.out("[%s]...", category); int b, e; if (percentage > 0) { b = 0; e = (int) (files.length * percentage); } else { b = (int) (files.length * (1 + percentage)); e = files.length; } int logEvery = (int) Math.ceil((e - b) / 10000f); for (int i = b; i < e; i++) { add(folder.getName(), TextProcessUtility.readTxt(files[i], charsetName)); if (i % logEvery == 0) { ConsoleLogger.logger.out("%c[%s]...%.2f%%", 13, category, MathUtility.percentage(i - b + 1, e - b));
} } ConsoleLogger.logger.out(" %d 篇文档\n", e - b); } ConsoleLogger.logger.finish(" 加载了 %d 个类目,共 %d 篇文档\n", getCatalog().size(), size()); return this; } @Override public IDataSet load(String folderPath, double rate) throws IllegalArgumentException, IOException { return null; } @Override public IDataSet add(Map<String, String[]> testingDataSet) { for (Map.Entry<String, String[]> entry : testingDataSet.entrySet()) { for (String document : entry.getValue()) { add(entry.getKey(), document); } } return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\AbstractDataSet.java
1
请完成以下Java代码
protected DbEntityManager getDbEntityManager() { return getCommandContext().getDbEntityManager(); } protected JobManager getJobManager() { return getCommandContext().getJobManager(); } protected JobDefinitionManager getJobDefinitionManager() { return getCommandContext().getJobDefinitionManager(); } protected EventSubscriptionManager getEventSubscriptionManager() { return getCommandContext().getEventSubscriptionManager(); } protected ProcessDefinitionManager getProcessDefinitionManager() { return getCommandContext().getProcessDefinitionManager(); } // getters/setters ///////////////////////////////////////////////////////////////////////////////////
public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public boolean isSuspended() { return activiti5ProcessInstance.isSuspended(); } @Override public Map<String, Object> getProcessVariables() { return activiti5ProcessInstance.getProcessVariables(); } @Override public String getTenantId() { return activiti5ProcessInstance.getTenantId(); } @Override public String getName() { return activiti5ProcessInstance.getName(); } @Override public String getDescription() { return activiti5ProcessInstance.getDescription(); } @Override public String getLocalizedName() { return activiti5ProcessInstance.getLocalizedName(); } @Override public String getLocalizedDescription() { return activiti5ProcessInstance.getLocalizedDescription(); } public org.activiti.engine.runtime.ProcessInstance getRawObject() { return activiti5ProcessInstance; } @Override public Date getStartTime() { return null; } @Override public String getStartUserId() { return null;
} @Override public String getCallbackId() { return null; } @Override public String getCallbackType() { return null; } @Override public String getReferenceId() { return null; } @Override public String getReferenceType() { return null; } @Override public String getPropagatedStageInstanceId() { return null; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5ProcessInstanceWrapper.java
1
请完成以下Java代码
private List<RelatedProcessDescriptor> createAdditionalRelatedProcessDescriptors() { return ImmutableList.of( // allow to open the HU-editor for various picking related purposes createProcessDescriptorForPickingSlotView(WEBUI_Picking_HUEditor_Launcher.class), // fine-picking related processes createProcessDescriptorForPickingSlotView(WEBUI_Picking_PickQtyToNewHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_PickQtyToComputedHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_PickQtyToExistingHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_ReturnQtyToSourceHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_ForcePickToNewHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_ForcePickToComputedHU.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_ForcePickToExistingHU.class), // note that WEBUI_Picking_M_Source_HU_Create is called from the HU-editor createProcessDescriptorForPickingSlotView(WEBUI_Picking_M_Source_HU_Delete.class), // complete-HU-picking related processes; note that the add to-slot-process is called from the HU-editor createProcessDescriptorForPickingSlotView(WEBUI_Picking_RemoveHUFromPickingSlot.class), // "picking-lifecycle" processes createProcessDescriptorForPickingSlotView(WEBUI_Picking_M_Picking_Candidate_Process.class), createProcessDescriptorForPickingSlotView(WEBUI_Picking_M_Picking_Candidate_Unprocess.class), // label createProcessDescriptorForPickingSlotView(WEBUI_Picking_TU_Label.class)); } private static RelatedProcessDescriptor createProcessDescriptorForPickingSlotView(@NonNull final Class<?> processClass)
{ final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(processClass); Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass); return RelatedProcessDescriptor.builder() .processId(processId) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } @Value @Builder private static class CreatePickingSlotRepoQueryReq { DocumentFilterList filters; @NonNull ShipmentScheduleId currentShipmentScheduleId; Set<ShipmentScheduleId> allShipmentScheduleIds; boolean includeAllShipmentSchedules; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewFactory.java
1
请完成以下Java代码
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_FTS_Config_SourceModel_ID (final int ES_FTS_Config_SourceModel_ID) { if (ES_FTS_Config_SourceModel_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_SourceModel_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_SourceModel_ID, ES_FTS_Config_SourceModel_ID); } @Override public int getES_FTS_Config_SourceModel_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_SourceModel_ID); } @Override public org.compiere.model.I_AD_Column getParent_Column() { return get_ValueAsPO(COLUMNNAME_Parent_Column_ID, org.compiere.model.I_AD_Column.class); }
@Override public void setParent_Column(final org.compiere.model.I_AD_Column Parent_Column) { set_ValueFromPO(COLUMNNAME_Parent_Column_ID, org.compiere.model.I_AD_Column.class, Parent_Column); } @Override public void setParent_Column_ID (final int Parent_Column_ID) { if (Parent_Column_ID < 1) set_Value (COLUMNNAME_Parent_Column_ID, null); else set_Value (COLUMNNAME_Parent_Column_ID, Parent_Column_ID); } @Override public int getParent_Column_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Column_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config_SourceModel.java
1
请完成以下Java代码
public void setReportStatus(Integer reportStatus) { this.reportStatus = reportStatus; } public Integer getHandleStatus() { return handleStatus; } public void setHandleStatus(Integer handleStatus) { this.handleStatus = handleStatus; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", reportType=").append(reportType); sb.append(", reportMemberName=").append(reportMemberName); sb.append(", createTime=").append(createTime); sb.append(", reportObject=").append(reportObject); sb.append(", reportStatus=").append(reportStatus); sb.append(", handleStatus=").append(handleStatus); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsMemberReport.java
1
请在Spring Boot框架中完成以下Java代码
public Set<Object> setMembers(String key) { return setOperations.members(key); } public boolean setIsMember(String key, Object value) { return setOperations.isMember(key, value); } public long setAdd(String key, Object... values) { return setOperations.add(key, values); } public long setAdd(String key, long milliseconds, Object... values) { Long count = setOperations.add(key, values); if (milliseconds > 0) { expire(key, milliseconds); } return count; } public long setSize(String key) { return setOperations.size(key); } public long setRemove(String key, Object... values) { return setOperations.remove(key, values); } //===============================list================================= public List<Object> lGet(String key, long start, long end) { return listOperations.range(key, start, end); } public long listSize(String key) { return listOperations.size(key); } public Object listIndex(String key, long index) { return listOperations.index(key, index); } public void listRightPush(String key, Object value) { listOperations.rightPush(key, value); }
public boolean listRightPush(String key, Object value, long milliseconds) { listOperations.rightPush(key, value); if (milliseconds > 0) { return expire(key, milliseconds); } return false; } public long listRightPushAll(String key, List<Object> value) { return listOperations.rightPushAll(key, value); } public boolean listRightPushAll(String key, List<Object> value, long milliseconds) { listOperations.rightPushAll(key, value); if (milliseconds > 0) { return expire(key, milliseconds); } return false; } public void listSet(String key, long index, Object value) { listOperations.set(key, index, value); } public long listRemove(String key, long count, Object value) { return listOperations.remove(key, count, value); } //===============================zset================================= public boolean zsAdd(String key, Object value, double score) { return zSetOperations.add(key, value, score); } }
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java
2
请完成以下Java代码
public class MapMapper { private final Map<String, String> source; private final Map<String, Object> target; public MapMapper(@NonNull Map<String, String> source, @NonNull Map<String, Object> target) { Assert.notNull(source, "Source Map must not be null"); Assert.notNull(target, "Target Map must not be null"); this.source = source; this.target = target; } 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代码
default Boolean getEmailVerified() { return this.getClaimAsBoolean(StandardClaimNames.EMAIL_VERIFIED); } /** * Returns the user's gender {@code (gender)}. * @return the user's gender */ default String getGender() { return this.getClaimAsString(StandardClaimNames.GENDER); } /** * Returns the user's birth date {@code (birthdate)}. * @return the user's birth date */ default String getBirthdate() { return this.getClaimAsString(StandardClaimNames.BIRTHDATE); } /** * Returns the user's time zone {@code (zoneinfo)}. * @return the user's time zone */ default String getZoneInfo() { return this.getClaimAsString(StandardClaimNames.ZONEINFO); } /** * Returns the user's locale {@code (locale)}. * @return the user's locale */ default String getLocale() { return this.getClaimAsString(StandardClaimNames.LOCALE); } /** * Returns the user's preferred phone number {@code (phone_number)}. * @return the user's preferred phone number */ default String getPhoneNumber() { return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER); } /** * Returns {@code true} if the user's phone number has been verified * {@code (phone_number_verified)}, otherwise {@code false}. * @return {@code true} if the user's phone number has been verified, otherwise * {@code false} */ default Boolean getPhoneNumberVerified() {
return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED); } /** * Returns the user's preferred postal address {@code (address)}. * @return the user's preferred postal address */ default AddressStandardClaim getAddress() { Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS); return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build() : new DefaultAddressStandardClaim.Builder().build()); } /** * Returns the time the user's information was last updated {@code (updated_at)}. * @return the time the user's information was last updated */ default Instant getUpdatedAt() { return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
1
请完成以下Java代码
public class Tenant extends BaseEntity { @Serial private static final long serialVersionUID = 1L; /** * 主键id */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 租户ID */ @Schema(description = "租户ID") private String tenantId; /** * 租户名称 */ @Schema(description = "租户名称") private String tenantName; /** * 域名地址 */ @Schema(description = "域名地址")
private String domain; /** * 联系人 */ @Schema(description = "联系人") private String linkman; /** * 联系电话 */ @Schema(description = "联系电话") private String contactNumber; /** * 联系地址 */ @Schema(description = "联系地址") private String address; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Tenant.java
1
请完成以下Java代码
public class MigrationVariableValidationReportDto extends VariableValueDto { protected List<String> failures; public List<String> getFailures() { return failures; } public void setFailures(List<String> failures) { this.failures = failures; } public static Map<String, MigrationVariableValidationReportDto> from(Map<String, MigrationVariableValidationReport> variableReports) { Map<String, MigrationVariableValidationReportDto> dtos = new HashMap<>(); variableReports.forEach((name, report) ->
dtos.put(name, MigrationVariableValidationReportDto.from(report))); return dtos; } public static MigrationVariableValidationReportDto from(MigrationVariableValidationReport variableReport) { MigrationVariableValidationReportDto dto = new MigrationVariableValidationReportDto(); VariableValueDto valueDto = VariableValueDto.fromTypedValue(variableReport.getTypedValue()); dto.setType(valueDto.getType()); dto.setValue(valueDto.getValue()); dto.setValueInfo(valueDto.getValueInfo()); dto.setFailures(variableReport.getFailures()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationVariableValidationReportDto.java
1
请完成以下Java代码
public void setParameterSeqNo (int ParameterSeqNo) { set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo)); } public int getParameterSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo); if (ii == null) return 0; return ii.intValue(); } public void setParameterDisplayLogic (String ParameterDisplayLogic) { set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic); } public String getParameterDisplayLogic () { return (String)get_Value(COLUMNNAME_ParameterDisplayLogic); } public void setColumnName (String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } public String getColumnName () { return (String)get_Value(COLUMNNAME_ColumnName); } /** Set Query Criteria Function. @param QueryCriteriaFunction column used for adding a sql function to query criteria
*/ public void setQueryCriteriaFunction (String QueryCriteriaFunction) { set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction); } /** Get Query Criteria Function. @return column used for adding a sql function to query criteria */ public String getQueryCriteriaFunction () { return (String)get_Value(COLUMNNAME_QueryCriteriaFunction); } @Override public void setDefaultValue (String DefaultValue) { set_Value (COLUMNNAME_DefaultValue, DefaultValue); } @Override public String getDefaultValue () { return (String)get_Value(COLUMNNAME_DefaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(SpringBootMvcFnApplication.class, args); } @Bean RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) { return pc.productListing(ps); } @Bean RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) { return route().add(pc.remainingProductRoutes(ps)) .before(req -> { LOG.info("Found a route which matches " + req.uri() .getPath()); return req; }) .after((req, res) -> { if (res.statusCode() == HttpStatus.OK) { LOG.info("Finished processing request " + req.uri() .getPath()); } else { LOG.info("There was an error while processing request" + req.uri()); } return res; }) .onError(Throwable.class, (e, res) -> { LOG.error("Fatal exception has occurred", e); return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}) .build() .and(route(RequestPredicates.all(), req -> notFound().build())); } public static class Error { private String errorMessage; public Error(String message) { this.errorMessage = message; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\SpringBootMvcFnApplication.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getCareType() { return careType; } public void setCareType(BigDecimal careType) { this.careType = careType; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractSalesContracts insuranceContractSalesContracts = (InsuranceContractSalesContracts) o; return Objects.equals(this.name, insuranceContractSalesContracts.name) && Objects.equals(this.careType, insuranceContractSalesContracts.careType); } @Override public int hashCode() { return Objects.hash(name, careType); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractSalesContracts {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" careType: ").append(toIndentedString(careType)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractSalesContracts.java
2
请完成以下Java代码
public class CachedBodyOutputMessage implements ReactiveHttpOutputMessage { private final DataBufferFactory bufferFactory; private final HttpHeaders httpHeaders; private boolean cached = false; private @Nullable Flux<DataBuffer> body = null; public CachedBodyOutputMessage(ServerWebExchange exchange, HttpHeaders httpHeaders) { this.bufferFactory = exchange.getResponse().bufferFactory(); this.httpHeaders = httpHeaders; } @Override public void beforeCommit(Supplier<? extends Mono<Void>> action) { } @Override public boolean isCommitted() { return false; } boolean isCached() { return this.cached; } @Override public HttpHeaders getHeaders() { return this.httpHeaders; } @Override public DataBufferFactory bufferFactory() { return this.bufferFactory; } /**
* Return the request body, or an error stream if the body was never set or when. * @return body as {@link Flux} */ public Flux<DataBuffer> getBody() { if (body == null) { return Flux .error(new IllegalStateException("The body is not set. " + "Did handling complete with success?")); } return this.body; } public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { this.body = Flux.from(body); this.cached = true; return Mono.empty(); } @Override public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { return writeWith(Flux.from(body).flatMap(p -> p)); } @Override public Mono<Void> setComplete() { return writeWith(Flux.empty()); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\CachedBodyOutputMessage.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getHasChildren() { return subCount > 0; } @ApiModelProperty(value = "是否为叶子") public Boolean getLeaf() { return subCount <= 0; } @ApiModelProperty(value = "部门全名") public String getLabel() { return name; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeptDto deptDto = (DeptDto) o; return Objects.equals(id, deptDto.id) && Objects.equals(name, deptDto.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\dto\DeptDto.java
2
请完成以下Java代码
public class NumberInfo { private int number; public NumberInfo(int number) { this.number = number; } public static NumberInfo from(int number) { return new NumberInfo(number); } public boolean isPositive() { return number > 0; } public boolean isEven() { return number % 2 == 0; } public int getNumber() { return number; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NumberInfo that = (NumberInfo) o; return number == that.number; } @Override public int hashCode() { return Objects.hash(number); } @Override public String toString() { return "NumberInfo{" + "number=" + number + '}'; } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\conditionalflow\model\NumberInfo.java
1
请完成以下Java代码
public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic) { set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic); } @Override public java.lang.String getReadOnlyLogic() { return get_ValueAsString(COLUMNNAME_ReadOnlyLogic); } @Override public void setSelectionColumnSeqNo (final int SelectionColumnSeqNo) { set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo); } @Override public int getSelectionColumnSeqNo() { return get_ValueAsInt(COLUMNNAME_SelectionColumnSeqNo); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } @Override public void setValueMax (final @Nullable java.lang.String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public java.lang.String getValueMax() { return get_ValueAsString(COLUMNNAME_ValueMax);
} @Override public void setValueMin (final @Nullable java.lang.String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public java.lang.String getValueMin() { return get_ValueAsString(COLUMNNAME_ValueMin); } @Override public void setVersion (final BigDecimal Version) { set_Value (COLUMNNAME_Version, Version); } @Override public BigDecimal getVersion() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Version); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column.java
1
请完成以下Java代码
public Enumeration<String> getHeaders(String name) { List<String> list = header(name); if (list != null) { return new Vector<String>(list).elements(); } return super.getHeaders(name); } @Override public String getHeader(String name) { List<String> list = header(name); if (list != null && !list.isEmpty()) { return list.iterator().next(); } return super.getHeader(name); } } } /** * Convenience class that converts an incoming request input stream into a form that can * be easily deserialized to a Java object using Spring message converters. It is only * used in a local forward dispatch, in which case there is a danger that the request body * will need to be read and analysed more than once. Apart from using the message * converters the other main feature of this class is that the request body is cached and * can be read repeatedly as necessary. * * @author Dave Syer * */ class ServletOutputToInputConverter extends HttpServletResponseWrapper { private StringBuilder builder = new StringBuilder(); ServletOutputToInputConverter(HttpServletResponse response) { super(response); } @Override public ServletOutputStream getOutputStream() throws IOException { return new ServletOutputStream() { @Override public void write(int b) throws IOException { builder.append(Character.valueOf((char) b)); } @Override public void setWriteListener(WriteListener listener) { } @Override public boolean isReady() {
return true; } }; } public ServletInputStream getInputStream() { ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return body.read(); } @Override public void setReadListener(ReadListener listener) { } @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return body.available() <= 0; } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
1
请完成以下Java代码
public OAuth2AccessToken getAccessToken() { return get(OAuth2AccessToken.class); } /** * Returns the {@link OAuth2Authorization authorization}. * @return the {@link OAuth2Authorization} */ public OAuth2Authorization getAuthorization() { return get(OAuth2Authorization.class); } /** * Constructs a new {@link Builder} with the provided * {@link OidcUserInfoAuthenticationToken}. * @param authentication the {@link OidcUserInfoAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OidcUserInfoAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OidcUserInfoAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OidcUserInfoAuthenticationContext, Builder> { private Builder(OidcUserInfoAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link OAuth2AccessToken OAuth 2.0 Access Token}. * @param accessToken the {@link OAuth2AccessToken} * @return the {@link Builder} for further configuration */ public Builder accessToken(OAuth2AccessToken accessToken) {
return put(OAuth2AccessToken.class, accessToken); } /** * Sets the {@link OAuth2Authorization authorization}. * @param authorization the {@link OAuth2Authorization} * @return the {@link Builder} for further configuration */ public Builder authorization(OAuth2Authorization authorization) { return put(OAuth2Authorization.class, authorization); } /** * Builds a new {@link OidcUserInfoAuthenticationContext}. * @return the {@link OidcUserInfoAuthenticationContext} */ @Override public OidcUserInfoAuthenticationContext build() { Assert.notNull(get(OAuth2AccessToken.class), "accessToken cannot be null"); Assert.notNull(get(OAuth2Authorization.class), "authorization cannot be null"); return new OidcUserInfoAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcUserInfoAuthenticationContext.java
1
请完成以下Java代码
public class ColumnEntity { /** * 列表 */ private String columnName; /** * 数据类型 */ private String dataType; /** * 备注 */ private String comments; /** * 驼峰属性 */ private String caseAttrName; /**
* 普通属性 */ private String lowerAttrName; /** * 属性类型 */ private String attrType; /** * jdbc类型 */ private String jdbcType; /** * 其他信息 */ private String extra; }
repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\entity\ColumnEntity.java
1
请完成以下Java代码
public boolean isLine() { return MFColorType.LINES.equals(getType()); } public boolean isTexture() { return MFColorType.TEXTURE.equals(getType()); } public MFColor setGradientUpperColor(final Color color) { if (!isGradient() || color == null) { return this; } return toBuilder().gradientUpperColor(color).build(); } public MFColor setGradientLowerColor(final Color color) { if (!isGradient() || color == null) { return this; } return toBuilder().gradientLowerColor(color).build(); } public MFColor setGradientStartPoint(final int startPoint) { if (!isGradient()) { return this; } return toBuilder().gradientStartPoint(startPoint).build(); } public MFColor setGradientRepeatDistance(final int repeatDistance) { if (!isGradient()) { return this; } return toBuilder().gradientRepeatDistance(repeatDistance).build(); } public MFColor setTextureURL(final URL textureURL) { if (!isTexture() || textureURL == null) { return this; } return toBuilder().textureURL(textureURL).build(); } public MFColor setTextureTaintColor(final Color color) { if (!isTexture() || color == null) { return this; } return toBuilder().textureTaintColor(color).build(); } public MFColor setTextureCompositeAlpha(final float alpha) { if (!isTexture()) { return this; } return toBuilder().textureCompositeAlpha(alpha).build(); } public MFColor setLineColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineColor(color).build(); } public MFColor setLineBackColor(final Color color) { if (!isLine() || color == null) {
return this; } return toBuilder().lineBackColor(color).build(); } public MFColor setLineWidth(final float width) { if (!isLine()) { return this; } return toBuilder().lineWidth(width).build(); } public MFColor setLineDistance(final int distance) { if (!isLine()) { return this; } return toBuilder().lineDistance(distance).build(); } public MFColor toFlatColor() { switch (getType()) { case FLAT: return this; case GRADIENT: return ofFlatColor(getGradientUpperColor()); case LINES: return ofFlatColor(getLineBackColor()); case TEXTURE: return ofFlatColor(getTextureTaintColor()); default: throw new IllegalStateException("Type not supported: " + getType()); } } public String toHexString() { final Color awtColor = toFlatColor().getFlatColor(); return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } public static String toHexString(final int red, final int green, final int blue) { Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red); Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green); Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue); return String.format("#%02x%02x%02x", red, green, blue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java
1
请完成以下Java代码
public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setExternalId (final @Nullable java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setIsDefault (final boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, IsDefault); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setM_Forecast_ID (final int M_Forecast_ID) { if (M_Forecast_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, M_Forecast_ID); } @Override public int getM_Forecast_ID() { return get_ValueAsInt(COLUMNNAME_M_Forecast_ID); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); }
@Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java
1
请完成以下Java代码
public ResponseEntity<PageResult<ColumnInfo>> queryColumns(@RequestParam String tableName){ List<ColumnInfo> columnInfos = generatorService.getColumns(tableName); return new ResponseEntity<>(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK); } @ApiOperation("保存字段数据") @PutMapping public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos){ generatorService.save(columnInfos); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("同步字段数据") @PostMapping(value = "sync") public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables){ for (String table : tables) { generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); } return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("生成代码") @PostMapping(value = "/{tableName}/{type}") public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){ if(!generatorEnabled && type == 0){
throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); } switch (type){ // 生成代码 case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); break; // 预览 case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); // 打包 case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); break; default: throw new BadRequestException("没有这个选项"); } return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\rest\GeneratorController.java
1
请完成以下Java代码
private static ITranslatableString getLocationString(final LocationId locationId, final CountryId fallbackCountryId) { if (locationId != null) { return TranslatableStrings.anyLanguage(getLocationString(locationId)); } if (fallbackCountryId != null) { return getCountryName(fallbackCountryId); } return TranslatableStrings.anyLanguage("?"); } private static ITranslatableString getCountryName(final CountryId countryId) { return countryId != null ? Services.get(ICountryDAO.class).getCountryNameById(countryId) : TranslatableStrings.anyLanguage("?"); } private static String getLocationString(@Nullable final LocationId locationId) { if (locationId == null) { return "?"; } final MLocation loc = MLocation.get(Env.getCtx(), locationId.getRepoId(), ITrx.TRXNAME_ThreadInherited); if (loc == null || loc.getC_Location_ID() != locationId.getRepoId()) { return "?"; } return loc.toString(); }
private static String getLocationString(final BPartnerLocationAndCaptureId bpLocationId) { if (bpLocationId == null) { return "?"; } final LocationId locationId; if (bpLocationId.getLocationCaptureId() != null) { locationId = bpLocationId.getLocationCaptureId(); } else { final I_C_BPartner_Location bpLocation = Services.get(IBPartnerDAO.class).getBPartnerLocationByIdEvenInactive(bpLocationId.getBpartnerLocationId()); locationId = bpLocation != null ? LocationId.ofRepoIdOrNull(bpLocation.getC_Location_ID()) : null; } if (locationId == null) { return "?"; } final I_C_Location location = Services.get(ILocationDAO.class).getById(locationId); return location != null ? location.toString() : locationId.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\TaxNotFoundException.java
1
请完成以下Java代码
protected void validateValue(Object value) { if(value != null) { if(values != null && !values.containsKey(value)) { throw new ProcessEngineException("Invalid value for enum form property: " + value); } } } public Map<String, String> getValues() { return values; } //////////////////// deprecated //////////////////////////////////////// @Override public Object convertFormValueToModelValue(Object propertyValue) {
validateValue(propertyValue); return propertyValue; } @Override public String convertModelValueToFormValue(Object modelValue) { if(modelValue != null) { if(!(modelValue instanceof String)) { throw new ProcessEngineException("Model value should be a String"); } validateValue(modelValue); } return (String) modelValue; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\EnumFormType.java
1
请完成以下Java代码
public Optional<WarehouseId> retrieveInTransitWarehouseIdIfExists(@NonNull final OrgId adOrgId) { final IWarehouseDAO warehousesRepo = Services.get(IWarehouseDAO.class); return warehousesRepo.getInTransitWarehouseIdIfExists(adOrgId); } public Optional<BPartnerId> retrieveOrgBPartnerId(final OrgId orgId) { final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class); final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(orgId.getRepoId()); return orgBPartner != null ? BPartnerId.optionalOfRepoId(orgBPartner.getC_BPartner_ID()) : Optional.empty(); } public BPartnerLocationId retrieveOrgBPartnerLocationId(@NonNull final OrgId orgId) { final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class); return bpartnerOrgBL.retrieveOrgBPLocationId(orgId); } /** * @param productPlanningData may be {@code null} as of gh #1635 * @param networkLine may also be {@code null} as of gh #1635 */ public int calculateDurationDays( @Nullable final ProductPlanning productPlanningData, @Nullable final DistributionNetworkLine networkLine) { // // Leadtime final int leadtimeDays; if (productPlanningData != null) { leadtimeDays = productPlanningData.getLeadTimeDays(); Check.assume(leadtimeDays >= 0, "leadtimeDays >= 0"); } else { leadtimeDays = 0; } // // Transfer time final int transferTimeFromNetworkLine; if (networkLine != null) { transferTimeFromNetworkLine = (int)networkLine.getTransferDuration().toDays(); } else
{ transferTimeFromNetworkLine = 0; } final int transferTime; if (transferTimeFromNetworkLine > 0) { transferTime = transferTimeFromNetworkLine; } else if (productPlanningData != null) { transferTime = productPlanningData.getTransferTimeDays(); Check.assume(transferTime >= 0, "transferTime >= 0"); } else { transferTime = 0; } return leadtimeDays + transferTime; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ddorder\DDOrderUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class ComponentIssueCreateRequest { @NonNull I_PP_Order_BOMLine orderBOMLine; @NonNull ProductId productId; @NonNull LocatorId locatorId; @NonNull AttributeSetInstanceId attributeSetInstanceId; @NonNull ZonedDateTime movementDate; @NonNull Quantity qtyIssue; @NonNull Quantity qtyScrap; @NonNull Quantity qtyReject; int pickingCandidateId; @Builder private ComponentIssueCreateRequest( @NonNull final I_PP_Order_BOMLine orderBOMLine, @Nullable ProductId productId, @NonNull final LocatorId locatorId, @Nullable final AttributeSetInstanceId attributeSetInstanceId, @Nullable final ZonedDateTime movementDate, @NonNull final Quantity qtyIssue,
@Nullable final Quantity qtyScrap, @Nullable final Quantity qtyReject, final int pickingCandidateId) { this.orderBOMLine = orderBOMLine; this.productId = productId != null ? productId : ProductId.ofRepoId(orderBOMLine.getM_Product_ID()); this.locatorId = locatorId; this.attributeSetInstanceId = attributeSetInstanceId != null ? attributeSetInstanceId : AttributeSetInstanceId.NONE; this.movementDate = movementDate != null ? movementDate : SystemTime.asZonedDateTime(); this.qtyIssue = qtyIssue; this.qtyScrap = qtyScrap != null ? qtyScrap : qtyIssue.toZero(); this.qtyReject = qtyReject != null ? qtyReject : qtyIssue.toZero(); this.pickingCandidateId = pickingCandidateId > 0 ? pickingCandidateId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\ComponentIssueCreateRequest.java
2
请完成以下Java代码
public final class ColorConverter extends LogEventPatternConverter { private static final Map<String, AnsiElement> ELEMENTS; static { Map<String, AnsiElement> ansiElements = new HashMap<>(); Arrays.stream(AnsiColor.values()) .filter((color) -> color != AnsiColor.DEFAULT) .forEach((color) -> ansiElements.put(color.name().toLowerCase(Locale.ROOT), color)); ansiElements.put("faint", AnsiStyle.FAINT); ELEMENTS = Collections.unmodifiableMap(ansiElements); } private static final Map<Integer, AnsiElement> LEVELS; static { Map<Integer, AnsiElement> ansiLevels = new HashMap<>(); ansiLevels.put(Level.FATAL.intLevel(), AnsiColor.RED); ansiLevels.put(Level.ERROR.intLevel(), AnsiColor.RED); ansiLevels.put(Level.WARN.intLevel(), AnsiColor.YELLOW); LEVELS = Collections.unmodifiableMap(ansiLevels); } private final List<PatternFormatter> formatters; private final @Nullable AnsiElement styling; private ColorConverter(List<PatternFormatter> formatters, @Nullable AnsiElement styling) { super("style", "style"); this.formatters = formatters; this.styling = styling; } @Override public boolean handlesThrowable() { for (PatternFormatter formatter : this.formatters) { if (formatter.handlesThrowable()) { return true; } } return super.handlesThrowable(); } @Override public void format(LogEvent event, StringBuilder toAppendTo) { StringBuilder buf = new StringBuilder(); for (PatternFormatter formatter : this.formatters) { formatter.format(event, buf); } if (!buf.isEmpty()) { AnsiElement element = this.styling; if (element == null) { // Assume highlighting
element = LEVELS.get(event.getLevel().intLevel()); element = (element != null) ? element : AnsiColor.GREEN; } appendAnsiString(toAppendTo, buf.toString(), element); } } protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement element) { toAppendTo.append(AnsiOutput.toString(element, in)); } /** * Creates a new instance of the class. Required by Log4J2. * @param config the configuration * @param options the options * @return a new instance, or {@code null} if the options are invalid */ public static @Nullable ColorConverter newInstance(@Nullable Configuration config, @Nullable String[] options) { if (options.length < 1) { LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length); return null; } if (options[0] == null) { LOGGER.error("No pattern supplied on style"); return null; } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null; return new ColorConverter(formatters, element); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\ColorConverter.java
1
请在Spring Boot框架中完成以下Java代码
public DecisionRequirementsDefinitionQuery orderByDecisionRequirementsDefinitionName() { orderBy(DecisionRequirementsDefinitionQueryProperty.DECISION_REQUIREMENTS_DEFINITION_NAME); return this; } public DecisionRequirementsDefinitionQuery orderByDeploymentId() { orderBy(DecisionRequirementsDefinitionQueryProperty.DEPLOYMENT_ID); return this; } public DecisionRequirementsDefinitionQuery orderByTenantId() { return orderBy(DecisionRequirementsDefinitionQueryProperty.TENANT_ID); } //results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { if (commandContext.getProcessEngineConfiguration().isDmnEnabled()) { checkQueryOk(); return commandContext .getDecisionRequirementsDefinitionManager() .findDecisionRequirementsDefinitionCountByQueryCriteria(this); } return 0; } @Override public List<DecisionRequirementsDefinition> executeList(CommandContext commandContext, Page page) { if (commandContext.getProcessEngineConfiguration().isDmnEnabled()) { checkQueryOk(); return commandContext .getDecisionRequirementsDefinitionManager() .findDecisionRequirementsDefinitionsByQueryCriteria(this, page); } return Collections.emptyList(); } @Override public void checkQueryOk() { super.checkQueryOk(); // latest() makes only sense when used with key() or keyLike() if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){ throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)"); } } // getters //////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; }
public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public Integer getVersion() { return version; } public boolean isLatest() { return latest; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionQueryImpl.java
2
请完成以下Java代码
public Area getEllipseAreaBounds() { Ellipse2D.Double coll = new Ellipse2D.Double(x, y, width, height); return new Area(coll); } public Ellipse2D getCircleBounds() { return new Ellipse2D.Double(x, y, 200, 200); } public Area getPolygonBounds() { for (int i = 0; i < xOffsets.length; i++) { this.xPoints[i] = x + xOffsets[i]; this.yPoints[i] = y + yOffsets[i]; } Polygon p = new Polygon(xPoints, yPoints, xOffsets.length); return new Area(p); } public boolean collidesWith(GameObject other) {
int top = Math.max(y, other.y); int bottom = Math.min(y + height, other.y + other.height); int left = Math.max(x, other.x); int right = Math.min(x + width, other.x + other.height); if (right <= left || bottom <= top) return false; for (int i = top; i < bottom; i++) { for (int j = left; j < right; j++) { int pixel1 = image.getRGB(j - x, i - y); int pixel2 = other.image.getRGB(j - other.x, i - other.y); if (((pixel1 >> 24) & 0xff) > 0 && ((pixel2 >> 24) & 0xff) > 0) { return true; } } } return false; } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imagecollision\GameObject.java
1
请在Spring Boot框架中完成以下Java代码
public R submit(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.saveOrUpdate(topMenu)); } /** * 删除 顶部菜单表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(topMenuService.deleteLogic(Func.toLongList(ids))); }
/** * 设置顶部菜单 */ @PostMapping("/grant") @ApiOperationSupport(order = 8) @Operation(summary = "顶部菜单配置", description = "传入topMenuId集合以及menuId集合") public R grant(@RequestBody GrantVO grantVO) { CacheUtil.clear(SYS_CACHE); CacheUtil.clear(MENU_CACHE); CacheUtil.clear(MENU_CACHE); boolean temp = topMenuService.grant(grantVO.getTopMenuIds(), grantVO.getMenuIds()); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TopMenuController.java
2
请完成以下Spring Boot application配置
#spring settings spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true #logging settings logging.level.org.springframework.web=INFO logging.file=${user.home}/logs/csp/sentinel-dashboard.log logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n #logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n #auth settings auth.filter.exclude-urls=/,/auth/login,/auth/logout,/registry/machine,/version auth.filter.exclude-url-suffixes=htm,html,js,css,map,ico,ttf,woff,png #
If auth.enabled=false, Sentinel console disable login auth.username=sentinel auth.password=sentinel # Inject the dashboard version. It's required to enable # filtering in pom.xml for this resource file. sentinel.dashboard.version=${project.version}
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\resources\application.properties
2
请完成以下Java代码
public boolean isGenerated () { Object oo = get_Value(COLUMNNAME_IsGenerated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请完成以下Java代码
public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/" + currentModulesPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录"); return false; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
repos\spring-boot-quick-master\quick-mybatis-druid\src\main\java\com\quick\druid\utils\CodeGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsOperatorLogServiceImpl implements PmsOperatorLogService { @Autowired private PmsOperatorLogDao pmsOperatorLogDao; /** * 创建pmsOperator */ public void saveData(PmsOperatorLog pmsOperatorLog) { pmsOperatorLogDao.insert(pmsOperatorLog); } /** * 修改pmsOperator */ public void updateData(PmsOperatorLog pmsOperatorLog) { pmsOperatorLogDao.update(pmsOperatorLog); } /** * 根据id获取数据pmsOperator * * @param id * @return */ public PmsOperatorLog getDataById(Long id) { return pmsOperatorLogDao.getById(id);
} /** * 分页查询pmsOperator * * @param pageParam * @param ActivityVo * PmsOperator * @return */ public PageBean listPage(PageParam pageParam, PmsOperatorLog pmsOperatorLog) { Map<String, Object> paramMap = new HashMap<String, Object>(); return pmsOperatorLogDao.listPage(pageParam, paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorLogServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class SpelConditional { @Value("#{false ? 'There was true value' : 'Something went wrong. There was false value'}") private String ternary; @Value("#{someCar.model != null ? someCar.model : 'Unknown model'}") private String ternary2; @Value("#{someCar.model?:'Unknown model'}") private String elvis; public String getTernary() { return ternary; } public void setTernary(String ternary) { this.ternary = ternary; } public String getTernary2() { return ternary2; } public void setTernary2(String ternary2) { this.ternary2 = ternary2;
} public String getElvis() { return elvis; } public void setElvis(String elvis) { this.elvis = elvis; } @Override public String toString() { return "SpelConditional{" + "ternary='" + ternary + '\'' + ", ternary2='" + ternary2 + '\'' + ", elvis='" + elvis + '\'' + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelConditional.java
2
请完成以下Java代码
public void setAllowEmptyExpiryClaim(boolean allowEmptyExpiryClaim) { this.allowEmptyExpiryClaim = allowEmptyExpiryClaim; } /** * Whether to allow the {@code nbf} header to be empty. The default value is * {@code true} * * @since 7.0 */ public void setAllowEmptyNotBeforeClaim(boolean allowEmptyNotBeforeClaim) { this.allowEmptyNotBeforeClaim = allowEmptyNotBeforeClaim; } @Override public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "jwt cannot be null"); Instant expiry = jwt.getExpiresAt(); if (!this.allowEmptyExpiryClaim && ObjectUtils.isEmpty(expiry)) { return createOAuth2Error("exp is required"); } if (expiry != null) { if (Instant.now(this.clock).minus(this.clockSkew).isAfter(expiry)) { return createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt())); } } Instant notBefore = jwt.getNotBefore(); if (!this.allowEmptyNotBeforeClaim && ObjectUtils.isEmpty(notBefore)) { return createOAuth2Error("nbf is required"); } if (notBefore != null) { if (Instant.now(this.clock).plus(this.clockSkew).isBefore(notBefore)) { return createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore()));
} } return OAuth2TokenValidatorResult.success(); } private OAuth2TokenValidatorResult createOAuth2Error(String reason) { this.logger.debug(reason); return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, reason, "https://tools.ietf.org/html/rfc6750#section-3.1")); } /** * Use this {@link Clock} with {@link Instant#now()} for assessing timestamp validity * @param clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtTimestampValidator.java
1
请完成以下Java代码
public final ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!hasChangedRows()) { return ProcessPreconditionsResolution.rejectWithInternalReason("nothing to save"); } final ProductsProposalView view = getView(); if (!view.getSinglePriceListVersionId().isPresent()) { return ProcessPreconditionsResolution.rejectWithInternalReason("no base price list version"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { streamChangedRows() .forEach(this::save); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); } private boolean hasChangedRows() { return streamChangedRows() .findAny() .isPresent(); } private Stream<ProductsProposalRow> streamChangedRows() { return getSelectedRows() .stream() .filter(ProductsProposalRow::isChanged); } private void save(final ProductsProposalRow row) { if (!row.isChanged()) { return; }
final BigDecimal userEnteredPriceValue = row.getPrice().getUserEnteredPriceValue(); final ProductPriceId productPriceId; // // Update existing product price if (row.getProductPriceId() != null) { productPriceId = row.getProductPriceId(); pricesListsRepo.updateProductPrice(UpdateProductPriceRequest.builder() .productPriceId(productPriceId) .priceStd(userEnteredPriceValue) .build()); } // // Save a new product price which was copied from some other price list version else if (row.getCopiedFromProductPriceId() != null) { productPriceId = pricesListsRepo.copyProductPrice(CopyProductPriceRequest.builder() .copyFromProductPriceId(row.getCopiedFromProductPriceId()) .copyToPriceListVersionId(getPriceListVersionId()) .priceStd(userEnteredPriceValue) .build()); } else { throw new AdempiereException("Cannot save row: " + row); } // // Refresh row getView().patchViewRow(row.getId(), RowSaved.builder() .productPriceId(productPriceId) .price(row.getPrice().withPriceListPriceValue(userEnteredPriceValue)) .build()); } private PriceListVersionId getPriceListVersionId() { return getView() .getSinglePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_PriceList_Version_ID@")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.java
1
请完成以下Java代码
public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } public I_AD_Window getPO_Window() throws RuntimeException { return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name) .getPO(getPO_Window_ID(), get_TrxName()); } /** Set PO Window. @param PO_Window_ID Purchase Order Window */ public void setPO_Window_ID (int PO_Window_ID) { if (PO_Window_ID < 1) set_Value (COLUMNNAME_PO_Window_ID, null); else set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID)); } /** Get PO Window. @return Purchase Order Window */ public int getPO_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Query. @param Query SQL */ public void setQuery (String Query) { set_Value (COLUMNNAME_Query, Query); } /** Get Query. @return SQL */ public String getQuery () { return (String)get_Value(COLUMNNAME_Query); } /** Set Search Type. @param SearchType Which kind of search is used (Query or Table) */ public void setSearchType (String SearchType) { set_Value (COLUMNNAME_SearchType, SearchType); } /** Get Search Type. @return Which kind of search is used (Query or Table) */ public String getSearchType () { return (String)get_Value(COLUMNNAME_SearchType); } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ public void setTransactionCode (String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ public String getTransactionCode () { return (String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
1
请完成以下Java代码
public class ZipType { @XmlValue protected String value; @XmlAttribute(name = "statecode") protected String statecode; @XmlAttribute(name = "countrycode") protected String countrycode; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the statecode property. * * @return * possible object is * {@link String } * */ public String getStatecode() { return statecode; } /** * Sets the value of the statecode property. * * @param value * allowed object is * {@link String } * */ public void setStatecode(String value) { this.statecode = value;
} /** * Gets the value of the countrycode property. * * @return * possible object is * {@link String } * */ public String getCountrycode() { if (countrycode == null) { return "CH"; } else { return countrycode; } } /** * Sets the value of the countrycode property. * * @param value * allowed object is * {@link String } * */ public void setCountrycode(String value) { this.countrycode = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ZipType.java
1
请在Spring Boot框架中完成以下Java代码
public Object getForObject(@PathVariable Long id) { String url = HOST_MALL_ADMIN + "/brand/{id}"; CommonResult commonResult = restTemplate.getForObject(url, CommonResult.class, id); return commonResult; } @ApiOperation("postForEntity jsonBody") @RequestMapping(value = "/post", method = RequestMethod.POST) @ResponseBody public Object postForEntity(@RequestBody PmsBrand brand) { String url = HOST_MALL_ADMIN + "/brand/create"; ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(url, brand, CommonResult.class); return responseEntity.getBody(); } @ApiOperation("postForEntity jsonBody") @RequestMapping(value = "/post2", method = RequestMethod.POST) @ResponseBody public Object postForObject(@RequestBody PmsBrand brand) { String url = HOST_MALL_ADMIN + "/brand/create"; CommonResult commonResult = restTemplate.postForObject(url, brand, CommonResult.class); return commonResult;
} @ApiOperation("postForEntity form") @RequestMapping(value = "/post3", method = RequestMethod.POST) @ResponseBody public Object postForEntity3(@RequestParam String name) { String url = HOST_MALL_ADMIN + "/productAttribute/category/create"; //设置头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //构造表单参数 MultiValueMap<String, String> params= new LinkedMultiValueMap<>(); params.add("name", name); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, CommonResult.class); return responseEntity.getBody(); } }
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\controller\RestTemplateDemoController.java
2
请在Spring Boot框架中完成以下Java代码
protected boolean contains(List<IdentityLinkEntity> identityLinkEntities, String identityLinkId) { return identityLinkEntities.stream().anyMatch(identityLinkEntity -> Objects.equals(identityLinkId, identityLinkEntity.getId())); } @Override public List<IdentityLinkEntity> deleteProcessDefinitionIdentityLink(String processDefinitionId, String userId, String groupId) { List<IdentityLinkEntity> identityLinks = findIdentityLinkByProcessDefinitionUserAndGroup(processDefinitionId, userId, groupId); for (IdentityLinkEntity identityLink : identityLinks) { delete(identityLink); } return identityLinks; } @Override public List<IdentityLinkEntity> deleteScopeDefinitionIdentityLink(String scopeDefinitionId, String scopeType, String userId, String groupId) { List<IdentityLinkEntity> identityLinks = findIdentityLinkByScopeDefinitionScopeTypeUserAndGroup(scopeDefinitionId, scopeType, userId, groupId); for (IdentityLinkEntity identityLink : identityLinks) { deleteIdentityLink(identityLink); } return identityLinks; } public void deleteIdentityLink(IdentityLinkEntity identityLink) { delete(identityLink); } @Override public void deleteIdentityLinksByTaskId(String taskId) { dataManager.deleteIdentityLinksByTaskId(taskId); } @Override public void deleteIdentityLinksByProcDef(String processDefId) { dataManager.deleteIdentityLinksByProcDef(processDefId); }
@Override public void deleteIdentityLinksByProcessInstanceId(String processInstanceId) { dataManager.deleteIdentityLinksByProcessInstanceId(processInstanceId); } @Override public void deleteIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { dataManager.deleteIdentityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteIdentityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { dataManager.deleteIdentityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType); } @Override public void bulkDeleteIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) { dataManager.bulkDeleteIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType); } protected IdentityLinkEventHandler getIdentityLinkEventHandler() { return serviceConfiguration.getIdentityLinkEventHandler(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\IdentityLinkEntityManagerImpl.java
2
请完成以下Java代码
public class WordCounter { private static final String LIST_NAME = "textList"; private static final String MAP_NAME = "countMap"; private Pipeline createPipeLine() { Pipeline p = Pipeline.create(); p.readFrom(Sources.<String>list(LIST_NAME)) .flatMap(word -> traverseArray(word.toLowerCase().split("\\W+"))) .filter(word -> !word.isEmpty()) .groupingKey(wholeItem()) .aggregate(counting()) .writeTo(Sinks.map(MAP_NAME)); return p; } public Long countWord(List<String> sentences, String word) { long count = 0;
JetInstance jet = Jet.newJetInstance(); try { List<String> textList = jet.getList(LIST_NAME); textList.addAll(sentences); Pipeline p = createPipeLine(); jet.newJob(p).join(); Map<String, Long> counts = jet.getMap(MAP_NAME); count = counts.get(word); } finally { Jet.shutdownAll(); } return count; } }
repos\tutorials-master\hazelcast\src\main\java\com\baeldung\hazelcast\jet\WordCounter.java
1
请完成以下Java代码
public void setTraceSqlQueries( @Parameter(description = "If Enabled, all SQL queries are logged with loglevel=WARN, or if the system property <code>" + IQueryStatisticsLogger.SYSTEM_PROPERTY_LOG_TO_SYSTEM_ERROR + "</code> is set to <code>true</code>, they will be written to std-err.") @RequestParam("enabled") final boolean enabled) { userSession.assertLoggedIn(); if (enabled) { statisticsLogger.enableSqlTracing(); } else { statisticsLogger.disableSqlTracing(); } } @GetMapping("/top/byAverageDuration") @Operation(summary = "Gets top SQL queries ordered by their average execution time (descending)") public Map<String, Object> getTopAverageDurationQueriesAsString() { userSession.assertLoggedIn(); return queriesListToMap(statisticsLogger.getTopAverageDurationQueriesAsString()); } @Operation(summary = "Gets top SQL queries ordered by their total summed executon time (descending)") @GetMapping("/top/byTotalDuration") public Map<String, Object> getTopTotalDurationQueriesAsString() { userSession.assertLoggedIn(); return queriesListToMap(statisticsLogger.getTopTotalDurationQueriesAsString()); }
@GetMapping("/top/byExecutionCount") @Operation(summary = "Gets top SQL queries ordered by their execution count (descending)") public Map<String, Object> getTopCountQueriesAsString() { userSession.assertLoggedIn(); return queriesListToMap(statisticsLogger.getTopCountQueriesAsString()); } private static Map<String, Object> queriesListToMap(final String[] list) { final HashMap<String, Object> map = new HashMap<>(); map.put("queries", ImmutableList.copyOf(list)); return map; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\debug\DebugTraceSqlQueriesRestController.java
1
请完成以下Java代码
public static JaxBContextProvider defaultJaxBContextProvider() { return new DefaultJaxBContextProvider(); } /* * Configures the DocumentBuilderFactory in a way, that it is protected against * XML External Entity Attacks. If the implementing parser does not support one or * multiple features, the failed feature is ignored. The parser might not be protected, * if the feature assignment fails. * * @see <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet">OWASP Information of XXE attacks</a> * * @param dbf The factory to configure. */ protected static void disableXxeProcessing(DocumentBuilderFactory dbf) { try { dbf.setFeature(EXTERNAL_GENERAL_ENTITIES, false); dbf.setFeature(DISALLOW_DOCTYPE_DECL, true); dbf.setFeature(LOAD_EXTERNAL_DTD, false); dbf.setFeature(EXTERNAL_PARAMETER_ENTITIES, false); } catch (ParserConfigurationException ignored) { // ignore } dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); } /* * Configures the DocumentBuilderFactory to process XML securely. * If the implementing parser does not support one or multiple features, * the failed feature is ignored. The parser might not be protected, * if the feature assignment fails. * * @param dbf The factory to configure. */ protected static void enableSecureProcessing(DocumentBuilderFactory dbf) { try { dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setAttribute(JAXP_ACCESS_EXTERNAL_SCHEMA, resolveAccessExternalSchemaProperty()); } catch (ParserConfigurationException | IllegalArgumentException ignored) {
// ignored } } /* * JAXP allows users to override the default value via system properties and * a central properties file (see https://docs.oracle.com/javase/tutorial/jaxp/properties/scope.html). * However, both are overridden by an explicit configuration in code, as we apply it. * Since we want users to customize the value, we take the system property into account. * The properties file is not supported at the moment. */ protected static String resolveAccessExternalSchemaProperty() { String systemProperty = System.getProperty(JAXP_ACCESS_EXTERNAL_SCHEMA_SYSTEM_PROPERTY); if (systemProperty != null) { return systemProperty; } else { return JAXP_ACCESS_EXTERNAL_SCHEMA_ALL; } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormat.java
1
请完成以下Java代码
public class HttpClientBasicAuthentication { private static final Logger logger = LoggerFactory.getLogger(HttpClientBasicAuthentication.class); public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException { useClientWithAuthenticator(); useClientWithHeaders(); } private static void useClientWithAuthenticator() throws URISyntaxException, IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("postman", "password".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .GET() .uri(new URI("https://postman-echo.com/basic-auth")) .build(); HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); logger.info("Status using authenticator {}", response.statusCode()); } private static void useClientWithHeaders() throws IOException, InterruptedException, URISyntaxException { HttpClient client = HttpClient.newBuilder() .build();
HttpRequest request = HttpRequest.newBuilder() .GET() .uri(new URI("https://postman-echo.com/basic-auth")) .header("Authorization", getBasicAuthenticationHeader("postman", "password")) .build(); HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); logger.info("Status using headers: {}", response.statusCode()); } private static final String getBasicAuthenticationHeader(String username, String password) { String valueToEncode = username + ":" + password; return "Basic " + Base64.getEncoder() .encodeToString(valueToEncode.getBytes()); } }
repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\httpclient\basicauthentication\HttpClientBasicAuthentication.java
1
请在Spring Boot框架中完成以下Java代码
public String getTimerJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) { Job job = getTimerJobById(jobId); String stackTrace = managementService.getTimerJobExceptionStacktrace(job.getId()); if (stackTrace == null) { throw new FlowableObjectNotFoundException("Timer job with id '" + job.getId() + "' doesn't have an exception stacktrace.", String.class); } response.setContentType("text/plain"); return stackTrace; } @ApiOperation(value = "Get the exception stacktrace for a suspended job", tags = { "Jobs" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."), @ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.") }) @GetMapping("/cmmn-management/suspended-jobs/{jobId}/exception-stacktrace") public String getSuspendedJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) { Job job = getSuspendedJobById(jobId); String stackTrace = managementService.getSuspendedJobExceptionStacktrace(job.getId()); if (stackTrace == null) { throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' doesn't have an exception stacktrace.", String.class); } response.setContentType("text/plain");
return stackTrace; } @ApiOperation(value = "Get the exception stacktrace for a deadletter job", tags = { "Jobs" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."), @ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.") }) @GetMapping("/cmmn-management/deadletter-jobs/{jobId}/exception-stacktrace") public String getDeadLetterJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) { Job job = getDeadLetterJobById(jobId); String stackTrace = managementService.getDeadLetterJobExceptionStacktrace(job.getId()); if (stackTrace == null) { throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' doesn't have an exception stacktrace.", String.class); } response.setContentType("text/plain"); return stackTrace; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobExceptionStacktraceResource.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { @Bean public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) { UserDetails admin = User.withUsername("admin") .password(passwordEncoder.encode("password")) .roles("USER", "ADMIN") .build(); UserDetails user = User.withUsername("user") .password(passwordEncoder.encode("password")) .roles("USER") .build(); return new InMemoryUserDetailsManager(admin, user); }
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/products/**")) .permitAll()) .authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/customers/**")) .hasRole("ADMIN") .anyRequest() .authenticated()) .httpBasic(Customizer.withDefaults()) .build(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-security\src\main\java\com\baeldung\antmatchers\config\SecurityConfiguration.java
2
请完成以下Java代码
public abstract class AbstractAclVoter implements AccessDecisionVoter<MethodInvocation> { @SuppressWarnings("NullAway.Init") private @Nullable Class<?> processDomainObjectClass; protected Object getDomainObjectInstance(MethodInvocation invocation) { Object[] args = invocation.getArguments(); Class<?>[] params = invocation.getMethod().getParameterTypes(); for (int i = 0; i < params.length; i++) { if (this.processDomainObjectClass.isAssignableFrom(params[i])) { return args[i]; } } throw new AuthorizationServiceException("MethodInvocation: " + invocation + " did not provide any argument of type: " + this.processDomainObjectClass); } public Class<?> getProcessDomainObjectClass() { return this.processDomainObjectClass; }
public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) { Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null"); this.processDomainObjectClass = processDomainObjectClass; } /** * This implementation supports only <code>MethodSecurityInterceptor</code>, because * it queries the presented <code>MethodInvocation</code>. * @param clazz the secure object * @return <code>true</code> if the secure object is <code>MethodInvocation</code>, * <code>false</code> otherwise */ @Override public boolean supports(Class<?> clazz) { return (MethodInvocation.class.isAssignableFrom(clazz)); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AbstractAclVoter.java
1
请完成以下Java代码
private boolean canVoidPaidInvoice(@NonNull final I_C_Invoice invoice) { final I_C_Invoice inv = InterfaceWrapperHelper.create(invoice, I_C_Invoice.class); if (hasAnyNonPaymentAllocations(inv)) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .contentADMessage(MSG_SKIPPED_INVOICE_NON_PAYMENT_ALLOC_INVOLVED) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build(); notificationBL.send(userNotificationRequest); return false; } if (commissionTriggerService.isContainsCommissionTriggers(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()))) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .contentADMessage(MSG_SKIPPED_INVOICE_DUE_TO_COMMISSION) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build(); notificationBL.send(userNotificationRequest); return false; }
return true; } @NonNull private IInvoicingParams getIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setUpdateLocationAndContactForInvoice(true); invoicingParams.setIgnoreInvoiceSchedule(false); return invoicingParams; } private boolean hasAnyNonPaymentAllocations(@NonNull final I_C_Invoice invoice) { final List<I_C_AllocationLine> availableAllocationLines = allocationDAO.retrieveAllocationLines(invoice); return availableAllocationLines.stream() .anyMatch(allocationLine -> allocationLine.getC_Payment_ID() <= 0); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\RecreateInvoiceWorkpackageProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public List<Student> read() { return service.readAll(); } @GetMapping("/{id}") public ResponseEntity<Student> read(@PathVariable("id") Long id) { Student foundStudent = service.read(id); if (foundStudent == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(foundStudent); } } @PostMapping("/") public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException { Student createdStudent = service.create(student); URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(createdStudent.getId()) .toUri(); return ResponseEntity.created(uri) .body(createdStudent); } @PutMapping("/{id}") public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable Long id) {
Student updatedStudent = service.update(id, student); if (updatedStudent == null) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(updatedStudent); } } @DeleteMapping("/{id}") public ResponseEntity<Object> deleteStudent(@PathVariable Long id) { service.delete(id); return ResponseEntity.noContent().build(); } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\students\StudentController.java
2
请完成以下Java代码
public void updateStatusIfNeededWhenCancelling(final I_C_Flatrate_Term term, final Set<OrderId> orderIds) { if (X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract.equals(term.getContractStatus()) || X_C_Flatrate_Term.CONTRACTSTATUS_Quit.equals(term.getContractStatus())) { // update order contract status to cancel final List<I_C_Order> orders = orderDAO.getByIds(orderIds, I_C_Order.class); for (final I_C_Order order : orders) { contractOrderService.setOrderContractStatusAndSave(order, I_C_Order.CONTRACTSTATUS_Cancelled); } } } public void updateStausIfNeededWhenVoiding(@NonNull final I_C_Flatrate_Term term) { final OrderId orderId = contractOrderService.getContractOrderId(term); if (orderId == null || !X_C_Flatrate_Term.CONTRACTSTATUS_Voided.equals(term.getContractStatus())) { return; } final OrderId parentOrderId = contractOrderService.retrieveLinkedFollowUpContractOrder(orderId); final ImmutableSet<OrderId> orderIds = parentOrderId == null ? ImmutableSet.of(orderId) : ImmutableSet.of(orderId, parentOrderId); final List<I_C_Order> orders = orderDAO.getByIds(orderIds, I_C_Order.class); final I_C_Order contractOrder = orders.get(0); setContractStatusForCurrentOrder(contractOrder, term); setContractStatusForParentOrderIfNeeded(orders); } private void setContractStatusForCurrentOrder(@NonNull final I_C_Order contractOrder, @NonNull final I_C_Flatrate_Term term) { // set status for the current order final List<I_C_Flatrate_Term> terms = contractsDAO.retrieveFlatrateTermsForOrderIdLatestFirst(OrderId.ofRepoId(contractOrder.getC_Order_ID())); final boolean anyActiveTerms = terms .stream() .anyMatch(currentTerm -> term.getC_Flatrate_Term_ID() != currentTerm.getC_Flatrate_Term_ID() && subscriptionBL.isActiveTerm(currentTerm)); contractOrderService.setOrderContractStatusAndSave(contractOrder, anyActiveTerms ? I_C_Order.CONTRACTSTATUS_Active : I_C_Order.CONTRACTSTATUS_Cancelled); } private void setContractStatusForParentOrderIfNeeded(final List<I_C_Order> orders)
{ if (orders.size() == 1) // means that the order does not have parent { return; } final I_C_Order contractOrder = orders.get(0); final I_C_Order parentOrder = orders.get(1); if (isActiveParentContractOrder(parentOrder, contractOrder)) { contractOrderService.setOrderContractStatusAndSave(parentOrder, I_C_Order.CONTRACTSTATUS_Active); } } private boolean isActiveParentContractOrder(@NonNull final I_C_Order parentOrder, @NonNull final I_C_Order contractOrder) { return parentOrder.getC_Order_ID() != contractOrder.getC_Order_ID() // different order from the current one && !I_C_Order.CONTRACTSTATUS_Cancelled.equals(parentOrder.getContractStatus()) // current order wasn't previously cancelled, although shall not be possible this && I_C_Order.CONTRACTSTATUS_Cancelled.equals(contractOrder.getContractStatus()); // current order was cancelled } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\UpdateContractOrderStatus.java
1
请完成以下Java代码
public void clearCachedAuthorizationInfo(PrincipalCollection principals) { super.clearCachedAuthorizationInfo(principals); clearAllCache(); } @Override public void clearCachedAuthenticationInfo(PrincipalCollection principals) { super.clearCachedAuthenticationInfo(principals); clearAllCache(); } @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); clearAllCache(); } public void clearAllCachedAuthorizationInfo() {
if (getAuthorizationCache() != null) { getAuthorizationCache().clear(); } } public void clearAllCachedAuthenticationInfo() { if (getAuthenticationCache() != null) { getAuthenticationCache().clear(); } } public void clearAllCache() { clearAllCachedAuthenticationInfo(); clearAllCachedAuthorizationInfo(); } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroRealm.java
1
请在Spring Boot框架中完成以下Java代码
private Set<String> getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); Assert.state(attributes != null, "'attributes' must not be null"); Set<String> packagesToScan = new LinkedHashSet<>(); for (String basePackage : attributes.getStringArray("basePackages")) { String[] tokenized = StringUtils.tokenizeToStringArray( this.environment.resolvePlaceholders(basePackage), ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); Collections.addAll(packagesToScan, tokenized); } for (Class<?> basePackageClass : attributes.getClassArray("basePackageClasses")) { packagesToScan.add(this.environment.resolvePlaceholders(ClassUtils.getPackageName(basePackageClass))); } if (packagesToScan.isEmpty()) { String packageName = ClassUtils.getPackageName(metadata.getClassName()); Assert.state(StringUtils.hasLength(packageName), "@EntityScan cannot be used with the default package"); return Collections.singleton(packageName); } return packagesToScan; } } static class EntityScanPackagesBeanDefinition extends RootBeanDefinition {
private final Set<String> packageNames = new LinkedHashSet<>(); EntityScanPackagesBeanDefinition(Collection<String> packageNames) { setBeanClass(EntityScanPackages.class); setRole(BeanDefinition.ROLE_INFRASTRUCTURE); addPackageNames(packageNames); } private void addPackageNames(Collection<String> additionalPackageNames) { this.packageNames.addAll(additionalPackageNames); getConstructorArgumentValues().addIndexedArgumentValue(0, StringUtils.toStringArray(this.packageNames)); } } }
repos\spring-boot-4.0.1\module\spring-boot-persistence\src\main\java\org\springframework\boot\persistence\autoconfigure\EntityScanPackages.java
2
请完成以下Java代码
public static boolean hasIgnoreCounterVariable(PlanItemInstanceEntity repeatingPlanItemInstanceEntity) { return repeatingPlanItemInstanceEntity.getPlanItem().getItemControl().getRepetitionRule().isIgnoreRepetitionCounterVariable(); } public static String getCounterVariable(PlanItemInstanceEntity repeatingPlanItemInstanceEntity) { String repetitionCounterVariableName = repeatingPlanItemInstanceEntity.getPlanItem().getItemControl().getRepetitionRule().getRepetitionCounterVariableName(); return repetitionCounterVariableName; } protected static PlanItemInstanceEntity createPlanItemInstanceDuplicateForCollectionRepetition(RepetitionRule repetitionRule, PlanItemInstanceEntity planItemInstanceEntity, String entryCriterionId, Object item, int index, CommandContext commandContext) { // check, if we need to set local variables as the item or item index Map<String, Object> localVariables = new HashMap<>(2); if (repetitionRule.hasElementVariable()) { localVariables.put(repetitionRule.getElementVariableName(), item); } if (repetitionRule.hasElementIndexVariable()) { localVariables.put(repetitionRule.getElementIndexVariableName(), index);
} PlanItemInstanceEntity childPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, localVariables, false, false); // record the plan item being created based on the collection, so it gets synchronized to the history as well CommandContextUtil.getAgenda(commandContext).planCreateRepeatedPlanItemInstanceOperation(childPlanItemInstanceEntity); // The repetition counter is 1 based if (repetitionRule.getAggregations() != null || !repetitionRule.isIgnoreRepetitionCounterVariable()) { childPlanItemInstanceEntity.setVariableLocal(PlanItemInstanceUtil.getCounterVariable(childPlanItemInstanceEntity), index + 1); } // createPlanItemInstance operations will also sync planItemInstance history CommandContextUtil.getAgenda(commandContext).planActivatePlanItemInstanceOperation(childPlanItemInstanceEntity, entryCriterionId); return childPlanItemInstanceEntity; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\PlanItemInstanceUtil.java
1
请完成以下Java代码
private static Object normalizeSingleArgumentBeforeFormat_ReferenceListAwareEnum( @NonNull final ReferenceListAwareEnum referenceListAwareEnum, final String adLanguage) { final int adReferenceId = ReferenceListAwareEnums.getAD_Reference_ID(referenceListAwareEnum); if (adReferenceId > 0) { final ADReferenceService adReferenceService = ADReferenceService.get(); final ADRefListItem adRefListItem = adReferenceService.retrieveListItemOrNull(adReferenceId, referenceListAwareEnum.getCode()); if (adRefListItem != null) { return adRefListItem.getName().translate(adLanguage); } } // Fallback return referenceListAwareEnum.toString(); } private static String normalizeSingleArgumentBeforeFormat_Iterable( @NonNull final Iterable<Object> iterable, final String adLanguage) { final StringBuilder result = new StringBuilder(); for (final Object item : iterable) { String itemNormStr; try { final Object itemNormObj = normalizeSingleArgumentBeforeFormat(item, adLanguage); itemNormStr = itemNormObj != null ? itemNormObj.toString() : "-"; }
catch (Exception ex) { s_log.warn("Failed normalizing argument `{}`. Using toString().", item, ex); itemNormStr = item.toString(); } if (!(result.length() == 0)) { result.append(", "); } result.append(itemNormStr); } return result.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessageFormatter.java
1
请在Spring Boot框架中完成以下Java代码
class DefaultServerHttpMessageConvertersCustomizer implements ServerHttpMessageConvertersCustomizer { private final @Nullable HttpMessageConverters legacyConverters; private final Collection<HttpMessageConverter<?>> converters; DefaultServerHttpMessageConvertersCustomizer(@Nullable HttpMessageConverters legacyConverters, Collection<HttpMessageConverter<?>> converters) { this.legacyConverters = legacyConverters; this.converters = converters; } @Override public void customize(ServerBuilder builder) { if (this.legacyConverters != null) { this.legacyConverters.forEach(builder::addCustomConverter);
} else { builder.registerDefaults(); this.converters.forEach((converter) -> { if (converter instanceof KotlinSerializationJsonHttpMessageConverter) { builder.withKotlinSerializationJsonConverter(converter); } else { builder.addCustomConverter(converter); } }); } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\DefaultServerHttpMessageConvertersCustomizer.java
2
请完成以下Java代码
public void sendDashboardItemsOrderChangedEvent( @NonNull final UserDashboard dashboard, @NonNull final DashboardWidgetType widgetType) { sendEvents( getWebsocketTopicNamesByDashboardId(dashboard.getId()), JSONDashboardChangedEventsList.of( JSONDashboardOrderChangedEvent.of( dashboard.getId(), widgetType, dashboard.getItemIds(widgetType)))); } public void sendDashboardItemChangedEvent( @NonNull final UserDashboard dashboard, @NonNull final UserDashboardItemChangeResult changeResult) { sendEvents( getWebsocketTopicNamesByDashboardId(dashboard.getId()), toJSONDashboardChangedEventsList(changeResult)); } private static JSONDashboardChangedEventsList toJSONDashboardChangedEventsList(final @NonNull UserDashboardItemChangeResult changeResult) { final JSONDashboardChangedEventsList.JSONDashboardChangedEventsListBuilder eventBuilder = JSONDashboardChangedEventsList.builder() .event(JSONDashboardItemChangedEvent.of( changeResult.getDashboardId(), changeResult.getDashboardWidgetType(), changeResult.getItemId())); if (changeResult.isPositionChanged()) { eventBuilder.event(JSONDashboardOrderChangedEvent.of( changeResult.getDashboardId(), changeResult.getDashboardWidgetType(), changeResult.getDashboardOrderedItemIds())); } return eventBuilder.build(); } private void sendEvents( @NonNull final Set<WebsocketTopicName> websocketEndpoints, @NonNull final JSONDashboardChangedEventsList events)
{ if (websocketEndpoints.isEmpty() || events.isEmpty()) { return; } for (final WebsocketTopicName websocketEndpoint : websocketEndpoints) { websocketSender.convertAndSend(websocketEndpoint, events); logger.trace("Notified WS {}: {}", websocketEndpoint, events); } } private ImmutableSet<WebsocketTopicName> getWebsocketTopicNamesByDashboardId(@NonNull final UserDashboardId dashboardId) { return websocketProducersRegistry.streamActiveProducersOfType(UserDashboardWebsocketProducer.class) .filter(producer -> producer.isMatchingDashboardId(dashboardId)) .map(UserDashboardWebsocketProducer::getWebsocketTopicName) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketSender.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isClientAndOrgMatching(@NonNull final ClientAndOrgId clientAndOrgId) { for (ClientAndOrgId currentClientAndOrgId = clientAndOrgId; currentClientAndOrgId != null; currentClientAndOrgId = getFallbackClientAndOrgId(currentClientAndOrgId)) { if (entryValues.containsKey(currentClientAndOrgId)) { return true; } } return false; } @Nullable private ClientAndOrgId getFallbackClientAndOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { if (!clientAndOrgId.getOrgId().isAny()) { return clientAndOrgId.withAnyOrgId(); } else if (!clientAndOrgId.getClientId().isSystem()) { return clientAndOrgId.withSystemClientId(); } else { return null; } } public Optional<String> getValueAsString(@NonNull final ClientAndOrgId clientAndOrgId) { for (ClientAndOrgId currentClientAndOrgId = clientAndOrgId; currentClientAndOrgId != null; currentClientAndOrgId = getFallbackClientAndOrgId(currentClientAndOrgId)) {
final SysConfigEntryValue entryValue = entryValues.get(currentClientAndOrgId); if (entryValue != null) { return Optional.of(entryValue.getValue()); } } return Optional.empty(); } // // // ------------------------------- // // public static class SysConfigEntryBuilder { public String getName() { return name; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigEntry.java
2
请完成以下Java代码
private void removeDuplicateTransactions(final List<IHUTransactionAttribute> transactions) { if (transactions.isEmpty()) { return; } // // Check our transactions history and if we find a transaction which is shadowed by our newly created transaction // then just remove it from list and keep only ours final int size = transactions.size(); final Set<ArrayKey> seenTrxs = new HashSet<>(size); final ListIterator<IHUTransactionAttribute> it = transactions.listIterator(size); while (it.hasPrevious()) { final IHUTransactionAttribute trx = it.previous(); final ArrayKey trxKey = mkKey(trx); final boolean uniqueTransaction = seenTrxs.add(trxKey); if (!uniqueTransaction) { // Already seen transaction => remove it it.remove(); continue; } } } /** * Used by {@link #mkKey(IHUTransactionAttribute)} in case we want to make sure a given key is unique. * * In this case it will use and increment this value. */ private int uniqueKeyIndex = 1; /** * Creates transaction's unique key. * * @param trx * @return */ private ArrayKey mkKey(final IHUTransactionAttribute trx) { final AttributeId attributeId = trx.getAttributeId();
final HUTransactionAttributeOperation operation = trx.getOperation(); final Object referencedObject = trx.getReferencedObject(); final String referencedObjectTableName; final int referencedObjectId; final int uniqueDiscriminant; if (referencedObject == null) { referencedObjectTableName = null; referencedObjectId = -1; uniqueDiscriminant = uniqueKeyIndex++; // we want to have a unique discriminant } else { referencedObjectTableName = InterfaceWrapperHelper.getModelTableName(referencedObject); referencedObjectId = InterfaceWrapperHelper.getId(referencedObject); uniqueDiscriminant = 0; // nop, we don't want to have a unique discriminant } return Util.mkKey(uniqueDiscriminant, attributeId, operation, referencedObjectTableName, referencedObjectId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTrxAttributesCollector.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!rowsHaveSingleProductId()) { final ITranslatableString msg = msgBL.getTranslatableMsgText(MSG); return ProcessPreconditionsResolution.reject(msg); } return ProcessPreconditionsResolution.accept(); } private boolean rowsHaveSingleProductId() { // getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); doesn't work from checkPreconditionsApplicable final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds()); final IQueryFilter<I_M_DiscountSchemaBreak> selectionQueryFilter = viewSqlWhereClause.toQueryFilter(); return pricingConditionsRepo.isSingleProductId(selectionQueryFilter); } @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final String parameterName = parameter.getColumnName(); if (PARAM_M_Product_ID.equals(parameterName)) { final IQueryFilter<I_M_DiscountSchemaBreak> selectionQueryFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final ProductId uniqueProductIdForSelection = pricingConditionsRepo.retrieveUniqueProductIdForSelectionOrNull(selectionQueryFilter); if (uniqueProductIdForSelection == null) { // should not happen because of the preconditions above return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } return uniqueProductIdForSelection.getRepoId(); } else
{ return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds) { final String breaksTableName = I_M_DiscountSchemaBreak.Table_Name; return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(breaksTableName)); } @Override protected String doIt() { final IQueryFilter<I_M_DiscountSchemaBreak> queryFilter = getProcessInfo().getQueryFilterOrElse(null); if (queryFilter == null) { throw new AdempiereException("@NoSelection@"); } final boolean allowCopyToSameSchema = true; final CopyDiscountSchemaBreaksRequest request = CopyDiscountSchemaBreaksRequest.builder() .filter(queryFilter) .pricingConditionsId(PricingConditionsId.ofRepoId(p_PricingConditionsId)) .productId(ProductId.ofRepoId(p_ProductId)) .allowCopyToSameSchema(allowCopyToSameSchema) .direction(Direction.SourceTarget) .build(); pricingConditionsRepo.copyDiscountSchemaBreaksWithProductId(request); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pricing\process\M_DiscountSchemaBreak_CopyToOtherSchema_Product.java
1
请完成以下Java代码
public void createUpdateConsent( @NonNull final ContactPerson contactPerson) { final ContactPersonId contactPersonId = Check.assumeNotNull(contactPerson.getContactPersonId(), "contact is saved: {}", contactPerson); final I_MKTG_Consent consentExistingRecord = getConsentRecord(contactPersonId); final I_MKTG_Consent consent = consentExistingRecord != null ? consentExistingRecord : newInstance(I_MKTG_Consent.class); consent.setAD_User_ID(UserId.toRepoIdOr(contactPerson.getUserId(), -1)); consent.setC_BPartner_ID(BPartnerId.toRepoIdOr(contactPerson.getBPartnerId(), 0)); consent.setConsentDeclaredOn(SystemTime.asTimestamp()); consent.setMKTG_ContactPerson_ID(contactPersonId.getRepoId()); saveRecord(consent); } public void revokeConsent( @NonNull final ContactPerson contactPerson) { final ContactPersonId contactPersonId = Check.assumeNotNull(contactPerson.getContactPersonId(), "contact is saved: {}", contactPerson); final I_MKTG_Consent consent = getConsentRecord(contactPersonId); if (consent != null) { consent.setConsentRevokedOn(SystemTime.asTimestamp()); saveRecord(consent); } } private I_MKTG_Consent getConsentRecord(@NonNull final ContactPersonId contactPersonId) { return queryBL.createQueryBuilder(I_MKTG_Consent.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_Consent.COLUMNNAME_ConsentRevokedOn, null) .addEqualsFilter(I_MKTG_Consent.COLUMNNAME_MKTG_ContactPerson_ID, contactPersonId.getRepoId()) .orderByDescending(I_MKTG_Consent.COLUMNNAME_ConsentDeclaredOn) .create() .first(I_MKTG_Consent.class); } public void updateBPartnerLocation(final ContactPerson contactPerson, BPartnerLocationId bpLocationId) { contactPerson.toBuilder()
.bpLocationId(bpLocationId) .build(); save(contactPerson); } public Set<ContactPerson> getByBPartnerLocationId(@NonNull final BPartnerLocationId bpLocationId) { return queryBL .createQueryBuilder(I_MKTG_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_ContactPerson.COLUMN_C_BPartner_Location_ID, bpLocationId.getRepoId()) .create() .stream() .map(ContactPersonRepository::toContactPerson) .collect(ImmutableSet.toImmutableSet()); } public Set<ContactPerson> getByUserId(@NonNull final UserId userId) { return queryBL .createQueryBuilder(I_MKTG_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_ContactPerson.COLUMN_AD_User_ID, userId.getRepoId()) .create() .stream() .map(ContactPersonRepository::toContactPerson) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\ContactPersonRepository.java
1
请完成以下Java代码
public Optional<I_C_BPartner_Location> getFirstBPLocationMatching(@NonNull final BPartnerLocationMatchingKey matchingKey) { return getFirstBPLocationMatching(bpLocation -> isBPartnerLocationMatching(bpLocation, matchingKey)); } private boolean isBPartnerLocationMatching(@NonNull final I_C_BPartner_Location bpLocation, @NonNull final BPartnerLocationMatchingKey matchingKey) { final BPartnerLocationMatchingKey bpLocationKey = BPartnerLocationMatchingKey.of(bpLocation.getC_Location()); return bpLocationKey.equals(matchingKey); } public Optional<I_C_BPartner_Location> getFirstBPLocationMatching(@NonNull final Predicate<I_C_BPartner_Location> filter) { return getOrLoadBPLocations() .stream() .filter(filter) .findFirst(); } private ArrayList<I_C_BPartner_Location> getOrLoadBPLocations() { if (bpLocations == null) { if (record.getC_BPartner_ID() > 0) { bpLocations = new ArrayList<>(bpartnersRepo.retrieveBPartnerLocations(record)); } else { bpLocations = new ArrayList<>(); } } return bpLocations; } public void addAndSaveLocation(final I_C_BPartner_Location bpartnerLocation) { bpartnersRepo.save(bpartnerLocation); final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerLocation.getC_BPartner_ID(), bpartnerLocation.getC_BPartner_Location_ID()); if (!getBPLocationById(bpartnerLocationId).isPresent()) { getOrLoadBPLocations().add(bpartnerLocation); } } public Optional<I_AD_User> getContactById(final BPartnerContactId contactId) { return getOrLoadContacts() .stream() .filter(contact -> contact.getAD_User_ID() == contactId.getRepoId()) .findFirst(); } private ArrayList<I_AD_User> getOrLoadContacts() {
if (contacts == null) { if (record.getC_BPartner_ID() > 0) { contacts = new ArrayList<>(bpartnersRepo.retrieveContacts(record)); } else { contacts = new ArrayList<>(); } } return contacts; } public BPartnerContactId addAndSaveContact(final I_AD_User contact) { bpartnersRepo.save(contact); final BPartnerContactId contactId = BPartnerContactId.ofRepoId(contact.getC_BPartner_ID(), contact.getAD_User_ID()); if (!getContactById(contactId).isPresent()) { getOrLoadContacts().add(contact); } return contactId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnersCache.java
1
请完成以下Java代码
public class StaticNameResolverProvider extends NameResolverProvider { /** * The constant containing the scheme that will be used by this factory. */ public static final String STATIC_SCHEME = "static"; private static final Pattern PATTERN_COMMA = Pattern.compile(","); @Nullable @Override public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) { if (STATIC_SCHEME.equals(targetUri.getScheme())) { return of(targetUri.getAuthority(), args.getDefaultPort()); } return null; } /** * Creates a new {@link NameResolver} for the given authority and attributes. * * @param targetAuthority The authority to connect to. * @param defaultPort The default port to use, if none is specified. * @return The newly created name resolver for the given target. */ private NameResolver of(final String targetAuthority, int defaultPort) { requireNonNull(targetAuthority, "targetAuthority"); // Determine target ips final String[] hosts = PATTERN_COMMA.split(targetAuthority); final List<EquivalentAddressGroup> targets = new ArrayList<>(hosts.length); for (final String host : hosts) { final URI uri = URI.create("//" + host); int port = uri.getPort(); if (port == -1) { port = defaultPort; } targets.add(new EquivalentAddressGroup(new InetSocketAddress(uri.getHost(), port))); } if (targets.isEmpty()) { throw new IllegalArgumentException("Must have at least one target, but was: " + targetAuthority); } return new StaticNameResolver(targetAuthority, targets); }
@Override public String getDefaultScheme() { return STATIC_SCHEME; } @Override protected boolean isAvailable() { return true; } @Override protected int priority() { return 4; // Less important than DNS } @Override public String toString() { return "StaticNameResolverProvider [scheme=" + getDefaultScheme() + "]"; } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\nameresolver\StaticNameResolverProvider.java
1
请完成以下Java代码
public class SessionEventHttpSessionListenerAdapter implements ApplicationListener<AbstractSessionEvent>, ServletContextAware { private final List<HttpSessionListener> listeners; private ServletContext context; public SessionEventHttpSessionListenerAdapter(List<HttpSessionListener> listeners) { super(); this.listeners = listeners; } /* * @see org.springframework.context.ApplicationListener#onApplicationEvent(org. * springframework.context.ApplicationEvent) */ @Override public void onApplicationEvent(AbstractSessionEvent event) { if (this.listeners.isEmpty()) { return; } HttpSessionEvent httpSessionEvent = createHttpSessionEvent(event); for (HttpSessionListener listener : this.listeners) { if (event instanceof SessionDestroyedEvent) { listener.sessionDestroyed(httpSessionEvent); } else if (event instanceof SessionCreatedEvent) { listener.sessionCreated(httpSessionEvent); } } }
private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) { Session session = event.getSession(); HttpSession httpSession = new HttpSessionAdapter<>(session, this.context); return new HttpSessionEvent(httpSession); } /* * @see org.springframework.web.context.ServletContextAware#setServletContext(jakarta. * servlet.ServletContext) */ @Override public void setServletContext(ServletContext servletContext) { this.context = servletContext; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionEventHttpSessionListenerAdapter.java
1
请完成以下Java代码
final class DurationToStringConverter implements GenericConverter { @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(Duration.class, String.class)); } @Override public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((Duration) source, getDurationStyle(sourceType), getDurationUnit(sourceType)); } private @Nullable ChronoUnit getDurationUnit(TypeDescriptor sourceType) {
DurationUnit annotation = sourceType.getAnnotation(DurationUnit.class); return (annotation != null) ? annotation.value() : null; } private @Nullable DurationStyle getDurationStyle(TypeDescriptor sourceType) { DurationFormat annotation = sourceType.getAnnotation(DurationFormat.class); return (annotation != null) ? annotation.value() : null; } private String convert(Duration source, @Nullable DurationStyle style, @Nullable ChronoUnit unit) { style = (style != null) ? style : DurationStyle.ISO8601; return style.print(source, unit); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DurationToStringConverter.java
1
请完成以下Java代码
public void write(OutputStream out) throws IOException, WebApplicationException { try { byte[] buff = new byte[16 * 1000]; int read = 0; while((read = filteredStream.read(buff)) > 0) { out.write(buff, 0, read); } } finally { IoUtil.closeSilently(filteredStream); IoUtil.closeSilently(out); } } }, contentType).build(); } } // no asset found throw new RestException(Status.NOT_FOUND, "It was not able to load the following file '" + file + "'."); } /** * @param file * @param assetStream */ protected InputStream applyResourceOverrides(String file, InputStream assetStream) { // use a copy of the list cause it could be modified during iteration List<PluginResourceOverride> resourceOverrides = new ArrayList<PluginResourceOverride>(runtimeDelegate.getResourceOverrides()); for (PluginResourceOverride pluginResourceOverride : resourceOverrides) { assetStream = pluginResourceOverride.filterResource(assetStream, new RequestInfo(headers, servletContext, uriInfo)); } return assetStream; } protected String getContentType(String file) { if (file.endsWith(".js")) { return MIME_TYPE_TEXT_JAVASCRIPT; } else if (file.endsWith(".html")) { return MIME_TYPE_TEXT_HTML; } else if (file.endsWith(".css")) { return MIME_TYPE_TEXT_CSS; } else { return MIME_TYPE_TEXT_PLAIN; } }
/** * Returns an input stream for a given resource * * @param resourceName * @return */ protected InputStream getPluginAssetAsStream(AppPlugin plugin, String fileName) { String assetDirectory = plugin.getAssetDirectory(); if (assetDirectory == null) { return null; } InputStream result = getWebResourceAsStream(assetDirectory, fileName); if (result == null) { result = getClasspathResourceAsStream(plugin, assetDirectory, fileName); } return result; } protected InputStream getWebResourceAsStream(String assetDirectory, String fileName) { String resourceName = String.format("/%s/%s", assetDirectory, fileName); return servletContext.getResourceAsStream(resourceName); } protected InputStream getClasspathResourceAsStream(AppPlugin plugin, String assetDirectory, String fileName) { String resourceName = String.format("%s/%s", assetDirectory, fileName); return plugin.getClass().getClassLoader().getResourceAsStream(resourceName); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\plugin\resource\AbstractAppPluginRootResource.java
1
请完成以下Java代码
public class AttributesKeyQueryHelper<T> { /** * @param modelColumn the attributesKey column to build the composite filter around. * @return an instance that can create a composite filter for attributes keys. */ public static <T> AttributesKeyQueryHelper<T> createFor(@NonNull final ModelColumn<T, Object> modelColumn) { return new AttributesKeyQueryHelper<>(modelColumn); } private final IQueryBL queryBL = Services.get(IQueryBL.class); private final Class<T> clazz; private final ModelColumn<T, Object> modelColumn; private AttributesKeyQueryHelper(@NonNull final ModelColumn<T, Object> modelColumn) { this.clazz = modelColumn.getModelClass(); this.modelColumn = modelColumn; } public IQueryFilter<T> createFilter(@NonNull final AttributesKeyPattern attributesKeyPattern) { return createFilter(ImmutableList.of(attributesKeyPattern)); } /** * @return an OR filter that matches any of the given {@code attributesKeys}. */ public IQueryFilter<T> createFilter(@NonNull final List<AttributesKeyPattern> attributesKeyPatterns) { Check.assumeNotEmpty(attributesKeyPatterns, "attributesKeyPatterns is not empty"); if (attributesKeyPatterns.contains(AttributesKeyPattern.ALL)) { return ConstantQueryFilter.of(true); } if (attributesKeyPatterns.contains(AttributesKeyPattern.OTHER)) { return ConstantQueryFilter.of(true); } final ArrayList<IQueryFilter<T>> filters = new ArrayList<>();
for (final AttributesKeyPattern attributesKeyPattern : attributesKeyPatterns) { final String likeExpression = attributesKeyPattern.getSqlLikeString(); final boolean ignoreCase = false; final StringLikeFilter<T> filter = new StringLikeFilter<>(modelColumn.getColumnName(), likeExpression, ignoreCase); filters.add(filter); } if (filters.isEmpty()) { return ConstantQueryFilter.of(true); } else if (filters.size() == 1) { return filters.get(0); } else { return queryBL.createCompositeQueryFilter(clazz) .setJoinOr() .addFilters(filters); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyQueryHelper.java
1
请完成以下Java代码
public static HttpHeaders getHeader(String mediaType) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(mediaType)); headers.add("Accept", mediaType); return headers; } /** * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式 */ public static String asUrlVariables(JSONObject variables) { Map<String, Object> source = variables.getInnerMap(); Iterator<String> it = source.keySet().iterator(); StringBuilder urlVariables = new StringBuilder(); while (it.hasNext()) {
String key = it.next(); String value = ""; Object object = source.get(key); if (object != null) { if (!StringUtils.isEmpty(object.toString())) { value = object.toString(); } } urlVariables.append("&").append(key).append("=").append(value); } // 去掉第一个& return urlVariables.substring(1); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\RestUtil.java
1
请完成以下Java代码
protected boolean isHistoryEventProduced() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); return historyLevel.isHistoryEventProduced(HistoryEventTypes.USER_OPERATION_LOG, null); } protected boolean isUserAuthenticated() { String userId = getAuthenticatedUserId(); return userId != null && !userId.isEmpty(); } protected String getAuthenticatedUserId() { CommandContext commandContext = Context.getCommandContext(); return commandContext.getAuthenticatedUserId(); } protected void fireUserOperationLog(final UserOperationLogContext context) { if (context.getUserId() == null) { context.setUserId(getAuthenticatedUserId()); } HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public List<HistoryEvent> createHistoryEvents(HistoryEventProducer producer) { return producer.createUserOperationLogEvents(context); } }); } protected boolean writeUserOperationLogOnlyWithLoggedInUser() {
return Context.getCommandContext().isRestrictUserOperationLogToAuthenticatedUsers(); } protected boolean isUserOperationLogEnabledOnCommandContext() { return Context.getCommandContext().isUserOperationLogEnabled(); } protected String getOperationType(IdentityOperationResult operationResult) { switch (operationResult.getOperation()) { case IdentityOperationResult.OPERATION_CREATE: return UserOperationLogEntry.OPERATION_TYPE_CREATE; case IdentityOperationResult.OPERATION_UPDATE: return UserOperationLogEntry.OPERATION_TYPE_UPDATE; case IdentityOperationResult.OPERATION_DELETE: return UserOperationLogEntry.OPERATION_TYPE_DELETE; case IdentityOperationResult.OPERATION_UNLOCK: return UserOperationLogEntry.OPERATION_TYPE_UNLOCK; default: return null; } } protected void configureQuery(UserOperationLogQueryImpl query) { getAuthorizationManager().configureUserOperationLogQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserOperationLogManager.java
1
请完成以下Java代码
public class DocumentNoBL implements IDocumentNoBL { private final Map<String, IDocumentNoListener> listeners = new HashMap<>(); @Override public void registerDocumentNoListener(@NonNull final IDocumentNoListener listener) { listeners.put(listener.getTableName(), listener); } @Override public void fireDocumentNoChange(final Object model, final String newDocumentNo) { final String tableName = InterfaceWrapperHelper.getModelTableNameOrNull(model); if (Check.isEmpty(tableName)) { return; } final IDocumentNoListener documentNoListener = listeners.get(tableName); if (documentNoListener == null) { return; }
final Optional<IDocumentNoAware> documentNoAware = asDocumentNoAware(model); if (!documentNoAware.isPresent()) { return; } documentNoListener.onDocumentNoChange(documentNoAware.get(), newDocumentNo); } @Override public Optional<IDocumentNoAware> asDocumentNoAware(final Object model) { final IDocumentNoAware documentNoAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(model, IDocumentNoAware.class); return Optional.of(documentNoAware); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBL.java
1
请完成以下Java代码
public String getAD_RelationType_InternalName () { return (String)get_Value(COLUMNNAME_AD_RelationType_InternalName); } public org.compiere.model.I_AD_Table getAD_Table_Source() throws RuntimeException { return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name) .getPO(getAD_Table_Source_ID(), get_TrxName()); } /** Set Quell-Tabelle. @param AD_Table_Source_ID Quell-Tabelle */ public void setAD_Table_Source_ID (int AD_Table_Source_ID) { if (AD_Table_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_Source_ID, Integer.valueOf(AD_Table_Source_ID)); } /** Get Quell-Tabelle. @return Quell-Tabelle */ public int getAD_Table_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Source_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Table getAD_Table_Target() throws RuntimeException { return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name) .getPO(getAD_Table_Target_ID(), get_TrxName()); } /** Set Ziel-Tabelle. @param AD_Table_Target_ID Ziel-Tabelle */ public void setAD_Table_Target_ID (int AD_Table_Target_ID) { if (AD_Table_Target_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, Integer.valueOf(AD_Table_Target_ID)); } /** Get Ziel-Tabelle. @return Ziel-Tabelle */ public int getAD_Table_Target_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Target_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Quell-Datensatz-ID. @param Record_Source_ID Quell-Datensatz-ID */ public void setRecord_Source_ID (int Record_Source_ID) { if (Record_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_Record_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID)); } /** Get Quell-Datensatz-ID. @return Quell-Datensatz-ID */ public int getRecord_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ziel-Datensatz-ID. @param Record_Target_ID Ziel-Datensatz-ID */ public void setRecord_Target_ID (int Record_Target_ID) { if (Record_Target_ID < 1) set_ValueNoCheck (COLUMNNAME_Record_Target_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID)); } /** Get Ziel-Datensatz-ID. @return Ziel-Datensatz-ID */ public int getRecord_Target_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Relation_Explicit_v1.java
1
请完成以下Java代码
public int getPP_MRP_Demand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Demand_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_MRP getPP_MRP_Supply() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class); } @Override public void setPP_MRP_Supply(org.eevolution.model.I_PP_MRP PP_MRP_Supply) { set_ValueFromPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class, PP_MRP_Supply); } /** Set MRP Supply. @param PP_MRP_Supply_ID MRP Supply */ @Override public void setPP_MRP_Supply_ID (int PP_MRP_Supply_ID) { if (PP_MRP_Supply_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, Integer.valueOf(PP_MRP_Supply_ID)); } /** Get MRP Supply. @return MRP Supply */ @Override public int getPP_MRP_Supply_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Supply_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugewiesene Menge. @param QtyAllocated Zugewiesene Menge */ @Override public void setQtyAllocated (java.math.BigDecimal QtyAllocated) { set_Value (COLUMNNAME_QtyAllocated, QtyAllocated); } /** Get Zugewiesene Menge. @return Zugewiesene Menge */ @Override public java.math.BigDecimal getQtyAllocated () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyAllocated); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alloc.java
1
请在Spring Boot框架中完成以下Java代码
protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .add("product", product) .add("bpartner", bpartner) .add("day", day) .add("trend", trend); } public Long getProductId() { return product.getId(); } public String getProductIdAsString() { return product.getIdAsString(); } public String getProductUUID() { return product.getUuid(); } public String getBpartnerUUID() { return bpartner.getUuid(); } public LocalDate getDay() { return day.toLocalDate(); } public YearWeek getWeek()
{ return YearWeekUtil.ofLocalDate(day.toLocalDate()); } @Nullable public Trend getTrend() { return Trend.ofNullableCode(trend); } @Nullable public String getTrendAsString() { return trend; } public void setTrend(@Nullable final Trend trend) { this.trend = trend != null ? trend.getCode() : null; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\WeekSupply.java
2
请完成以下Java代码
public void setEXP_ReplicationTrx_ID (final int EXP_ReplicationTrx_ID) { if (EXP_ReplicationTrx_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrx_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrx_ID, EXP_ReplicationTrx_ID); } @Override public int getEXP_ReplicationTrx_ID() { return get_ValueAsInt(COLUMNNAME_EXP_ReplicationTrx_ID); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setIsReplicationTrxFinished (final boolean IsReplicationTrxFinished) { set_Value (COLUMNNAME_IsReplicationTrxFinished, IsReplicationTrxFinished); } @Override public boolean isReplicationTrxFinished() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationTrxFinished); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrx.java
1
请在Spring Boot框架中完成以下Java代码
public void setAgencyCode(String value) { this.agencyCode = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language; }
/** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\FreeTextType.java
2
请完成以下Java代码
public NShortSegment enablePlaceRecognize(boolean enable) { config.placeRecognize = enable; config.updateNerConfig(); return this; } /** * 开启机构名识别 * @param enable * @return */ public NShortSegment enableOrganizationRecognize(boolean enable) { config.organizationRecognize = enable; config.updateNerConfig(); return this; } /** * 是否启用音译人名识别 * * @param enable */ public NShortSegment enableTranslatedNameRecognize(boolean enable) { config.translatedNameRecognize = enable; config.updateNerConfig(); return this; } /** * 是否启用日本人名识别 * * @param enable */ public NShortSegment enableJapaneseNameRecognize(boolean enable) { config.japaneseNameRecognize = enable;
config.updateNerConfig(); return this; } /** * 是否启用偏移量计算(开启后Term.offset才会被计算) * @param enable * @return */ public NShortSegment enableOffset(boolean enable) { config.offset = enable; return this; } public NShortSegment enableAllNamedEntityRecognize(boolean enable) { config.nameRecognize = enable; config.japaneseNameRecognize = enable; config.translatedNameRecognize = enable; config.placeRecognize = enable; config.organizationRecognize = enable; config.updateNerConfig(); return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\NShortSegment.java
1
请完成以下Java代码
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 String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link PersonIdentificationSchemeName1Choice } * */ public PersonIdentificationSchemeName1Choice getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is
* {@link PersonIdentificationSchemeName1Choice } * */ public void setSchmeNm(PersonIdentificationSchemeName1Choice value) { this.schmeNm = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericPersonIdentification1.java
1
请在Spring Boot框架中完成以下Java代码
public class AsyncConfig { public static final String EXECUTOR_ONE_BEAN_NAME = "executor-one"; public static final String EXECUTOR_TWO_BEAN_NAME = "executor-two"; @Configuration public static class ExecutorOneConfiguration { @Bean(name = EXECUTOR_ONE_BEAN_NAME + "-properties") @Primary @ConfigurationProperties(prefix = "spring.task.execution-one") // 读取 spring.task.execution-one 配置到 TaskExecutionProperties 对象 public TaskExecutionProperties taskExecutionProperties() { return new TaskExecutionProperties(); } @Bean(name = EXECUTOR_ONE_BEAN_NAME) public ThreadPoolTaskExecutor threadPoolTaskExecutor() { // 创建 TaskExecutorBuilder 对象 TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties()); // 创建 ThreadPoolTaskExecutor 对象 return builder.build(); } } @Configuration public static class ExecutorTwoConfiguration { @Bean(name = EXECUTOR_TWO_BEAN_NAME + "-properties") @ConfigurationProperties(prefix = "spring.task.execution-two") // 读取 spring.task.execution-two 配置到 TaskExecutionProperties 对象 public TaskExecutionProperties taskExecutionProperties() { return new TaskExecutionProperties(); } @Bean(name = EXECUTOR_TWO_BEAN_NAME) public ThreadPoolTaskExecutor threadPoolTaskExecutor() { // 创建 TaskExecutorBuilder 对象 TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties());
// 创建 ThreadPoolTaskExecutor 对象 return builder.build(); } } private static TaskExecutorBuilder createTskExecutorBuilder(TaskExecutionProperties properties) { // Pool 属性 TaskExecutionProperties.Pool pool = properties.getPool(); TaskExecutorBuilder builder = new TaskExecutorBuilder(); builder = builder.queueCapacity(pool.getQueueCapacity()); builder = builder.corePoolSize(pool.getCoreSize()); builder = builder.maxPoolSize(pool.getMaxSize()); builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout()); builder = builder.keepAlive(pool.getKeepAlive()); // Shutdown 属性 TaskExecutionProperties.Shutdown shutdown = properties.getShutdown(); builder = builder.awaitTermination(shutdown.isAwaitTermination()); builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod()); // 其它基本属性 builder = builder.threadNamePrefix(properties.getThreadNamePrefix()); // builder = builder.customizers(taskExecutorCustomizers.orderedStream()::iterator); // builder = builder.taskDecorator(taskDecorator.getIfUnique()); return builder; } }
repos\SpringBoot-Labs-master\lab-29\lab-29-async-two\src\main\java\cn\iocoder\springboot\lab29\asynctask\config\AsyncConfig.java
2
请完成以下Java代码
public abstract class JsonWriterStructuredLogFormatter<E> implements StructuredLogFormatter<E> { private final JsonWriter<E> jsonWriter; /** * Create a new {@link JsonWriterStructuredLogFormatter} instance with the given * members. * @param members a consumer, which should configure the members * @param customizer an optional customizer to apply */ protected JsonWriterStructuredLogFormatter(Consumer<Members<E>> members, @Nullable StructuredLoggingJsonMembersCustomizer<?> customizer) { this(JsonWriter.of(customized(members, customizer)).withNewLineAtEnd()); } private static <E> Consumer<Members<E>> customized(Consumer<Members<E>> members, @Nullable StructuredLoggingJsonMembersCustomizer<?> customizer) { return (customizer != null) ? members.andThen(customizeWith(customizer)) : members; } @SuppressWarnings("unchecked") private static <E> Consumer<Members<E>> customizeWith(StructuredLoggingJsonMembersCustomizer<?> customizer) { return (members) -> LambdaSafe.callback(StructuredLoggingJsonMembersCustomizer.class, customizer, members) .invoke((instance) -> instance.customize(members)); } /** * Create a new {@link JsonWriterStructuredLogFormatter} instance with the given * {@link JsonWriter}.
* @param jsonWriter the {@link JsonWriter} */ protected JsonWriterStructuredLogFormatter(JsonWriter<E> jsonWriter) { this.jsonWriter = jsonWriter; } @Override public String format(E event) { return this.jsonWriter.writeToString(event); } @Override public byte[] formatAsBytes(E event, Charset charset) { return this.jsonWriter.write(event).toByteArray(charset); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\JsonWriterStructuredLogFormatter.java
1
请完成以下Java代码
public class DLMPermanentIniCustomizer extends AbstractDLMCustomizer { public static final String INI_P_DLM_COALESCE_LEVEL = "de.metas.dlm.DLM_Coalesce_Level"; public static final String INI_P_DLM_DLM_LEVEL = "de.metas.dlm.DLM_Level"; public static AbstractDLMCustomizer INSTANCE = new DLMPermanentIniCustomizer(); private DLMPermanentIniCustomizer() { } /** * Returns the dlm level set in the {@link Ini} (metasfresh.properties).<br> * <b>Side Effect:</b> if none is set there yet, then it gets the value from {@link DLMPermanentSysConfigCustomizer} and adds it to the {@link Ini}. */ @Override public int getDlmLevel() { final int dlmLevel; final String iniLevel = Ini.getProperty(INI_P_DLM_DLM_LEVEL); if (Check.isEmpty(iniLevel)) { dlmLevel = DLMPermanentSysConfigCustomizer.PERMANENT_SYSCONFIG_INSTANCE.getDlmLevel(); Ini.setProperty(INI_P_DLM_DLM_LEVEL, dlmLevel); Ini.saveProperties(); } else { dlmLevel = Integer.parseInt(iniLevel);
} return dlmLevel; } /** * Returns the coalesce level set in the {@link Ini} (metasfresh.properties).<br> * <b>Side Effect:</b> if none is set there yet, then it gets the value from {@link DLMPermanentSysConfigCustomizer} and adds it to the {@link Ini}. */ @Override public int getDlmCoalesceLevel() { final int dlmCoalesceLevel; final String iniLevel = Ini.getProperty(INI_P_DLM_COALESCE_LEVEL); if (Check.isEmpty(iniLevel)) { dlmCoalesceLevel = DLMPermanentSysConfigCustomizer.PERMANENT_SYSCONFIG_INSTANCE.getDlmCoalesceLevel(); Ini.setProperty(INI_P_DLM_COALESCE_LEVEL, dlmCoalesceLevel); Ini.saveProperties(); } else { dlmCoalesceLevel = Integer.parseInt(iniLevel); } return dlmCoalesceLevel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMPermanentIniCustomizer.java
1
请完成以下Java代码
public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Report.java
1
请在Spring Boot框架中完成以下Java代码
public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } /** * {@link View} backed by an HTML resource. */ private static class HtmlResourceView implements View { private final Resource resource; HtmlResourceView(Resource resource) { this.resource = resource;
} @Override public String getContentType() { return MediaType.TEXT_HTML_VALUE; } @Override public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(getContentType()); FileCopyUtils.copy(this.resource.getInputStream(), response.getOutputStream()); } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\error\DefaultErrorViewResolver.java
2
请完成以下Java代码
final class ProductsCache { private final IProductDAO productsRepo; private final Map<ProductId, Product> productsCache = new HashMap<>(); @Builder private ProductsCache(@NonNull final IProductDAO productsRepo) { this.productsRepo = productsRepo; } public Product getProductById(final ProductId productId) { return productsCache.computeIfAbsent(productId, this::retrieveProductById); } private Product retrieveProductById(final ProductId productId) { final I_M_Product productRecord = productsRepo.getByIdInTrx(productId); return new ProductsCache.Product(productRecord); } public Product newProduct(@NonNull final I_M_Product productRecord) { return new ProductsCache.Product(productRecord); } public void clear() { productsCache.clear(); } final class Product
{ @Getter private final I_M_Product record; private Product(@NonNull final I_M_Product record) { this.record = record; } public ProductId getIdOrNull() { return ProductId.ofRepoIdOrNull(record.getM_Product_ID()); } public int getOrgId() { return record.getAD_Org_ID(); } public void save() { productsRepo.save(record); productsCache.put(getIdOrNull(), this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\ProductsCache.java
1
请完成以下Java代码
public void setSubjectTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver) { Assert.notNull(subjectTokenResolver, "subjectTokenResolver cannot be null"); this.subjectTokenResolver = subjectTokenResolver; } /** * Sets the resolver used for resolving the {@link OAuth2Token actor token}. * @param actorTokenResolver the resolver used for resolving the {@link OAuth2Token * actor token} */ public void setActorTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver) { Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null"); this.actorTokenResolver = actorTokenResolver; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds. * * <p>
* An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew */ public void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public boolean isIncludeAllAttributeValues () { Object oo = get_Value(COLUMNNAME_IsIncludeAllAttributeValues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Merkmalswert-Zusammenfassung. @param IsValueAggregate Merkmalswert-Zusammenfassung */ @Override public void setIsValueAggregate (boolean IsValueAggregate) { set_Value (COLUMNNAME_IsValueAggregate, Boolean.valueOf(IsValueAggregate)); } /** Get Merkmalswert-Zusammenfassung. @return Merkmalswert-Zusammenfassung */ @Override public boolean isValueAggregate () { Object oo = get_Value(COLUMNNAME_IsValueAggregate); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Merkmal. @param M_Attribute_ID Produkt-Merkmal */ @Override public void setM_Attribute_ID (int M_Attribute_ID) { if (M_Attribute_ID < 1) set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID)); } /** Get Merkmal. @return Produkt-Merkmal */ @Override
public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gruppenname. @param ValueAggregateName Gruppenname */ @Override public void setValueAggregateName (java.lang.String ValueAggregateName) { set_Value (COLUMNNAME_ValueAggregateName, ValueAggregateName); } /** Get Gruppenname. @return Gruppenname */ @Override public java.lang.String getValueAggregateName () { return (java.lang.String)get_Value(COLUMNNAME_ValueAggregateName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
class OtherLinesAggregator implements QuotationLinesGroupAggregator { private final ProjectQuotationPriceCalculator priceCalculator; private final LinkedHashMap<QuotationLineKey, QuotationLineAggregator> lineAggregators = new LinkedHashMap<>(); @Builder private OtherLinesAggregator( @NonNull final ProjectQuotationPriceCalculator priceCalculator) { this.priceCalculator = priceCalculator; } @Override public void add(final @NonNull ServiceRepairProjectCostCollector costCollector) { final QuotationLineKey lineKey = QuotationLineAggregator.extractKey(costCollector); final QuotationLineAggregator lineAggregator = lineAggregators.computeIfAbsent(lineKey, this::newLineAggregator); lineAggregator.add(costCollector); } private QuotationLineAggregator newLineAggregator(@NonNull final QuotationLineKey lineKey) { return QuotationLineAggregator.builder() .priceCalculator(priceCalculator) .key(lineKey) .build(); } @Override public void createOrderLines(@NonNull final OrderFactory orderFactory) { lineAggregators.values() .forEach(lineAggregator -> lineAggregator.createOrderLines(orderFactory));
} @Override public Stream<Map.Entry<ServiceRepairProjectCostCollectorId, OrderAndLineId>> streamQuotationLineIdsIndexedByCostCollectorId() { return lineAggregators.values() .stream() .flatMap(QuotationLineAggregator::streamQuotationLineIdsIndexedByCostCollectorId); } @Override public GroupTemplate getGroupTemplate() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\OtherLinesAggregator.java
2
请完成以下Java代码
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } @Override public String modelChange(PO po, int type) throws Exception { if (I_AD_Table_MView.Table_Name.equals(po.get_TableName())) { processMetadataChanges(po, type); } else if (TYPE_AFTER_NEW == type || TYPE_AFTER_CHANGE == type || TYPE_AFTER_DELETE == type) { refreshFromSource(po, type); } return null; } private void processMetadataChanges(PO po, int type) { final I_AD_Table_MView mview = InterfaceWrapperHelper.create(po, I_AD_Table_MView.class); if (TYPE_AFTER_NEW == type || (TYPE_AFTER_CHANGE == type && po.is_ValueChanged(I_AD_Table_MView.COLUMNNAME_IsValid) && mview.isValid())) { addMView(mview, false); } } private void refreshFromSource(PO sourcePO, int changeType) { final String sourceTableName = sourcePO.get_TableName(); final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class); for (I_AD_Table_MView mview : mviewBL.fetchAll(Env.getCtx())) { MViewMetadata mdata = mviewBL.getMetadata(mview); if (mdata == null) { mview.setIsValid(false); InterfaceWrapperHelper.save(mview); log.info("No metadata found for " + mview + " [SKIP]"); continue; } if (!mdata.getSourceTables().contains(sourceTableName)) { // not relevant PO for this MView continue; } if (!mviewBL.isSourceChanged(mdata, sourcePO, changeType)) { // no relevant changes for this view continue; } refreshFromSource(mdata, sourcePO, new RefreshMode[] { RefreshMode.Partial }); } } public void refreshFromSource(MViewMetadata mdata, PO sourcePO, RefreshMode[] refreshModes) { final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class); final I_AD_Table_MView mview = mviewBL.fetchForTableName(sourcePO.getCtx(), mdata.getTargetTableName(), sourcePO.get_TrxName()); boolean staled = true; for (RefreshMode refreshMode : refreshModes) { if (mviewBL.isAllowRefresh(mview, sourcePO, refreshMode)) { mviewBL.refresh(mview, sourcePO, refreshMode, sourcePO.get_TrxName()); staled = false; break; }
} // // We should do a complete refresh => marking mview as staled if (staled) { mviewBL.setStaled(mview); } } private boolean addMView(I_AD_Table_MView mview, boolean invalidateIfNecessary) { final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class); MViewMetadata mdata = mviewBL.getMetadata(mview); if (mdata == null) { // no metadata found => IGNORE if (invalidateIfNecessary) { mview.setIsValid(false); InterfaceWrapperHelper.save(mview); } return false; } for (String sourceTableName : mdata.getSourceTables()) { engine.addModelChange(sourceTableName, this); } registeredTables.add(mview.getAD_Table_ID()); return true; } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewModelValidator.java
1
请完成以下Java代码
public CaseInstanceMigrationDocumentBuilder preUpgradeExpression(String preUpgradeExpression) { this.preUpgradeExpression = preUpgradeExpression; return this; } @Override public CaseInstanceMigrationDocumentBuilder postUpgradeExpression(String postUpgradeExpression) { this.postUpgradeExpression = postUpgradeExpression; return this; } @Override public CaseInstanceMigrationDocument build() { CaseInstanceMigrationDocumentImpl caseInstanceMigrationDocument = new CaseInstanceMigrationDocumentImpl(); caseInstanceMigrationDocument.setMigrateToCaseDefinitionId(this.migrateToCaseDefinitionId);
caseInstanceMigrationDocument.setMigrateToCaseDefinition(this.migrateToCaseDefinitionKey, this.migrateToCaseDefinitionVersion, this.migrateToCaseDefinitionTenantId); caseInstanceMigrationDocument.setActivatePlanItemDefinitionMappings(this.activatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setTerminatePlanItemDefinitionMappings(this.terminatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setMoveToAvailablePlanItemDefinitionMappings(this.moveToAvailablePlanItemDefinitionMappings); caseInstanceMigrationDocument.setWaitingForRepetitionPlanItemDefinitionMappings(this.waitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setRemoveWaitingForRepetitionPlanItemDefinitionMappings(this.removeWaitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setChangePlanItemIdMappings(this.changePlanItemIdMappings); caseInstanceMigrationDocument.setChangePlanItemIdWithDefinitionIdMappings(this.changePlanItemIdWithDefinitionIdMappings); caseInstanceMigrationDocument.setChangePlanItemDefinitionWithNewTargetIdsMappings(this.changePlanItemDefinitionWithNewTargetIdsMappings); caseInstanceMigrationDocument.setCaseInstanceVariables(this.caseInstanceVariables); caseInstanceMigrationDocument.setPreUpgradeExpression(this.preUpgradeExpression); caseInstanceMigrationDocument.setPostUpgradeExpression(this.postUpgradeExpression); return caseInstanceMigrationDocument; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentBuilderImpl.java
1