instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ResourceImportService extends BaseEntityImportService<TbResourceId, TbResource, EntityExportData<TbResource>> { private final ResourceService resourceService; private final ImageService imageService; @Override protected void setOwner(TenantId tenantId, TbResource resource, IdProvider idProvider) { resource.setTenantId(tenantId); } @Override protected TbResource prepare(EntitiesImportCtx ctx, TbResource resource, TbResource oldResource, EntityExportData<TbResource> exportData, IdProvider idProvider) { return resource; } @Override protected TbResource findExistingEntity(EntitiesImportCtx ctx, TbResource resource, IdProvider idProvider) { TbResource existingResource = super.findExistingEntity(ctx, resource, idProvider); if (existingResource == null && ctx.isFindExistingByName()) { existingResource = resourceService.findResourceByTenantIdAndKey(ctx.getTenantId(), resource.getResourceType(), resource.getResourceKey()); } return existingResource; } @Override protected TbResource deepCopy(TbResource resource) { return new TbResource(resource); } @Override protected void cleanupForComparison(TbResource resource) { super.cleanupForComparison(resource); resource.setSearchText(null); if (resource.getDescriptor() != null && resource.getDescriptor().isNull()) { resource.setDescriptor(null); } } @Override protected TbResource saveOrUpdate(EntitiesImportCtx ctx, TbResource resource, EntityExportData<TbResource> exportData, IdProvider idProvider, CompareResult compareResult) { if (resource.getResourceType() == ResourceType.IMAGE) { return new TbResource(imageService.saveImage(resource)); } else { if (compareResult.isExternalIdChangedOnly()) { resource = resourceService.saveResource(resource, false); } else {
resource = resourceService.saveResource(resource); } resource.setData(null); resource.setPreview(null); return resource; } } @Override protected void onEntitySaved(User user, TbResource savedResource, TbResource oldResource) throws ThingsboardException { super.onEntitySaved(user, savedResource, oldResource); clusterService.onResourceChange(savedResource, null); } @Override public EntityType getEntityType() { return EntityType.TB_RESOURCE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\ResourceImportService.java
2
请完成以下Java代码
public OrderId getOrderId() {return orderAndLineId.getOrderId();} public OrderLineId getOrderLineId() {return orderAndLineId.getOrderLineId();} public InOutId getInOutId() {return inoutAndLineId.getInOutId();} public InOutLineId getInOutLineId() {return inoutAndLineId.getInOutLineId();} public void addCostAmountInvoiced(@NonNull final Money amtToAdd) { this.costAmountInvoiced = this.costAmountInvoiced.add(amtToAdd); this.isInvoiced = this.costAmount.isEqualByComparingTo(this.costAmountInvoiced); } public Money getCostAmountToInvoice() { return costAmount.subtract(costAmountInvoiced); }
public Money getCostAmountForQty(final Quantity qty, CurrencyPrecision precision) { if (qty.equalsIgnoreSource(this.qty)) { return costAmount; } else if (qty.isZero()) { return costAmount.toZero(); } else { final Money price = costAmount.divide(this.qty.toBigDecimal(), CurrencyPrecision.ofInt(12)); return price.multiply(qty.toBigDecimal()).round(precision); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCost.java
1
请完成以下Java代码
public List<EventDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getParentDeploymentId() { return parentDeploymentId; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getKeyLikeIgnoreCase() { return keyLikeIgnoreCase;
} public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDefinitionQueryImpl.java
1
请完成以下Java代码
public static JSONObject convert2JsonAndCheckRequiredColumns(HttpServletRequest request, String requiredColumns) { JSONObject jsonObject = request2Json(request); hasAllRequired(jsonObject, requiredColumns); return jsonObject; } /** * 验证是否含有全部必填字段 * * @param requiredColumns 必填的参数字段名称 逗号隔开 比如"userId,name,telephone" */ public static void hasAllRequired(final JSONObject jsonObject, String requiredColumns) { if (!StringTools.isNullOrEmpty(requiredColumns)) { //验证字段非空 String[] columns = requiredColumns.split(","); String missCol = ""; for (String column : columns) { Object val = jsonObject.get(column.trim()); if (StringTools.isNullOrEmpty(val)) { missCol += column + " "; } } if (!StringTools.isNullOrEmpty(missCol)) { jsonObject.clear(); jsonObject.put("code", ErrorEnum.E_90003.getErrorCode()); jsonObject.put("msg", "缺少必填参数:" + missCol.trim()); jsonObject.put("info", new JSONObject()); throw new CommonJsonException(jsonObject); } } }
/** * 在分页查询之前,为查询条件里加上分页参数 * * @param paramObject 查询条件json * @param defaultPageRow 默认的每页条数,即前端不传pageRow参数时的每页条数 */ private static void fillPageParam(final JSONObject paramObject, int defaultPageRow) { int pageNum = paramObject.getIntValue("pageNum"); pageNum = pageNum == 0 ? 1 : pageNum; int pageRow = paramObject.getIntValue("pageRow"); pageRow = pageRow == 0 ? defaultPageRow : pageRow; paramObject.put("offSet", (pageNum - 1) * pageRow); paramObject.put("pageRow", pageRow); paramObject.put("pageNum", pageNum); //删除此参数,防止前端传了这个参数,pageHelper分页插件检测到之后,拦截导致SQL错误 paramObject.remove("pageSize"); } /** * 分页查询之前的处理参数 * 没有传pageRow参数时,默认每页10条. */ public static void fillPageParam(final JSONObject paramObject) { fillPageParam(paramObject, 10); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\util\CommonUtil.java
1
请完成以下Java代码
private BatchPreparedStatementSetter getCalculatedFieldEventSetter(List<Event> events) { return new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { CalculatedFieldDebugEvent event = (CalculatedFieldDebugEvent) events.get(i); setCommonEventFields(ps, event); safePutUUID(ps, 6, event.getCalculatedFieldId().getId()); safePutUUID(ps, 7, event.getEventEntity() != null ? event.getEventEntity().getId() : null); safePutString(ps, 8, event.getEventEntity() != null ? event.getEventEntity().getEntityType().name() : null); safePutUUID(ps, 9, event.getMsgId()); safePutString(ps, 10, event.getMsgType()); safePutString(ps, 11, event.getArguments()); safePutString(ps, 12, event.getResult()); safePutString(ps, 13, event.getError()); } @Override public int getBatchSize() { return events.size(); } }; } void safePutString(PreparedStatement ps, int parameterIdx, String value) throws SQLException { if (value != null) { ps.setString(parameterIdx, replaceNullChars(value)); } else { ps.setNull(parameterIdx, Types.VARCHAR); } } void safePutUUID(PreparedStatement ps, int parameterIdx, UUID value) throws SQLException { if (value != null) { ps.setObject(parameterIdx, value); } else { ps.setNull(parameterIdx, Types.OTHER); } }
private void setCommonEventFields(PreparedStatement ps, Event event) throws SQLException { ps.setObject(1, event.getId().getId()); ps.setObject(2, event.getTenantId().getId()); ps.setLong(3, event.getCreatedTime()); ps.setObject(4, event.getEntityId()); ps.setString(5, event.getServiceId()); } private String replaceNullChars(String strValue) { if (removeNullChars && strValue != null) { return PATTERN_THREAD_LOCAL.get().matcher(strValue).replaceAll(EMPTY_STR); } return strValue; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\EventInsertRepository.java
1
请完成以下Java代码
public List<Object> getSqlValuesList(@NonNull final DocumentId rowId) { return extractComposedKey(rowId).getSqlValuesList(); } @Nullable public DocumentId retrieveRowId(final ResultSet rs) { final String sqlColumnPrefix = null; final boolean useKeyColumnNames = true; return retrieveRowId(rs, sqlColumnPrefix, useKeyColumnNames); } @Nullable public DocumentId retrieveRowId(final ResultSet rs, @Nullable final String sqlColumnPrefix, final boolean useKeyColumnNames) { final List<Object> rowIdParts = keyFields .stream() .map(keyField -> retrieveRowIdPart(rs, buildKeyColumnNameEffective(keyField.getColumnName(), sqlColumnPrefix, useKeyColumnNames), keyField.getSqlValueClass())) .collect(Collectors.toList()); final boolean isNotNull = rowIdParts.stream().anyMatch(Objects::nonNull); if (!isNotNull) { return null; } return DocumentId.ofComposedKeyParts(rowIdParts); } private String buildKeyColumnNameEffective(final String keyColumnName, @Nullable final String sqlColumnPrefix, final boolean useKeyColumnName) { final String selectionColumnName = useKeyColumnName ? keyColumnName : getWebuiSelectionColumnNameForKeyColumnName(keyColumnName); if (sqlColumnPrefix != null && !sqlColumnPrefix.isEmpty()) { return sqlColumnPrefix + selectionColumnName; } else { return selectionColumnName; } } @Nullable private Object retrieveRowIdPart(final ResultSet rs, final String columnName, final Class<?> sqlValueClass) { try { if (Integer.class.equals(sqlValueClass) || int.class.equals(sqlValueClass)) { final int rowIdPart = rs.getInt(columnName); if (rs.wasNull()) { return null; } return rowIdPart;
} else if (String.class.equals(sqlValueClass)) { return rs.getString(columnName); } else { throw new AdempiereException("Unsupported type " + sqlValueClass + " for " + columnName); } } catch (final SQLException ex) { throw new DBException("Failed fetching " + columnName + " (" + sqlValueClass + ")", ex); } } @Value @Builder private static class KeyColumnNameInfo { @NonNull String keyColumnName; @NonNull String webuiSelectionColumnName; boolean isNullable; public String getEffectiveColumnName(@NonNull final MappingType mappingType) { if (mappingType == MappingType.SOURCE_TABLE) { return keyColumnName; } else if (mappingType == MappingType.WEBUI_SELECTION_TABLE) { return webuiSelectionColumnName; } else { // shall not happen throw new AdempiereException("Unknown mapping type: " + mappingType); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewKeyColumnNamesMap.java
1
请完成以下Java代码
private ImmutableSet<AdWindowId> getTargetAdWindowIds(final AdTableId adTableId, final @Nullable AdWindowId onlyWindowId) { final ImmutableSet<AdWindowId> eligibleWindowIds = adWindowDAO.retrieveAllAdWindowIdsByTableId(adTableId); if (onlyWindowId == null) { return eligibleWindowIds; } else if (eligibleWindowIds.contains(onlyWindowId)) { return ImmutableSet.of(onlyWindowId); } else { return ImmutableSet.of(); } }
private ITranslatableString buildFilterCaption(final AdWindowId windowsWindowId) { return adWindowDAO.retrieveWindowName(windowsWindowId); } private ITranslatableString buildFilterByFieldCaption(@NonNull final AdTableId adTableId) { final String tableName = TableIdsCache.instance.getTableName(adTableId); return TranslatableStrings.builder() .appendADElement("TableName") .append(": ") .append(tableName) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\TableRelatedDocumentsProvider.java
1
请完成以下Java代码
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代码
public void validateVoidActionForMediatedOrder(final I_C_Order order) { if (orderBL.isMediated(order)) { throw new AdempiereException("'Void' action is not permitted for mediated orders!"); } } private void validateSupplierApprovals(final I_C_Order order) { if (order.isSOTrx()) { // Only purchase orders are relevant return; } final ImmutableList<ProductId> productIds = orderDAO.retrieveOrderLines(order) .stream() .map(line -> ProductId.ofRepoId(line.getM_Product_ID())) .collect(ImmutableList.toImmutableList()); for (final ProductId productId : productIds) { final ImmutableList<String> supplierApprovalNorms = productBL.retrieveSupplierApprovalNorms(productId); if (Check.isEmpty(supplierApprovalNorms)) { // nothing to validate continue; } final BPartnerId partnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID()); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); partnerSupplierApprovalService.validateSupplierApproval(partnerId, TimeUtil.asLocalDate(order.getDatePromised(), timeZone), supplierApprovalNorms); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Order.COLUMNNAME_C_BPartner_ID }) public void setBillBPartnerIdIfAssociation(final I_C_Order order) { final I_C_BP_Group bpartnerGroup = groupDAO.getByBPartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID())); if (bpartnerGroup.isAssociation())
{ order.setBill_BPartner_ID(bpartnerGroup.getBill_BPartner_ID()); order.setBill_Location_ID(bpartnerGroup.getBill_Location_ID()); order.setBill_User_ID(bpartnerGroup.getBill_User_ID()); } else { final BPGroupId parentGroupId = BPGroupId.ofRepoIdOrNull(bpartnerGroup.getParent_BP_Group_ID()); if (parentGroupId != null) { final I_C_BP_Group parentGroup = groupDAO.getById(parentGroupId); if (parentGroup.isAssociation()) { order.setBill_BPartner_ID(parentGroup.getBill_BPartner_ID()); order.setBill_Location_ID(parentGroup.getBill_Location_ID()); order.setBill_User_ID(parentGroup.getBill_User_ID()); } } } } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void createOrderPaySchedules(final I_C_Order order) { orderPayScheduleService.createOrderPaySchedules(order); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE) public void deleteOrderPaySchedules(final I_C_Order order) { orderPayScheduleService.deleteByOrderId(OrderId.ofRepoId(order.getC_Order_ID())); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_Order.COLUMNNAME_LC_Date, I_C_Order.COLUMNNAME_ETA, I_C_Order.COLUMNNAME_BLDate, I_C_Order.COLUMNNAME_InvoiceDate }) public void updateOrderPaySchedules(final I_C_Order order) { orderPayScheduleService.updatePayScheduleStatus(order); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_Order.java
1
请完成以下Java代码
public int assignAsyncBatchForProcessing( @NonNull final Set<QueuePackageProcessorId> queuePackageProcessorIds, @NonNull final AsyncBatchId asyncBatchId) { final ILockManager lockManager = Services.get(ILockManager.class); final ICompositeQueryUpdater<I_C_Queue_WorkPackage> updater = queryBL.createCompositeQueryUpdater(I_C_Queue_WorkPackage.class) .addSetColumnValue(I_C_Queue_WorkPackage.COLUMNNAME_C_Async_Batch_ID, asyncBatchId.getRepoId()); final IQuery<I_C_Queue_WorkPackage> updateQuery = queryBL.createQueryBuilder(I_C_Queue_WorkPackage.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_Queue_WorkPackage.COLUMNNAME_C_Queue_PackageProcessor_ID, queuePackageProcessorIds) .addEqualsFilter(I_C_Queue_WorkPackage.COLUMNNAME_C_Async_Batch_ID, null) .addEqualsFilter(I_C_Queue_WorkPackage.COLUMNNAME_IsReadyForProcessing, true) .addEqualsFilter(I_C_Queue_WorkPackage.COLUMNNAME_Processed, false) .addEqualsFilter(I_C_Queue_WorkPackage.COLUMNNAME_IsError, false) .create(); return lockManager.addNotLockedClause(updateQuery) .updateDirectly(updater); }
private final CCache<String, QueuePackageProcessorId> classname2QueuePackageProcessorId = CCache .<String, QueuePackageProcessorId>builder() .tableName(I_C_Queue_PackageProcessor.Table_Name) .build(); // we will only ever have a handful of processors, so there is nothing much to worry about wrt cache-size @Nullable @Override public QueuePackageProcessorId retrieveQueuePackageProcessorIdFor(@NonNull final String classname) { return classname2QueuePackageProcessorId.getOrLoad(classname, this::retrieveQueuePackageProcessorIdFor0); } @Nullable private QueuePackageProcessorId retrieveQueuePackageProcessorIdFor0(@NonNull final String classname) { return queryBL.createQueryBuilder(I_C_Queue_PackageProcessor.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Queue_PackageProcessor.COLUMNNAME_Classname, classname) .create() .firstId(QueuePackageProcessorId::ofRepoIdOrNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AbstractQueueDAO.java
1
请完成以下Java代码
public int getDisplayType(final int IGNORED, final int col) { final Object value = currentRow.get(col); return CellValues.extractDisplayTypeFromValue(value); } @Override public List<CellValue> getHeaderNames() { final List<String> headerNames = new ArrayList<>(); if (m_columnHeaders == null || m_columnHeaders.isEmpty()) { // use the next data row; can be the first, but if we add another sheet, it can also be another one. stepToNextRow(); for (Object headerNameObj : currentRow) { headerNames.add(headerNameObj != null ? headerNameObj.toString() : null); } } else { headerNames.addAll(m_columnHeaders); } final ArrayList<CellValue> result = new ArrayList<>(); final String adLanguage = getLanguage().getAD_Language(); for (final String rawHeaderName : headerNames) { final String headerName; if (translateHeaders) { headerName = msgBL.translatable(rawHeaderName).translate(adLanguage); } else { headerName = rawHeaderName; } result.add(CellValues.toCellValue(headerName)); } return result; } @Override
public int getRowCount() { return m_data.size() - 1; } @Override public boolean isColumnPrinted(final int col) { return true; } @Override public boolean isFunctionRow(final int row) { return false; } @Override public boolean isPageBreak(final int row, final int col) { return false; } @Override protected List<CellValue> getNextRow() { stepToNextRow(); return CellValues.toCellValues(currentRow); } private void stepToNextRow() { currentRow = m_data.get(currentRowNumber); currentRowNumber++; } @Override protected boolean hasNextRow() { return currentRowNumber < m_data.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ArrayExcelExporter.java
1
请完成以下Java代码
public void setX1 (java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } /** Get Regal. @return Regal */ @Override public java.lang.String getX1 () { return (java.lang.String)get_Value(COLUMNNAME_X1); } /** Set Fach. @param Y Y-Dimension, z.B. Fach */ @Override public void setY (java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); } /** Get Fach. @return Y-Dimension, z.B. Fach */ @Override public java.lang.String getY () { return (java.lang.String)get_Value(COLUMNNAME_Y); } /** Set Ebene. @param Z
Z-Dimension, z.B. Ebene */ @Override public void setZ (java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } /** Get Ebene. @return Z-Dimension, z.B. Ebene */ @Override public java.lang.String getZ () { return (java.lang.String)get_Value(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java
1
请完成以下Java代码
public java.lang.String getMSV3_Tour () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Tour); } /** Set MSV3_Tour. @param MSV3_Tour_ID MSV3_Tour */ @Override public void setMSV3_Tour_ID (int MSV3_Tour_ID) { if (MSV3_Tour_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Tour_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Tour_ID, Integer.valueOf(MSV3_Tour_ID)); } /** Get MSV3_Tour. @return MSV3_Tour */ @Override public int getMSV3_Tour_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Tour_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil getMSV3_VerfuegbarkeitAnteil() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class); } @Override public void setMSV3_VerfuegbarkeitAnteil(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil MSV3_VerfuegbarkeitAnteil) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class, MSV3_VerfuegbarkeitAnteil); } /** Set MSV3_VerfuegbarkeitAnteil. @param MSV3_VerfuegbarkeitAnteil_ID MSV3_VerfuegbarkeitAnteil */ @Override
public void setMSV3_VerfuegbarkeitAnteil_ID (int MSV3_VerfuegbarkeitAnteil_ID) { if (MSV3_VerfuegbarkeitAnteil_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, Integer.valueOf(MSV3_VerfuegbarkeitAnteil_ID)); } /** Get MSV3_VerfuegbarkeitAnteil. @return MSV3_VerfuegbarkeitAnteil */ @Override public int getMSV3_VerfuegbarkeitAnteil_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Tour.java
1
请完成以下Spring Boot application配置
logging.level.org.springframework=debug #spring.security.user.name=in28minutes #spring.security.user.password=dummy spring.datasource.url=jdbc:h2:mem:testdb # spring.h2.console.enabled=true // Before Spring Boot 4 spring.jpa.defer-datasource-initial
ization=true spring.main.banner-mode=off logging.pattern.console= %d{MM-dd HH:mm:ss} - %logger{36} - %msg%n
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\resources\application.properties
2
请完成以下Java代码
public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() {
return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderReturnReasonExample.java
1
请完成以下Java代码
public Cache<String, String> expiringHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) { return this.buildCache(EXPIRING_HELLO_WORLD_CACHE, cacheManager, listener, expiringConfiguration()); } public Cache<String, String> evictingHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) { return this.buildCache(EVICTING_HELLO_WORLD_CACHE, cacheManager, listener, evictingConfiguration()); } public Cache<String, String> passivatingHelloWorldCache(DefaultCacheManager cacheManager, CacheListener listener) { return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration()); } private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) { cacheManager.defineConfiguration(cacheName, configuration); Cache<K, V> cache = cacheManager.getCache(cacheName); cache.addListener(listener); return cache; } private Configuration expiringConfiguration() {
return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build(); } private Configuration evictingConfiguration() { return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build(); } private Configuration passivatingConfiguration() { return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build(); } private Configuration transactionalConfiguration() { return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build(); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\infinispan\CacheConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
private Map<String, String> getDepartOtherPostByUserIds(List<String> userIdList, String symbol) { Map<String, String> departPostMap = new HashMap<>(); List<SysUserSysDepPostModel> departPost = sysDepartMapper.getDepartOtherPostByUserIds(userIdList); if (CollectionUtil.isNotEmpty(departPost)) { ISysDepartService service = SpringContextUtils.getBean(SysDepartServiceImpl.class); departPost.forEach(item -> { if (oConvertUtils.isNotEmpty(item.getId()) && oConvertUtils.isNotEmpty(item.getOtherDepPostId())) { String postName = service.getDepartPathNameByOrgCode(item.getOrgCode(), ""); if (departPostMap.containsKey(item.getId())) { departPostMap.put(item.getId(), departPostMap.get(item.getId()) + symbol + postName); } else { departPostMap.put(item.getId(), postName); } } }); } return departPostMap; } /** * 根据用户ids获取部门名称 * * @param userIdList
* @param symbol * @return */ private Map<String, String> getDepartNamesByUserIds(List<String> userIdList, String symbol) { Map<String, String> userOrgCodeMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(userIdList)) { List<SysUserSysDepPostModel> userDepPosts = sysUserDepartMapper.getUserDepPostByUserIds(userIdList); if (CollectionUtil.isNotEmpty(userDepPosts)) { ISysDepartService service = SpringContextUtils.getBean(SysDepartServiceImpl.class); userDepPosts.forEach(item -> { if (oConvertUtils.isNotEmpty(item.getId()) && oConvertUtils.isNotEmpty(item.getOrgCode())) { String departNamePath = service.getDepartPathNameByOrgCode(item.getOrgCode(), ""); if (userOrgCodeMap.containsKey(item.getId())) { userOrgCodeMap.put(item.getId(), userOrgCodeMap.get(item.getId()) + symbol + departNamePath); } else { userOrgCodeMap.put(item.getId(), departNamePath); } } }); } } return userOrgCodeMap; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserServiceImpl.java
2
请完成以下Java代码
public void concurrentChildExecutionEnded(ActivityExecution scopeExecution, ActivityExecution endedExecution) { // cannot happen } protected void prepareScope(ActivityExecution scopeExecution, int totalNumberOfInstances) { setLoopVariable(scopeExecution, NUMBER_OF_INSTANCES, totalNumberOfInstances); setLoopVariable(scopeExecution, NUMBER_OF_COMPLETED_INSTANCES, 0); } public List<ActivityExecution> initializeScope(ActivityExecution scopeExecution, int nrOfInstances) { if (nrOfInstances > 1) { LOG.unsupportedConcurrencyException(scopeExecution.toString(), this.getClass().getSimpleName()); } List<ActivityExecution> executions = new ArrayList<ActivityExecution>(); prepareScope(scopeExecution, nrOfInstances); setLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES, nrOfInstances); if (nrOfInstances > 0) { setLoopVariable(scopeExecution, LOOP_COUNTER, 0); executions.add(scopeExecution); } return executions; } @Override public ActivityExecution createInnerInstance(ActivityExecution scopeExecution) { if (hasLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES) && getLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES) > 0) { throw LOG.unsupportedConcurrencyException(scopeExecution.toString(), this.getClass().getSimpleName());
} else { int nrOfInstances = getLoopVariable(scopeExecution, NUMBER_OF_INSTANCES); setLoopVariable(scopeExecution, LOOP_COUNTER, nrOfInstances); setLoopVariable(scopeExecution, NUMBER_OF_INSTANCES, nrOfInstances + 1); setLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES, 1); } return scopeExecution; } @Override public void destroyInnerInstance(ActivityExecution scopeExecution) { removeLoopVariable(scopeExecution, LOOP_COUNTER); int nrOfActiveInstances = getLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES); setLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES, nrOfActiveInstances - 1); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\SequentialMultiInstanceActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderInfo { @Id @Column(name = "order_id") private Long orderID; @Column(name = "user_id") private String userID; @Column(name = "quantity") private Integer orderQuantity; public OrderInfo() { super(); } public OrderInfo(Integer orderQuantity, String userID, Long orderID) { this.orderQuantity = orderQuantity; this.userID = userID; this.orderID = orderID; } public Long getOrderID() { return orderID;
} public void setOrderID(Long orderID) { this.orderID = orderID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public Integer getOrderQuantity() { return orderQuantity; } public void setOrderQuantity(Integer orderQuantity) { this.orderQuantity = orderQuantity; } }
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\java\com\baeldung\spring\ai\om\OrderInfo.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteBatchByIds(String ids) { LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); //根据用户id和阅读表的id获取所有阅读的数据 List<String> sendIds = sysAnnouncementSendMapper.getReadAnnSendByUserId(Arrays.asList(ids.split(SymbolConstant.COMMA)),sysUser.getId()); if(CollectionUtil.isNotEmpty(sendIds)){ this.removeByIds(sendIds); } } /** * 根据busId更新阅读状态 * @param busId * @param busType */ @Override
public void updateReadFlagByBusId(String busId, String busType) { SysAnnouncement announcement = sysAnnouncementMapper.selectOne(new QueryWrapper<SysAnnouncement>().eq("bus_type",busType).eq("bus_id",busId)); if(oConvertUtils.isNotEmpty(announcement)){ LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal(); String userId = sysUser.getId(); LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda(); updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG); updateWrapper.set(SysAnnouncementSend::getReadTime, new Date()); updateWrapper.eq(SysAnnouncementSend::getAnntId,announcement.getId()); updateWrapper.eq(SysAnnouncementSend::getUserId,userId); SysAnnouncementSend announcementSend = new SysAnnouncementSend(); sysAnnouncementSendMapper.update(announcementSend, updateWrapper); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysAnnouncementSendServiceImpl.java
2
请完成以下Java代码
public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } public org.compiere.model.I_M_InOutLine getRef_InOutLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getRef_InOutLine_ID(), get_TrxName()); } /** Set Referenced Shipment Line. @param Ref_InOutLine_ID Referenced Shipment Line */ public void setRef_InOutLine_ID (int Ref_InOutLine_ID) { if (Ref_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, Integer.valueOf(Ref_InOutLine_ID)); } /** Get Referenced Shipment Line. @return Referenced Shipment Line */ public int getRef_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InOutLine getReversalLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getReversalLine_ID(), get_TrxName()); } /** Set Reversal Line. @param ReversalLine_ID Use to keep the reversal line ID for reversing costing purpose */ public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null); else set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Reversal Line. @return Use to keep the reversal line ID for reversing costing purpose */ public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Verworfene Menge. @param ScrappedQty Durch QA verworfene Menge */ public void setScrappedQty (BigDecimal ScrappedQty) { set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return Durch QA verworfene Menge */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge. @param TargetQty Zielmenge der Warenbewegung */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Zielmenge der Warenbewegung */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java
1
请完成以下Java代码
public class CountryAttributeGenerator extends AbstractAttributeValueGenerator { @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_List; } /** * @return <code>false</code>, because "country" is a List attribute. */ @Override public boolean canGenerateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute) { return false; }
@Override public AttributeListValue generateAttributeValue(Properties ctx, int tableId, int recordId, boolean isSOTrx, String trxName) { Check.assume(I_C_Country.Table_ID == tableId, "Wrong table."); final I_C_Country country = InterfaceWrapperHelper.create(ctx, recordId, I_C_Country.class, trxName); final AttributeId attributeId = Services.get(ICountryAttributeDAO.class).retrieveCountryAttributeId(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)); return Services.get(IAttributeDAO.class).createAttributeValue(AttributeListValueCreateRequest.builder() .attributeId(attributeId) .value(country.getCountryCode()) .name(country.getName()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\CountryAttributeGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id") private Author author; @OneToMany(cascade = CascadeType.ALL, mappedBy = "book", orphanRemoval = true) private List<Review> reviews = new ArrayList<>(); public void addReview(Review review) { this.reviews.add(review); review.setBook(this); } public void removeReview(Review review) { review.setBook(null); this.reviews.remove(review); } public void removeReviews() { Iterator<Review> iterator = this.reviews.iterator(); while (iterator.hasNext()) { Review review = iterator.next(); review.setBook(null); iterator.remove(); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public List<Review> getReviews() { return reviews; }
public void setReviews(List<Review> reviews) { this.reviews = reviews; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public static PublicKeyCredentialUserEntityBuilder builder() { return new PublicKeyCredentialUserEntityBuilder(); } /** * Used to build {@link PublicKeyCredentialUserEntity}. * * @author Rob Winch * @since 6.4 */ public static final class PublicKeyCredentialUserEntityBuilder { @SuppressWarnings("NullAway.Init") private String name; @SuppressWarnings("NullAway.Init") private Bytes id; private @Nullable String displayName; private PublicKeyCredentialUserEntityBuilder() { } /** * Sets the {@link #getName()} property. * @param name the name * @return the {@link PublicKeyCredentialUserEntityBuilder} */ public PublicKeyCredentialUserEntityBuilder name(String name) { this.name = name; return this; } /** * Sets the {@link #getId()} property. * @param id the id * @return the {@link PublicKeyCredentialUserEntityBuilder} */ public PublicKeyCredentialUserEntityBuilder id(Bytes id) { this.id = id;
return this; } /** * Sets the {@link #getDisplayName()} property. * @param displayName the display name * @return the {@link PublicKeyCredentialUserEntityBuilder} */ public PublicKeyCredentialUserEntityBuilder displayName(String displayName) { this.displayName = displayName; return this; } /** * Builds a new {@link PublicKeyCredentialUserEntity} * @return a new {@link PublicKeyCredentialUserEntity} */ public PublicKeyCredentialUserEntity build() { return new ImmutablePublicKeyCredentialUserEntity(this.name, this.id, this.displayName); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutablePublicKeyCredentialUserEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class ResultBody { private String code; private String message; private Object result; public ResultBody() { } public ResultBody(BaseErrorInfoInterface errorInfo) { this.code = errorInfo.getResultCode(); this.message = errorInfo.getResultMsg(); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public static ResultBody success() { return success(null); } public static ResultBody success(Object data) { ResultBody rb = new ResultBody(); rb.setCode(CommonEnum.SUCCESS.getResultCode()); rb.setMessage(CommonEnum.SUCCESS.getResultMsg()); rb.setResult(data); return rb; }
public static ResultBody error(BaseErrorInfoInterface errorInfo) { ResultBody rb = new ResultBody(); rb.setCode(errorInfo.getResultCode()); rb.setMessage(errorInfo.getResultMsg()); rb.setResult(null); return rb; } public static ResultBody error(String code, String message) { ResultBody rb = new ResultBody(); rb.setCode(code); rb.setMessage(message); rb.setResult(null); return rb; } public static ResultBody error( String message) { ResultBody rb = new ResultBody(); rb.setCode("-1"); rb.setMessage(message); rb.setResult(null); return rb; } @Override public String toString() { return JSONObject.toJSONString(this); } }
repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\ResultBody.java
2
请完成以下Java代码
public class Student { private String firstName; private String lastName; private List<String> addresses; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Student(String firstName, String lastName, List<String> addresses) { super(); this.firstName = firstName; this.lastName = lastName; this.addresses = addresses; } public String getFirstName() { return this.firstName; }
public String getLastName() { return this.lastName; } public List<String> getAddresses() { return addresses; } public void setAddresses(List<String> addresses) { this.addresses = addresses; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } }
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\eclipsecollections\Student.java
1
请完成以下Java代码
private ImmutableMap<ShipperId, String> loadShipperInternalNameByIds(@NonNull final IdsRegistry idsRegistry) { if (Check.isEmpty(idsRegistry.getShipperIds())) { return ImmutableMap.of(); } return shipperDAO.getByIds(idsRegistry.getShipperIds()).entrySet() .stream() .filter(entry -> Check.isNotBlank(entry.getValue().getInternalName())) .map(entry -> new HashMap.SimpleImmutableEntry<>(entry.getKey(), entry.getValue().getInternalName())) .collect(ImmutableMap.toImmutableMap(HashMap.SimpleImmutableEntry::getKey, HashMap.SimpleImmutableEntry::getValue)); } private void setShipperInternalName( @NonNull final JsonResponseShipmentCandidateBuilder candidateBuilder, @NonNull final ShipmentSchedule shipmentSchedule, @NonNull final Map<ShipperId, String> shipperId2InternalName) { final ShipperId shipperId = shipmentSchedule.getShipperId(); if (shipperId == null) { return;// nothing to do } candidateBuilder.shipperInternalSearchKey(shipperId2InternalName.get(shipperId)); } private void setOrderReferences( @NonNull final JsonResponseShipmentCandidateBuilder candidateBuilder, @NonNull final ShipmentSchedule shipmentSchedule, @NonNull final Map<OrderId, I_C_Order> id2Order) { final OrderId orderId = shipmentSchedule.getOrderAndLineId() != null ? shipmentSchedule.getOrderAndLineId().getOrderId() : null; if (orderId == null) { return; // nothing to do } final I_C_Order orderRecord = id2Order.get(orderId);
if (orderRecord == null) { Loggables.withLogger(logger, Level.WARN).addLog("*** WARNING: No I_C_Order was found in id2Order: {} for orderId: {}!", id2Order, orderId); return; } candidateBuilder.orderDocumentNo(orderRecord.getDocumentNo()); candidateBuilder.poReference(orderRecord.getPOReference()); candidateBuilder.deliveryInfo(orderRecord.getDeliveryInfo()); } private static class ShipmentCandidateExportException extends AdempiereException { public ShipmentCandidateExportException(final String message) { super(message); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentCandidateAPIService.java
1
请完成以下Java代码
public void onInit(final ICalloutRecord calloutRecord) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if(gridTab == null) { return; } final ISideActionsGroupsListModel sideActionsGroupsModel = gridTab.getSideActionsGroupsModel(); // // Add action: Create purchase orders { action_CreatePurchaseOrders = new PMM_CreatePurchaseOrders_Action(gridTab); sideActionsGroupsModel .getGroupById(GridTab.SIDEACTIONS_Actions_GroupId) .addAction(action_CreatePurchaseOrders); } // // Setup facet filtering engine { gridTabFacetExecutor = new FacetExecutor<>(I_PMM_PurchaseCandidate.class); // Current facets will be displayed in GridTab's right-side panel final IFacetsPool<I_PMM_PurchaseCandidate> facetsPool = new SideActionFacetsPool<>(sideActionsGroupsModel); gridTabFacetExecutor.setFacetsPool(facetsPool); // The datasource which will be filtered by our facets is actually THIS grid tab final IFacetFilterable<I_PMM_PurchaseCandidate> facetFilterable = new GridTabFacetFilterable<>(I_PMM_PurchaseCandidate.class, gridTab); gridTabFacetExecutor.setFacetFilterable(facetFilterable); // We will use service registered collectors to collect the facets from our rows final IFacetCollector<I_PMM_PurchaseCandidate> facetCollectors = Services.get(IPurchaseCandidateFacetCollectorFactory.class).createFacetCollectors(); gridTabFacetExecutor.addFacetCollector(facetCollectors); } } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { updateFacets(calloutRecord); } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { // NOTE: we are not updating the facets on refresh all because following case would fail:
// Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid, // but user is not expecting to have all it's facets reset. // updateFacets(gridTab); } /** * Retrieve facets from current grid tab rows and add them to window side panel * * @param calloutRecord */ private void updateFacets(final ICalloutRecord calloutRecord) { // // If user asked to approve for invoicing some ICs, the grid will be asked to refresh all, // but in this case we don't want to reset current facets and recollect them if (action_CreatePurchaseOrders.isRunning()) { return; } // // Collect the facets from current grid tab rows and fully update the facets pool. gridTabFacetExecutor.collectFacetsAndResetPool(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\callout\PMM_PurchaseCandidate_TabCallout.java
1
请完成以下Java代码
protected ExecutionEntity getContextExecution() { return getEntity().getExecution(); } protected void logVariableOperation(AbstractVariableScope scope) { TaskEntity task = (TaskEntity) scope; commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), null, task.getId(), PropertyChange.EMPTY_CHANGE); } protected void checkSetTaskVariables(TaskEntity task) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateTaskVariable(task); } } protected void onLocalVariableChanged() { taskLocalVariablesUpdated = true; }
@Override public void onCreate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) { onLocalVariableChanged(); } @Override public void onDelete(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) { onLocalVariableChanged(); } @Override public void onUpdate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) { onLocalVariableChanged(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetTaskVariablesCmd.java
1
请完成以下Java代码
public DateTimePeriodDetails getFrToDt() { return frToDt; } /** * Sets the value of the frToDt property. * * @param value * allowed object is * {@link DateTimePeriodDetails } * */ public void setFrToDt(DateTimePeriodDetails value) { this.frToDt = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } *
*/ public void setRsn(String value) { this.rsn = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 } * */ public TaxCharges2 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomerReturnLineCandidate { @NonNull OrgId orgId; @NonNull ProductId productId; @NonNull Quantity returnedQty; @NonNull BPartnerLocationId bPartnerLocationId; @NonNull ReturnedGoodsWarehouseType returnedGoodsWarehouseType; @Nullable LocalDate movementDate; @Nullable ZonedDateTime dateReceived; @Nullable
List<CreateAttributeInstanceReq> createAttributeInstanceReqs; @Nullable String externalResourceURL; @Nullable InOutLineId originalShipmentInOutLineId; @Nullable OrderId orderId; @Nullable String externalId; @Nullable HUPIItemProductId hupiItemProductId; @Nullable QtyTU returnedTUQty; }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnLineCandidate.java
2
请完成以下Java代码
public final class MDiscountSchemaImportContext { private I_I_DiscountSchema previousImportRecord = null; private List<I_I_DiscountSchema> previousImportRecordsForSameDiscountSchema = new ArrayList<>(); public I_I_DiscountSchema getPreviousImportRecord() { return previousImportRecord; } public void setPreviousImportRecord(final I_I_DiscountSchema previousImportRecord) { this.previousImportRecord = previousImportRecord; } public int getPreviousM_DiscountSchema_ID() { return previousImportRecord == null ? -1 : previousImportRecord.getM_DiscountSchema_ID(); }
public int getPreviousBPartnerId() { return previousImportRecord == null ? -1 : previousImportRecord.getC_BPartner_ID(); } public List<I_I_DiscountSchema> getPreviousImportRecordsForSameDiscountSchema() { return previousImportRecordsForSameDiscountSchema; } public void clearPreviousRecordsForSameDiscountSchema() { previousImportRecordsForSameDiscountSchema = new ArrayList<>(); } public void collectImportRecordForSameDiscountSchema(final I_I_DiscountSchema importRecord) { previousImportRecordsForSameDiscountSchema.add(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\impexp\MDiscountSchemaImportContext.java
1
请完成以下Java代码
public String getAuthorizationUri() { return this.authorizationUri; } /** * Returns the client identifier. * @return the client identifier */ public String getClientId() { return this.clientId; } /** * Returns the state. * @return the state */ public String getState() { return this.state; }
/** * Returns the requested (or authorized) scope(s). * @return the requested (or authorized) scope(s), or an empty {@code Set} if not * available */ public Set<String> getScopes() { return this.scopes; } /** * Returns the additional parameters. * @return the additional parameters, or an empty {@code Map} if not available */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationConsentAuthenticationToken.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } public Map<String, VariableInstanceEntity> getVariableInstanceEntities() { ensureVariableInstancesInitialized(); return variableInstances; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public String getCategory() { return category; } public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public Map<String, Object> getTaskLocalVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables; } public Date getClaimTime() { return claimTime; } public void setClaimTime(Date claimTime) { this.claimTime = claimTime; } public Integer getAppVersion() { return this.appVersion; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public String toString() { return "Task[id=" + id + ", name=" + name + "]"; } private String truncate(String string, int maxLength) { if (string != null) { return string.length() > maxLength ? string.substring(0, maxLength) : string; } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class GS1Element { private static final DateTimeFormatter LOCAL_DATE_PATTERN = DateTimeFormatter.ofPattern("yyMMdd"); @Nullable GS1ApplicationIdentifier identifier; @NonNull String key; @NonNull Object value; public String getValueAsString() {return value.toString();} public BigDecimal getValueAsBigDecimal() {return NumberUtils.asBigDecimal(value);} public LocalDate getValueAsLocalDate() { if (value instanceof LocalDateTime) { return ((LocalDateTime)value).toLocalDate(); }
else if (value instanceof LocalDate) { return (LocalDate)value; } else { try { return LocalDate.parse(value.toString(), LOCAL_DATE_PATTERN); } catch (Exception ex) { throw new AdempiereException("Invalid LocalDate GS1 element: " + value + " (" + value.getClass() + ")", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1Element.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @PostMapping() private Mono<UserData> createEmployee(@RequestBody CreateUserData createUserData) { return userService.create(createUserData); } @GetMapping("/{id}") private Mono<UserData> getEmployeeById(@PathVariable String id) { return userService.getEmployee(id); } @GetMapping private Flux<UserData> getAllEmployees() { return userService.getAll(); } @PutMapping() private Mono<UserData> updateEmployee(@RequestBody UserData employee) { return userService.update(employee); } @DeleteMapping("/{id}")
private Mono<UserData> deleteEmployee(@PathVariable String id) { return userService.delete(id); } @PutMapping("/create/{n}") private void createUsersBulk(@PathVariable Integer n) { userService.createUsersBulk(n); } @GetMapping(value = "/stream", produces = MediaType.APPLICATION_STREAM_JSON_VALUE) private Flux<UserData> streamAllEmployees() { return Flux.from(userService.getAllStream()); } }
repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\controller\UserController.java
2
请完成以下Java代码
protected String doIt() throws Exception { final I_C_DocType docType = docTypeDAO.getById(p_C_DocType_ID); final DocBaseAndSubType docBaseAndSubType = DocBaseAndSubType.of(X_C_DocType.DOCBASETYPE_ARInvoice, docType.getDocSubType()); final AdjustmentChargeCreateRequest adjustmentChargeCreateRequest = AdjustmentChargeCreateRequest.builder() .invoiceID(InvoiceId.ofRepoId(getRecord_ID())) .docBaseAndSubTYpe(docBaseAndSubType) .build(); invoiceBL.adjustmentCharge(adjustmentChargeCreateRequest); return MSG_OK; } @Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\process\CreateAdjustmentChargeFromInvoice.java
1
请完成以下Java代码
public final class EncodingUtils { private EncodingUtils() { } /** * Combine the individual byte arrays into one array. */ public static byte[] concatenate(byte[]... arrays) { int length = 0; for (byte[] array : arrays) { length += array.length; } byte[] newArray = new byte[length]; int destPos = 0; for (byte[] array : arrays) { System.arraycopy(array, 0, newArray, destPos, array.length); destPos += array.length; } return newArray; }
/** * Extract a sub array of bytes out of the byte array. * @param array the byte array to extract from * @param beginIndex the beginning index of the sub array, inclusive * @param endIndex the ending index of the sub array, exclusive */ public static byte[] subArray(byte[] array, int beginIndex, int endIndex) { int length = endIndex - beginIndex; byte[] subarray = new byte[length]; System.arraycopy(array, beginIndex, subarray, 0, length); return subarray; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\util\EncodingUtils.java
1
请在Spring Boot框架中完成以下Java代码
public final class ProductsToPickRowId { ProductId productId; ShipmentScheduleId shipmentScheduleId; HuId pickFromHUId; PPOrderId pickFromPickingOrderId; PPOrderBOMLineId issueToOrderBOMLineId; @Getter(AccessLevel.NONE) DocumentId documentId; @Builder private ProductsToPickRowId( @NonNull final ProductId productId, @NonNull ShipmentScheduleId shipmentScheduleId, @Nullable final HuId pickFromHUId, @Nullable final PPOrderId pickFromPickingOrderId, @Nullable final PPOrderBOMLineId issueToOrderBOMLineId) { this.productId = productId; this.shipmentScheduleId = shipmentScheduleId; this.pickFromHUId = pickFromHUId; this.pickFromPickingOrderId = pickFromPickingOrderId; this.issueToOrderBOMLineId = issueToOrderBOMLineId; this.documentId = createDocumentId(productId, shipmentScheduleId, pickFromHUId, pickFromPickingOrderId, issueToOrderBOMLineId); } private static DocumentId createDocumentId( @NonNull final ProductId productId, @NonNull final ShipmentScheduleId shipmentScheduleId, @Nullable final HuId pickFromHUId,
@Nullable PPOrderId pickFromPickingOrderId, @Nullable final PPOrderBOMLineId issueToOrderBOMLineId) { final StringBuilder sb = new StringBuilder(); sb.append("P").append(productId.getRepoId()); sb.append("_").append("S").append(shipmentScheduleId.getRepoId()); if (pickFromHUId != null) { sb.append("_").append("HU").append(pickFromHUId.getRepoId()); } if (pickFromPickingOrderId != null) { sb.append("_").append("MO").append(pickFromPickingOrderId.getRepoId()); } if (issueToOrderBOMLineId != null) { sb.append("_").append("BOML").append(issueToOrderBOMLineId.getRepoId()); } return DocumentId.ofString(sb.toString()); } public DocumentId toDocumentId() { return documentId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowId.java
2
请完成以下Java代码
public static String generate() { return new StringBuilder(32).append(format(getIp())).append( format(getJvm())).append(format(getHiTime())).append( format(getLoTime())).append(format(getCount())).toString(); } private static final int IP; static { int ipadd; try { ipadd = toInt(InetAddress.getLocalHost().getAddress()); } catch (Exception e) { ipadd = 0; } IP = ipadd; } private static short counter = (short) 0; private static final int JVM = (int) (System.currentTimeMillis() >>> 8); private final static String format(int intval) { String formatted = Integer.toHexString(intval); StringBuilder buf = new StringBuilder("00000000"); buf.replace(8 - formatted.length(), 8, formatted); return buf.toString(); } private final static String format(short shortval) { String formatted = Integer.toHexString(shortval); StringBuilder buf = new StringBuilder("0000"); buf.replace(4 - formatted.length(), 4, formatted); return buf.toString(); } private final static int getJvm() { return JVM; } private final static short getCount() {
synchronized (UUIDGenerator.class) { if (counter < 0) { counter = 0; } return counter++; } } /** * Unique in a local network */ private final static int getIp() { return IP; } /** * Unique down to millisecond */ private final static short getHiTime() { return (short) (System.currentTimeMillis() >>> 32); } private final static int getLoTime() { return (int) System.currentTimeMillis(); } private final static int toInt(byte[] bytes) { int result = 0; int length = 4; for (int i = 0; i < length; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\UUIDGenerator.java
1
请完成以下Java代码
T getCurrent() { return current; } T getPrevious() { return previous; } double getRouteScore() { return routeScore; } double getEstimatedScore() { return estimatedScore; } void setPrevious(T previous) { this.previous = previous; } void setRouteScore(double routeScore) { this.routeScore = routeScore; } void setEstimatedScore(double estimatedScore) { this.estimatedScore = estimatedScore; }
@Override public int compareTo(RouteNode other) { if (this.estimatedScore > other.estimatedScore) { return 1; } else if (this.estimatedScore < other.estimatedScore) { return -1; } else { return 0; } } @Override public String toString() { return new StringJoiner(", ", RouteNode.class.getSimpleName() + "[", "]").add("current=" + current) .add("previous=" + previous).add("routeScore=" + routeScore).add("estimatedScore=" + estimatedScore) .toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\astar\RouteNode.java
1
请完成以下Java代码
private @NonNull ObjectMapper newObjectMapper() { return new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true) .findAndRegisterModules(); } /** * Returns a reference to the configured Jackson {@link ObjectMapper} used by this {@link Converter} * to convert {@link String JSON} into an {@link Object} (POJO). * * @return a reference to the configured Jackson {@link ObjectMapper}. */ protected @NonNull ObjectMapper getObjectMapper() { return this.objectMapper; } /** * Converts from {@link String JSON} to an {@link Object} (POJO) using Jackson's {@link ObjectMapper}. * * @param json {@link String} containing {@literal JSON} to convert. * @return an {@link Object} (POJO) converted from the given {@link String JSON}. * @see #getObjectMapper() */ @Override public @Nullable Object convert(@Nullable String json) { if (StringUtils.hasText(json)) { String objectTypeName = null; try { ObjectMapper objectMapper = getObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); if (isPojo(jsonNode)) { return ((POJONode) jsonNode).getPojo(); } else { Assert.state(jsonNode.isObject(), () -> String.format("The JSON [%s] must be an object", json)); Assert.state(jsonNode.has(AT_TYPE_FIELD_NAME), () -> String.format("The JSON object [%1$s] must have an '%2$s' metadata field", json, AT_TYPE_FIELD_NAME)); objectTypeName = jsonNode.get(AT_TYPE_FIELD_NAME).asText(); Class<?> objectType = ClassUtils.forName(objectTypeName, Thread.currentThread().getContextClassLoader());
return objectMapper.readValue(json, objectType); } } catch (ClassNotFoundException cause) { throw new MappingException(String.format("Failed to map JSON [%1$s] to an Object of type [%2$s]", json, objectTypeName), cause); } catch (JsonProcessingException cause) { throw new DataRetrievalFailureException(String.format("Failed to read JSON [%s]", json), cause); } } return null; } /** * Null-safe method to determine whether the given {@link JsonNode} represents a {@link Object POJO}. * * @param jsonNode {@link JsonNode} to evaluate. * @return a boolean value indicating whether the given {@link JsonNode} represents a {@link Object POJO}. * @see com.fasterxml.jackson.databind.JsonNode */ boolean isPojo(@Nullable JsonNode jsonNode) { return jsonNode != null && (jsonNode instanceof POJONode || jsonNode.isPojo() || JsonNodeType.POJO.equals(jsonNode.getNodeType())); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToObjectConverter.java
1
请完成以下Java代码
public int createMeasures (MSLACriteria criteria) { int counter = 0; MSLAGoal[] goals = criteria.getGoals(); for (int i = 0; i < goals.length; i++) { MSLAGoal goal = goals[i]; if (goal.isActive()) counter += createMeasures (goal); } return counter; } // createMeasures /** * Calculate Goal Actual from unprocessed Measures of the Goal * @param criteria SLA criteria */ public void calculateMeasures (MSLACriteria criteria)
{ MSLAGoal[] goals = criteria.getGoals(); for (int i = 0; i < goals.length; i++) { MSLAGoal goal = goals[i]; if (goal.isActive()) { goal.setMeasureActual(calculateMeasure(goal)); goal.setDateLastRun(new Timestamp(System.currentTimeMillis())); goal.save(); } } } // calculateMeasures } // SLACriteria
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\sla\SLACriteria.java
1
请完成以下Java代码
public static MetasfreshId ofOrNull(@Nullable final JsonMetasfreshId id) { if (id == null) { return null; } return of(id); } public static MetasfreshId of(@NonNull final RepoIdAware id) { return new MetasfreshId(id.getRepoId()); } public static MetasfreshId ofNullable(@Nullable final RepoIdAware id) { return id != null ? new MetasfreshId(id.getRepoId()) : null; } public static int toValue(@Nullable final MetasfreshId id) { if (id == null) { return -1; } return id.getValue(); } @JsonCreator private MetasfreshId(final int value) { this.value = Check.assumeGreaterOrEqualToZero(value, "value"); // zero occurs when e.g. an AD_was created by the system-user } @JsonValue public int getValue() {
return value; } public boolean isEqualTo(@Nullable final RepoIdAware otherId) { if (otherId == null) { return false; } return otherId.getRepoId() == value; } public static boolean equals(@Nullable final MetasfreshId id1, @Nullable final MetasfreshId id2) { return Objects.equals(id1, id2); } @NonNull public <T extends RepoIdAware> T mapToRepoId(@NonNull final Function<Integer, T> mappingFunction) { return mappingFunction.apply(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\MetasfreshId.java
1
请在Spring Boot框架中完成以下Java代码
public void setDepartment(String value) { this.department = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the phone property. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) {
this.phone = value; } /** * Gets the value of the personId property. * * @return * possible object is * {@link String } * */ public String getPersonId() { return personId; } /** * Sets the value of the personId property. * * @param value * allowed object is * {@link String } * */ public void setPersonId(String value) { this.personId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\PersonalDelivery.java
2
请完成以下Java代码
public Stream<PPOrderLineRow> streamByIds(final DocumentIdsSelection documentIds) { return getData().streamByIds(documentIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO: notifyRecordsChanged: identify the sub-trees which could be affected and invalidate only those } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { if (docStatus.isCompleted()) { return additionalRelatedProcessDescriptors; } else { return ImmutableList.of(); } } @Override public void invalidateAll()
{ invalidateAllNoNotify(); ViewChangesCollector.getCurrentOrAutoflush() .collectFullyChanged(this); } private void invalidateAllNoNotify() { dataSupplier.invalidate(); } private PPOrderLinesViewData getData() { return dataSupplier.getData(); } @Override public boolean isConsiderTableRelatedProcessDescriptors(@NonNull final ProcessHandlerType processHandlerType, final @NonNull DocumentIdsSelection selectedRowIds) { return ProcessHandlerType.equals(processHandlerType, HUReportProcessInstancesRepository.PROCESS_HANDLER_TYPE); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesView.java
1
请完成以下Java代码
protected CaptchaUsernamePasswordToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); String captcha = getCaptcha(request); boolean rememberMe = isRememberMe(request); String host = getHost(request); return new CaptchaUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha); } public String getCaptchaParam() { return captchaParam; }
public void setCaptchaParam(String captchaParam) { this.captchaParam = captchaParam; } protected String getCaptcha(ServletRequest request) { return WebUtils.getCleanParam(request, getCaptchaParam()); } //保存异常对象到request @Override protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { request.setAttribute(getFailureKeyAttribute(), ae); } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\shiro\KaptchaFilter.java
1
请完成以下Java代码
public class LoadMojo extends AbstractFileJasyptMojo { private static final Logger LOGGER = LoggerFactory.getLogger(LoadMojo.class); /** * Prefix that will be added before name of each property. Can be useful for distinguishing the * source of the properties from other maven properties. */ @Parameter(property = "jasypt.plugin.keyPrefix") private String keyPrefix = null; @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** {@inheritDoc} */ @Override protected void run(final EncryptionService service, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException { Properties properties = service.getEncryptableProperties(); FileService.load(path, properties); if (properties.isEmpty()) { LOGGER.info(" No properties found");
} else { for (String key : properties.stringPropertyNames()) { LOGGER.info(" Loaded '" + key + "' property"); } } Properties projectProperties = project.getProperties(); for (String key : properties.stringPropertyNames()) { if (keyPrefix != null) { projectProperties.put(keyPrefix + key, properties.get(key)); } else { projectProperties.put(key, properties.get(key)); } } } }
repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\LoadMojo.java
1
请完成以下Java代码
public int toIntValue() { return this.intValue; } /** * Converts the integer representation of the data type into a {@link MetricDataType} instance. * * @param i the integer representation of the data type. * @return a {@link MetricDataType} instance. */ public static MetricDataType fromInteger(int i) { switch (i) { case 1: return Int8; case 2: return Int16; case 3: return Int32; case 4: return Int64; case 5: return UInt8; case 6: return UInt16; case 7: return UInt32; case 8: return UInt64; case 9: return Float; case 10: return Double; case 11: return Boolean; case 12: return String; case 13: return DateTime; case 14: return Text; case 15: return UUID; case 16: return DataSet; case 17: return Bytes; case 18: return File; case 19: return Template; case 20: return PropertySet;
case 21: return PropertySetList; case 22: return Int8Array; case 23: return Int16Array; case 24: return Int32Array; case 25: return Int64Array; case 26: return UInt8Array; case 27: return UInt16Array; case 28: return UInt32Array; case 29: return UInt64Array; case 30: return FloatArray; case 31: return DoubleArray; case 32: return BooleanArray; case 33: return StringArray; case 34: return DateTimeArray; default: return Unknown; } } /** * @return the class type for this DataType */ public Class<?> getClazz() { return clazz; } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\MetricDataType.java
1
请完成以下Java代码
public class App02HelloWorldSpring { public static void main(String[] args) { //1: Launch a Spring Context try(var context = new AnnotationConfigApplicationContext (HelloWorldConfiguration.class)) { //2: Configure the things that we want Spring to manage - //HelloWorldConfiguration - @Configuration //name - @Bean //3: Retrieving Beans managed by Spring System.out.println(context.getBean("name")); System.out.println(context.getBean("age")); System.out.println(context.getBean("person")); System.out.println(context.getBean("person2MethodCall")); System.out.println(context.getBean("person3Parameters"));
System.out.println(context.getBean("address2")); System.out.println(context.getBean(Person.class)); System.out.println(context.getBean(Address.class)); System.out.println(context.getBean("person5Qualifier")); //System.out.println // Arrays.stream(context.getBeanDefinitionNames()) // .forEach(System.out::println); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-01\src\main\java\com\in28minutes\learnspringframework\helloworld\App02HelloWorldSpring.java
1
请在Spring Boot框架中完成以下Java代码
public int leftValency(int head) { return leftValency[head]; } public int getHead(int index) { if (arcs[index] != null) return arcs[index].headIndex; return -1; } public int getDependent(int index) { if (arcs[index] != null) return arcs[index].relationId; return -1; } public void setMaxSentenceSize(int maxSentenceSize) { this.maxSentenceSize = maxSentenceSize; } public void incrementBufferHead() { if (bufferHead == maxSentenceSize) bufferHead = -1; else bufferHead++; } public void setBufferHead(int bufferHead) { this.bufferHead = bufferHead; } @Override public State clone() { State state = new State(arcs.length - 1); state.stack = new ArrayDeque<Integer>(stack); for (int dependent = 0; dependent < arcs.length; dependent++) { if (arcs[dependent] != null) {
Edge head = arcs[dependent]; state.arcs[dependent] = head; int h = head.headIndex; if (rightMostArcs[h] != 0) { state.rightMostArcs[h] = rightMostArcs[h]; state.rightValency[h] = rightValency[h]; state.rightDepLabels[h] = rightDepLabels[h]; } if (leftMostArcs[h] != 0) { state.leftMostArcs[h] = leftMostArcs[h]; state.leftValency[h] = leftValency[h]; state.leftDepLabels[h] = leftDepLabels[h]; } } } state.rootIndex = rootIndex; state.bufferHead = bufferHead; state.maxSentenceSize = maxSentenceSize; state.emptyFlag = emptyFlag; return state; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\State.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomerExtensionType { @XmlElement(name = "Department") protected String department; @XmlElement(name = "CustomerReferenceNumber") protected String customerReferenceNumber; @XmlElement(name = "FiscalNumber") protected String fiscalNumber; /** * Department at the customer's side. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the customerReferenceNumber property. * * @return * possible object is * {@link String } * */ public String getCustomerReferenceNumber() { return customerReferenceNumber; } /** * Sets the value of the customerReferenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setCustomerReferenceNumber(String value) {
this.customerReferenceNumber = value; } /** * Fiscal number of the customer * * @return * possible object is * {@link String } * */ public String getFiscalNumber() { return fiscalNumber; } /** * Sets the value of the fiscalNumber property. * * @param value * allowed object is * {@link String } * */ public void setFiscalNumber(String value) { this.fiscalNumber = 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\CustomerExtensionType.java
2
请完成以下Java代码
public boolean matchesTableName(@NonNull final String tableName) { return matches(recordRef -> tableName.equals(recordRef.getTableName())); } public Stream<TableRecordReference> streamByTableName(@NonNull final String tableName) { return recordRefs.stream().filter(recordRef -> tableName.equals(recordRef.getTableName())); } public ListMultimap<AdTableId, Integer> extractTableId2RecordIds() { final ImmutableListMultimap<AdTableId, TableRecordReference> tableName2References = Multimaps.index(recordRefs, TableRecordReference::getAdTableId); return Multimaps.transformValues(tableName2References, TableRecordReference::getRecord_ID); } public <T extends RepoIdAware> Stream<T> streamIds(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper) { return streamByTableName(tableName) .mapToInt(TableRecordReference::getRecord_ID) .mapToObj(idMapper); } public <T extends RepoIdAware> ImmutableSet<T> getRecordIdsByTableName(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper) { return streamIds(tableName, idMapper).collect(ImmutableSet.toImmutableSet()); } public String getSingleTableName() { final ImmutableSet<String> tableNames = recordRefs.stream() .map(TableRecordReference::getTableName) .collect(ImmutableSet.toImmutableSet()); if (tableNames.isEmpty()) { throw new AdempiereException("No tablename"); } else if (tableNames.size() == 1) { return tableNames.iterator().next(); } else { throw new AdempiereException("More than one tablename found: " + tableNames); } } public Set<TableRecordReference> toSet() {return recordRefs;} public Set<Integer> toIntSet() { // just to make sure that our records are from a single table getSingleTableName(); return recordRefs.stream() .map(TableRecordReference::getRecord_ID) .collect(ImmutableSet.toImmutableSet()); } public int size() { return recordRefs.size();
} @NonNull public AdTableId getSingleTableId() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() == 1) { return tableIds.iterator().next(); } else { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public void assertSingleTableName() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() != 1) { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public Stream<TableRecordReference> streamReferences() { return recordRefs.stream(); } @NonNull private ImmutableSet<AdTableId> getTableIds() { return recordRefs.stream() .map(TableRecordReference::getAD_Table_ID) .map(AdTableId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReferenceSet.java
1
请完成以下Java代码
public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public String getScode() { return securityNumber; } public void setScode(String scode) { this.securityNumber = scode; } public String getDcode() {
return departmentCode; } public void setDcode(String dcode) { this.departmentCode = dcode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\uniqueconstraints\Person.java
1
请完成以下Java代码
public class Demo04Message implements Serializable { public static final String QUEUE_BASE = "QUEUE_DEMO_04-"; public static final String QUEUE_0 = QUEUE_BASE + "0"; public static final String QUEUE_1 = QUEUE_BASE + "1"; public static final String QUEUE_2 = QUEUE_BASE + "2"; public static final String QUEUE_3 = QUEUE_BASE + "3"; public static final int QUEUE_COUNT = 4; /** * 编号 */ private Integer id; public Demo04Message setId(Integer id) { this.id = id;
return this; } public Integer getId() { return id; } @Override public String toString() { return "Demo04Message{" + "id=" + id + '}'; } }
repos\SpringBoot-Labs-master\lab-32\lab-32-activemq-demo-orderly\src\main\java\cn\iocoder\springboot\lab32\activemqdemo\message\Demo04Message.java
1
请完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * HU_UnitType AD_Reference_ID=540472 * Reference name: HU_UnitType */ public static final int HU_UNITTYPE_AD_Reference_ID=540472; /** TransportUnit = TU */ public static final String HU_UNITTYPE_TransportUnit = "TU"; /** LoadLogistiqueUnit = LU */ public static final String HU_UNITTYPE_LoadLogistiqueUnit = "LU"; /** VirtualPI = V */ public static final String HU_UNITTYPE_VirtualPI = "V"; @Override public void setHU_UnitType (final @Nullable java.lang.String HU_UnitType) { set_Value (COLUMNNAME_HU_UnitType, HU_UnitType); } @Override public java.lang.String getHU_UnitType() { return get_ValueAsString(COLUMNNAME_HU_UnitType); } @Override public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID) { if (M_HU_PackagingCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID); }
@Override public int getM_HU_PackagingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override public void setPackagingCode (final java.lang.String PackagingCode) { set_Value (COLUMNNAME_PackagingCode, PackagingCode); } @Override public java.lang.String getPackagingCode() { return get_ValueAsString(COLUMNNAME_PackagingCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackagingCode.java
1
请完成以下Java代码
public String getByteArrayId() { return byteArrayId; } public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } public String getScopeActivityInstanceId() { return scopeActivityInstanceId; } public void setScopeActivityInstanceId(String scopeActivityInstanceId) { this.scopeActivityInstanceId = scopeActivityInstanceId; } public void setInitial(Boolean isInitial) { this.isInitial = isInitial; } public Boolean isInitial() { return isInitial; } @Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue
+ ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", scopeActivityInstanceId=" + scopeActivityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", tenantId=" + tenantId + ", isInitial=" + isInitial + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricVariableUpdateEventEntity.java
1
请完成以下Java代码
public void destroy() throws Exception { if (this.taskScheduler != null) { this.taskScheduler.shutdown(); } } /** * Sets the {@link Clock} used when generating one-time token and checking token * expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * The default {@code Function} that maps {@link OneTimeToken} to a {@code List} of * {@link SqlParameterValue}. * * @author Max Batischev * @since 6.4 */ private static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) { List<SqlParameterValue> parameters = new ArrayList<>(); parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue())); parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername())); parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt()))); return parameters;
} } /** * The default {@link RowMapper} that maps the current row in * {@code java.sql.ResultSet} to {@link OneTimeToken}. * * @author Max Batischev * @since 6.4 */ private static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> { @Override public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException { String tokenValue = rs.getString("token_value"); String userName = rs.getString("username"); Instant expiresAt = rs.getTimestamp("expires_at").toInstant(); return new DefaultOneTimeToken(tokenValue, userName, expiresAt); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\JdbcOneTimeTokenService.java
1
请在Spring Boot框架中完成以下Java代码
public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请完成以下Java代码
public void setIsStorageRelevant (final boolean IsStorageRelevant) { set_Value (COLUMNNAME_IsStorageRelevant, IsStorageRelevant); } @Override public boolean isStorageRelevant() { return get_ValueAsBoolean(COLUMNNAME_IsStorageRelevant); } @Override public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public org.compiere.model.I_M_AttributeSearch getM_AttributeSearch() { return get_ValueAsPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class); } @Override public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch) { set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch); } @Override public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_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 setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请完成以下Java代码
private List<I_PP_Product_BOMLine> getBOMLines() { final I_PP_Product_BOM bom = getBOMIfEligible(); if (bom == null) { return ImmutableList.of(); } return bomsRepo.retrieveLines(bom); } private I_PP_Product_BOM getBOMIfEligible() { final I_M_Product bomProduct = productsRepo.getById(bomProductId); if (!bomProduct.isBOM()) { return null; } return bomsRepo.getDefaultBOMByProductId(bomProductId) .filter(this::isEligible) .orElse(null); } private boolean isEligible(final I_PP_Product_BOM bom) {
final BOMType bomType = BOMType.ofNullableCode(bom.getBOMType()); return BOMType.MakeToOrder.equals(bomType); } // // // --- // // public static class BOMPriceCalculatorBuilder { public Optional<BOMPrices> calculate() { return build().calculate(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\BOMPriceCalculator.java
1
请完成以下Java代码
public MSLAMeasure[] getAllMeasures() { String sql = "SELECT * FROM PA_SLA_Measure " + "WHERE PA_SLA_Goal_ID=? " + "ORDER BY DateTrx"; return getMeasures (sql); } // getAllMeasures /** * Get New Measures only * @return array of unprocessed Measures */ public MSLAMeasure[] getNewMeasures() { String sql = "SELECT * FROM PA_SLA_Measure " + "WHERE PA_SLA_Goal_ID=?" + " AND Processed='N' " + "ORDER BY DateTrx"; return getMeasures (sql); } // getNewMeasures /** * Get Measures * @param sql sql * @return array of measures */ private MSLAMeasure[] getMeasures (String sql) { ArrayList<MSLAMeasure> list = new ArrayList<MSLAMeasure>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setInt (1, getPA_SLA_Goal_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add(new MSLAMeasure(getCtx(), rs, get_TrxName())); rs.close (); pstmt.close ();
pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } MSLAMeasure[] retValue = new MSLAMeasure[list.size ()]; list.toArray (retValue); return retValue; } // getMeasures /** * Is the Date in the Valid Range * @param date date * @return true if valid */ public boolean isDateValid (Timestamp date) { if (date == null) return false; if (getValidFrom() != null && date.before(getValidFrom())) return false; if (getValidTo() != null && date.after(getValidTo())) return false; return true; } // isDateValid } // MSLAGoal
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSLAGoal.java
1
请完成以下Java代码
void fixBlock(int blockId) { int begin = blockId * BLOCK_SIZE; int end = begin + BLOCK_SIZE; int unusedOffset = 0; for (int offset = begin; offset != end; ++offset) { if (!extras(offset).isUsed) { unusedOffset = offset; break; } } for (int id = begin; id != end; ++id) { if (!extras(id).isFixed)
{ reserveId(id); int[] units = _units.getBuffer(); // units[id].setLabel(id ^ unused_offset); units[id] = (units[id] & ~0xFF) | ((id ^ unusedOffset) & 0xFF); } } } private AutoIntPool _units = new AutoIntPool(); private DoubleArrayBuilderExtraUnit[] _extras; private AutoBytePool _labels = new AutoBytePool(); private int[] _table; private int _extrasHead; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DoubleArrayBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class FstStatsServiceImpl implements FstStatsService { private final ConcurrentHashMap<String, StatsCounter> encodeCounters = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, StatsCounter> decodeCounters = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Timer> encodeTimers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Timer> decodeTimer = new ConcurrentHashMap<>(); @Autowired private StatsFactory statsFactory; @Override public void incrementEncode(Class<?> clazz) { encodeCounters.computeIfAbsent(clazz.getSimpleName(), key -> statsFactory.createStatsCounter("fst_encode", key)).increment(); } @Override public void incrementDecode(Class<?> clazz) {
decodeCounters.computeIfAbsent(clazz.getSimpleName(), key -> statsFactory.createStatsCounter("fst_decode", key)).increment(); } @Override public void recordEncodeTime(Class<?> clazz, long startTime) { encodeTimers.computeIfAbsent(clazz.getSimpleName(), key -> statsFactory.createTimer("fst_encode_time", "statsName", key)).record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } @Override public void recordDecodeTime(Class<?> clazz, long startTime) { decodeTimer.computeIfAbsent(clazz.getSimpleName(), key -> statsFactory.createTimer("fst_decode_time", "statsName", key)).record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } }
repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\FstStatsServiceImpl.java
2
请完成以下Java代码
public void execute(PvmExecutionImpl execution) { // restore activity instance id if (execution.getActivityInstanceId() == null) { execution.setActivityInstanceId(execution.getParentActivityInstanceId()); } PvmActivity activity = execution.getActivity(); Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping = execution.createActivityExecutionMapping(); PvmExecutionImpl propagatingExecution = execution; if(execution.isScope() && activity.isScope()) { if (!LegacyBehavior.destroySecondNonScope(execution)) { execution.destroy(); if(!execution.isConcurrent()) { execution.remove(); propagatingExecution = execution.getParent(); propagatingExecution.setActivity(execution.getActivity()); } } } propagatingExecution = LegacyBehavior.determinePropagatingExecutionOnEnd(propagatingExecution, activityExecutionMapping); PvmScope flowScope = activity.getFlowScope(); // 1. flow scope = Process Definition if(flowScope == activity.getProcessDefinition()) { // 1.1 concurrent execution => end + tryPrune() if(propagatingExecution.isConcurrent()) { propagatingExecution.remove(); propagatingExecution.getParent().tryPruneLastConcurrentChild(); propagatingExecution.getParent().forceUpdate(); } else { // 1.2 Process End propagatingExecution.setEnded(true); if (!propagatingExecution.isPreserveScope()) { propagatingExecution.performOperation(PROCESS_END); } } } else { // 2. flowScope != process definition PvmActivity flowScopeActivity = (PvmActivity) flowScope; ActivityBehavior activityBehavior = flowScopeActivity.getActivityBehavior(); if (activityBehavior instanceof CompositeActivityBehavior) {
CompositeActivityBehavior compositeActivityBehavior = (CompositeActivityBehavior) activityBehavior; // 2.1 Concurrent execution => composite behavior.concurrentExecutionEnded() if(propagatingExecution.isConcurrent() && !LegacyBehavior.isConcurrentScope(propagatingExecution)) { compositeActivityBehavior.concurrentChildExecutionEnded(propagatingExecution.getParent(), propagatingExecution); } else { // 2.2 Scope Execution => composite behavior.complete() propagatingExecution.setActivity(flowScopeActivity); compositeActivityBehavior.complete(propagatingExecution); } } else { // activity behavior is not composite => this is unexpected throw new ProcessEngineException("Expected behavior of composite scope "+activity +" to be a CompositeActivityBehavior but got "+activityBehavior); } } } public String getCanonicalName() { return "activity-end"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityEnd.java
1
请完成以下Java代码
NestedLocation getLocation() { return this.location; } void connect() throws IOException { synchronized (this) { if (this.zipContent == null) { this.zipContent = ZipContent.open(this.location.path(), this.location.nestedEntryName()); try { connectData(); } catch (IOException | RuntimeException ex) { this.zipContent.close(); this.zipContent = null; throw ex; } } } } private void connectData() throws IOException { CloseableDataBlock data = this.zipContent.openRawZipData(); try { this.size = data.size(); this.inputStream = data.asInputStream(); } catch (IOException | RuntimeException ex) { data.close(); } } InputStream getInputStream() throws IOException { synchronized (this) { if (this.inputStream == null) { throw new IOException("Nested location not found " + this.location); } return this.inputStream; } } long getContentLength() { return this.size; } @Override public void run() { releaseAll(); } private void releaseAll() { synchronized (this) {
if (this.zipContent != null) { IOException exceptionChain = null; try { this.inputStream.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } try { this.zipContent.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } this.size = -1; if (exceptionChain != null) { throw new UncheckedIOException(exceptionChain); } } } } private IOException addToExceptionChain(IOException exceptionChain, IOException ex) { if (exceptionChain != null) { exceptionChain.addSuppressed(ex); return exceptionChain; } return ex; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnectionResources.java
1
请完成以下Java代码
public static class TableHeaderBorder extends javax.swing.border.AbstractBorder { private static final long serialVersionUID = 1L; private final Insets editorBorderInsets = new Insets(2, 2, 2, 2); private final Color borderColor; public TableHeaderBorder(final Color borderColor) { super(); this.borderColor = borderColor; } @Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) { g.translate(x, y); g.setColor(borderColor); g.drawLine(w - 1, 0, w - 1, h - 1); // right line g.drawLine(1, h - 1, w - 1, h - 1); // bottom line
// g.setColor(MetalLookAndFeel.getControlHighlight()); // g.drawLine(0, 0, w - 2, 0); // top line // g.drawLine(0, 0, 0, h - 2); // left line g.translate(-x, -y); } @Override public Insets getBorderInsets(final Component c, final Insets insets) { insets.set(editorBorderInsets.top, editorBorderInsets.left, editorBorderInsets.bottom, editorBorderInsets.right); return insets; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshTheme.java
1
请完成以下Java代码
public static char getDefaultBeginStartModifier() { return begin_start_modifier; } /** What the start modifier should be */ public static char getDefaultEndStartModifier() { return end_start_modifier; } /** What the end modifier should be */ public static char getDefaultBeginEndModifier() { return begin_end_modifier; } /** What the end modifier should be */ public static char getDefaultEndEndModifier() { return end_end_modifier; } /* What character should we use for quoting attributes. */ public static char getDefaultAttributeQuoteChar() { return attribute_quote_char; } /* Should we wrap quotes around an attribute? */ public static boolean getDefaultAttributeQuote() { return attribute_quote; } /** Does this element need a closing tag? */ public static boolean getDefaultEndElement() { return end_element; } /** What codeset are we going to use the default is 8859_1 */ public static String getDefaultCodeset() {
return codeset; } /** position of tag relative to start and end. */ public static int getDefaultPosition() { return position; } /** Default value to set case type */ public static int getDefaultCaseType() { return case_type; } public static char getDefaultStartTag() { return start_tag; } public static char getDefaultEndTag() { return end_tag; } /** Should we print html in a more readable format? */ public static boolean getDefaultPrettyPrint() { return pretty_print; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ECSDefaults.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } @Transactional(readOnly = true) public void fetchAuthorByNameAsEntityJpql() { Author author = authorRepository.findByName("Joana Nimar", Author.class); System.out.println(author); } @Transactional(readOnly = true) public void fetchAuthorByNameAsDtoNameEmailJpql() { AuthorNameEmailDto author = authorRepository.findByName("Joana Nimar", AuthorNameEmailDto.class); System.out.println(author.getEmail() + ", " + author.getName()); } @Transactional(readOnly = true) public void fetchAuthorByNameAsDtoGenreJpql() { AuthorGenreDto author = authorRepository.findByName("Joana Nimar", AuthorGenreDto.class); System.out.println(author.getGenre()); } @Transactional(readOnly = true) public void fetchAuthorByNameAndAgeAsEntityJpql() { Author author = authorRepository.findByNameAndAge("Joana Nimar", 34, Author.class); System.out.println(author); } @Transactional(readOnly = true) public void fetchAuthorByNameAndAgeAsDtoNameEmailJpql() { AuthorNameEmailDto author = authorRepository.findByNameAndAge("Joana Nimar", 34, AuthorNameEmailDto.class); System.out.println(author.getEmail() + ", " + author.getName()); }
@Transactional(readOnly = true) public void fetchAuthorByNameAndAgeAsDtoGenreJpql() { AuthorGenreDto author = authorRepository.findByNameAndAge("Joana Nimar", 34, AuthorGenreDto.class); System.out.println(author.getGenre()); } @Transactional(readOnly = true) public void fetchAuthorsAsEntitiesJpql() { List<Author> authors = authorRepository.findByGenre("Anthology", Author.class); System.out.println(authors); } @Transactional(readOnly = true) public void fetchAuthorsAsDtoJpql() { List<AuthorNameEmailDto> authors = authorRepository.findByGenre("Anthology", AuthorNameEmailDto.class); authors.forEach(a -> System.out.println(a.getName() + ", " + a.getEmail())); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDynamicProjection\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class EvaluateConditionalEventsCmd extends NeedsActiveExecutionCmd<Object> { private static final long serialVersionUID = 1L; protected Map<String, Object> processVariables; protected Map<String, Object> transientVariables; protected boolean async; public EvaluateConditionalEventsCmd(String processInstanceId, Map<String, Object> processVariables) { super(processInstanceId); this.processVariables = processVariables; } public EvaluateConditionalEventsCmd(String processInstanceId, Map<String, Object> processVariables, Map<String, Object> transientVariables) { this(processInstanceId, processVariables); this.transientVariables = transientVariables; } @Override protected Object execute(CommandContext commandContext, ExecutionEntity execution) { if (!execution.isProcessInstanceType()) {
throw new FlowableException(execution + " is not of type process instance"); } if (processVariables != null) { execution.setVariables(processVariables); } if (transientVariables != null) { execution.setTransientVariables(transientVariables); } CommandContextUtil.getAgenda(commandContext).planEvaluateConditionalEventsOperation(execution); return null; } @Override protected String getSuspendedExceptionMessagePrefix() { return "Cannot evaluate conditions for"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\EvaluateConditionalEventsCmd.java
1
请完成以下Java代码
public String getClrSysRef() { return clrSysRef; } /** * Sets the value of the clrSysRef property. * * @param value * allowed object is * {@link String } * */ public void setClrSysRef(String value) { this.clrSysRef = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link ProprietaryReference1 } * */ public ProprietaryReference1 getPrtry() {
return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryReference1 } * */ public void setPrtry(ProprietaryReference1 value) { this.prtry = 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\TransactionReferences2.java
1
请完成以下Java代码
private ImmutableSetMultimap<PaymentId, String> getInvoiceDocumentNosByPaymentId(final Set<PaymentId> paymentIds) { final SetMultimap<PaymentId, InvoiceId> invoiceIdsByPaymentId = allocationDAO.retrieveInvoiceIdsByPaymentIds(paymentIds); final ImmutableMap<InvoiceId, String> invoiceDocumentNos = invoiceDAO.getDocumentNosByInvoiceIds(invoiceIdsByPaymentId.values()); return invoiceIdsByPaymentId.entries() .stream() .map(GuavaCollectors.mapValue(invoiceDocumentNos::get)) .filter(ImmutableMapEntry::isValueNotNull) .collect(GuavaCollectors.toImmutableSetMultimap()); } private PaymentToReconcileRow toPaymentToReconcileRow( @NonNull final I_C_Payment record, @NonNull final ImmutableSetMultimap<PaymentId, String> invoiceDocumentNosByPaymentId) { final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID()); final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(currencyId); final Amount payAmt = Amount.of(record.getPayAmt(), currencyCode); final PaymentId paymentId = PaymentId.ofRepoId(record.getC_Payment_ID()); String invoiceDocumentNos = joinInvoiceDocumentNos(invoiceDocumentNosByPaymentId.get(paymentId)); return PaymentToReconcileRow.builder() .paymentId(paymentId) .inboundPayment(record.isReceipt()) .documentNo(record.getDocumentNo()) .dateTrx(TimeUtil.asLocalDate(record.getDateTrx())) .bpartner(bpartnerLookup.findById(record.getC_BPartner_ID()))
.invoiceDocumentNos(invoiceDocumentNos) .payAmt(payAmt) .reconciled(record.isReconciled()) .build(); } private static String joinInvoiceDocumentNos(final Collection<String> documentNos) { if (documentNos == null || documentNos.isEmpty()) { return ""; } return documentNos.stream() .map(StringUtils::trimBlankToNull) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementLineAndPaymentsToReconcileRepository.java
1
请完成以下Java代码
public SaveResult save(final @NotNull Document document) { final AttributesIncludedTabEntityBinding entityBinding = extractEntityBinding(document); final AttributesIncludedTabData data = attributesIncludedTabService.updateByKey( extractKey(document), entityBinding.getAttributeIds(), (attributeId, field) -> { final String fieldName = entityBinding.getFieldNameByAttributeId(attributeId); final IDocumentFieldView documentField = document.getFieldView(fieldName); if (!documentField.hasChangesToSave()) { return field; } final AttributesIncludedTabFieldBinding fieldBinding = extractFieldBinding(document, fieldName); return fieldBinding.updateData( field != null ? field : newDataField(fieldBinding), documentField); }); refreshDocumentFromData(document, data); // Notify the parent document that one of its children were saved (copied from SqlDocumentsRepository) document.getParentDocument().onChildSaved(document); return SaveResult.SAVED; } private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding) { return AttributesIncludedTabDataField.builder()
.attributeId(fieldBinding.getAttributeId()) .valueType(fieldBinding.getAttributeValueType()) .build(); } private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data) { document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data)); } @Override public void delete(final @NotNull Document document) { throw new UnsupportedOperationException(); } @Override public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;} @Override public int retrieveLastLineNo(final DocumentQuery query) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java
1
请在Spring Boot框架中完成以下Java代码
default List<HistoricEntityLink> findHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { return createInternalHistoricEntityLinkQuery() .scopeId(scopeId) .scopeType(scopeType) .linkType(linkType) .list(); } List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType); List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType, String linkType); default List<HistoricEntityLink> findHistoricEntityLinksByReferenceScopeIdAndType(String referenceScopeId, String scopeType, String linkType) { return createInternalHistoricEntityLinkQuery() .referenceScopeId(referenceScopeId) .referenceScopeType(scopeType) .linkType(linkType) .list(); } default List<HistoricEntityLink> findHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType, String linkType) { return createInternalHistoricEntityLinkQuery() .scopeDefinitionId(scopeDefinitionId) .scopeType(scopeType) .linkType(linkType) .list(); }
InternalEntityLinkQuery<HistoricEntityLink> createInternalHistoricEntityLinkQuery(); HistoricEntityLink createHistoricEntityLink(); void insertHistoricEntityLink(HistoricEntityLink entityLink, boolean fireCreateEvent); void deleteHistoricEntityLink(String id); void deleteHistoricEntityLink(HistoricEntityLink entityLink); void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType); void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType); void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds); void deleteHistoricEntityLinksForNonExistingProcessInstances(); void deleteHistoricEntityLinksForNonExistingCaseInstances(); }
repos\flowable-engine-main\modules\flowable-entitylink-service-api\src\main\java\org\flowable\entitylink\api\history\HistoricEntityLinkService.java
2
请完成以下Java代码
protected void doSetRollbackOnly(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.setRollbackOnly(); } } @Override protected void doCleanupAfterCompletion(Object transaction) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) transaction; TransactionSynchronizationManager.unbindResource(getProducerFactory()); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.close(); kafkaResourceHolder.clear(); } } /** * Kafka transaction object, representing a KafkaResourceHolder. Used as transaction object by * KafkaTransactionManager. * @see KafkaResourceHolder */ private static class KafkaTransactionObject<K, V> implements SmartTransactionObject { private @Nullable KafkaResourceHolder<K, V> resourceHolder; KafkaTransactionObject() {
} public void setResourceHolder(@Nullable KafkaResourceHolder<K, V> resourceHolder) { this.resourceHolder = resourceHolder; } public @Nullable KafkaResourceHolder<K, V> getResourceHolder() { return this.resourceHolder; } @Override public boolean isRollbackOnly() { return this.resourceHolder != null && this.resourceHolder.isRollbackOnly(); } @Override public void flush() { // no-op } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\transaction\KafkaTransactionManager.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteUser(SysUser sysUser, Integer tenantId) { //被删除人的用户id String userId = sysUser.getId(); //被删除人的密码 String password = sysUser.getPassword(); //当前登录用户 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal(); //step1 判断当前用户是否为当前租户的创建者才可以删除 SysTenant sysTenant = this.getById(tenantId); if(null == sysTenant || !user.getUsername().equals(sysTenant.getCreateBy())){ throw new JeecgBootException("您不是当前组织的创建者,无法删除用户!"); } //step2 判断除了当前组织之外是否还有加入了其他组织 LambdaQueryWrapper<SysUserTenant> query = new LambdaQueryWrapper<>(); query.eq(SysUserTenant::getUserId,userId); query.ne(SysUserTenant::getTenantId,tenantId); List<SysUserTenant> sysUserTenants = userTenantMapper.selectList(query); if(CollectionUtils.isNotEmpty(sysUserTenants)){ throw new JeecgBootException("该用户还存在于其它组织中,无法删除用户!"); } //step3 验证创建时间和密码 SysUser sysUserData = userService.getById(userId); this.verifyCreateTimeAndPassword(sysUserData,password); //step4 真实删除用户 userService.deleteUser(userId); userService.removeLogicDeleted(Collections.singletonList(userId)); } /** * 为用户添加租户下所有套餐 * * @param userId 用户id * @param tenantId 租户id
*/ public void addPackUser(String userId, String tenantId) { //根据租户id和产品包的code获取租户套餐id List<String> packIds = sysTenantPackMapper.getPackIdByPackCodeAndTenantId(oConvertUtils.getInt(tenantId)); if (CollectionUtil.isNotEmpty(packIds)) { for (String packId : packIds) { SysTenantPackUser sysTenantPackUser = new SysTenantPackUser(); sysTenantPackUser.setUserId(userId); sysTenantPackUser.setTenantId(oConvertUtils.getInt(tenantId)); sysTenantPackUser.setPackId(packId); sysTenantPackUser.setStatus(CommonConstant.STATUS_1_INT); try { this.addTenantPackUser(sysTenantPackUser); } catch (Exception e) { log.warn("添加用户套餐包失败,原因:" + e.getMessage()); } } } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTenantServiceImpl.java
2
请完成以下Java代码
public static IO<Unit> printLetters(final String s) { return () -> { for (int i = 0; i < s.length(); i++) { System.out.println(s.charAt(i)); } return Unit.unit(); }; } public static void main(String[] args) { F<String, IO<Unit>> printLetters = i -> printLetters(i); IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?"); IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input); IO<String> readInput = IOFunctions.stdinReadLine(); F<String, String> toUpperCase = i -> i.toUpperCase(); F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase); IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput); IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult); IOFunctions.toSafe(program).run(); } }
repos\tutorials-master\libraries-6\src\main\java\com\baeldung\fj\FunctionalJavaIOMain.java
1
请在Spring Boot框架中完成以下Java代码
public PaymentAllocationBuilder paymentDocuments(final Collection<PaymentDocument> paymentDocuments) { _paymentDocuments = ImmutableList.copyOf(paymentDocuments); return this; } public PaymentAllocationBuilder paymentDocument(final PaymentDocument paymentDocument) { return paymentDocuments(ImmutableList.of(paymentDocument)); } @VisibleForTesting final ImmutableList<PayableDocument> getPayableDocuments() { return _payableDocuments; } @VisibleForTesting final ImmutableList<PaymentDocument> getPaymentDocuments() { return _paymentDocuments;
} public PaymentAllocationBuilder invoiceProcessingServiceCompanyService(@NonNull final InvoiceProcessingServiceCompanyService invoiceProcessingServiceCompanyService) { assertNotBuilt(); this.invoiceProcessingServiceCompanyService = invoiceProcessingServiceCompanyService; return this; } /** * @param allocatePayableAmountsAsIs if true, we allow the allocated amount to exceed the payment's amount, * if the given payable is that big. * We need this behavior when we want to allocate a remittance advice and know that *in sum* the payables' amounts will match the payment */ public PaymentAllocationBuilder allocatePayableAmountsAsIs(final boolean allocatePayableAmountsAsIs) { assertNotBuilt(); this.allocatePayableAmountsAsIs = allocatePayableAmountsAsIs; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentAllocationBuilder.java
2
请完成以下Java代码
public int getMKTG_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Campaign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MKTG_ContactPerson_With_Campaign_ID. @param MKTG_ContactPerson_With_Campaign_ID MKTG_ContactPerson_With_Campaign_ID */ @Override
public void setMKTG_ContactPerson_With_Campaign_ID (int MKTG_ContactPerson_With_Campaign_ID) { if (MKTG_ContactPerson_With_Campaign_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID, Integer.valueOf(MKTG_ContactPerson_With_Campaign_ID)); } /** Get MKTG_ContactPerson_With_Campaign_ID. @return MKTG_ContactPerson_With_Campaign_ID */ @Override public int getMKTG_ContactPerson_With_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_With_Campaign_V.java
1
请在Spring Boot框架中完成以下Java代码
public class DhlShipmentOrderId implements RepoIdAware { int repoId; @JsonCreator public static DhlShipmentOrderId ofRepoId(final int repoId) { return new DhlShipmentOrderId(repoId); } @Nullable public static DhlShipmentOrderId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new DhlShipmentOrderId(repoId) : null; } public static int toRepoId(final DhlShipmentOrderId id)
{ return id != null ? id.getRepoId() : -1; } private DhlShipmentOrderId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "DHL_ShipmentOrder_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlShipmentOrderId.java
2
请在Spring Boot框架中完成以下Java代码
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword()); try { subject.login(token); } catch (AuthenticationException ae) { logger.error(ae.getMessage()); attr.addFlashAttribute("error", "Invalid Credentials"); return "redirect:/login"; } } return "redirect:/home"; } @GetMapping("/home") public String getMeHome(Model model) { addUserAttributes(model); return "comparison/home"; } @GetMapping("/admin") public String adminOnly(Model model) { addUserAttributes(model); Subject currentUser = SecurityUtils.getSubject(); if (currentUser.hasRole("ADMIN")) { model.addAttribute("adminContent", "only admin can view this"); } return "comparison/home"; } @PostMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/"; } private void addUserAttributes(Model model) { Subject currentUser = SecurityUtils.getSubject();
String permission = ""; if (currentUser.hasRole("ADMIN")) { model.addAttribute("role", "ADMIN"); } else if (currentUser.hasRole("USER")) { model.addAttribute("role", "USER"); } if (currentUser.isPermitted("READ")) { permission = permission + " READ"; } if (currentUser.isPermitted("WRITE")) { permission = permission + " WRITE"; } model.addAttribute("username", currentUser.getPrincipal()); model.addAttribute("permission", permission); } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\shiro\controllers\ShiroController.java
2
请完成以下Java代码
public Map<LocatorId, ProductHUInventory> mapByLocatorId() { return mapByKey(HuForInventoryLine::getLocatorId); } @NonNull public Map<WarehouseId, ProductHUInventory> mapByWarehouseId() { return mapByKey(huForInventoryLine -> huForInventoryLine.getLocatorId().getWarehouseId()); } @NonNull public List<InventoryLineHU> toInventoryLineHUs( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final UomId targetUomId) { final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId); return huForInventoryLineList.stream() .map(DraftInventoryLinesCreateCommand::toInventoryLineHU) .map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter)) .collect(ImmutableList.toImmutableList()); } @NonNull public Set<HuId> getHuIds() { return huForInventoryLineList.stream() .map(HuForInventoryLine::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @NonNull private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider) { final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>();
huForInventoryLineList.forEach(hu -> { final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>(); husFromTargetWarehouse.add(hu); key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> { oldList.addAll(newList); return oldList; }); }); return key2Hus.keySet() .stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId)))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
1
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Set<Role> getRoles() {
return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public void addRole(Role role) { roles.add(role); } public void removeRole(Role role) { roles.remove(role); } }
repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\java\com\baeldung\quarkus\rbac\users\User.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("value", value); persistentState.put("password", passwordBytes); return persistentState; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getUserId() { return userId; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public byte[] getPasswordBytes() { return passwordBytes; } @Override
public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getName() { return key; } @Override public String getUsername() { return value; } @Override public String getParentId() { return parentId; } @Override public void setParentId(String parentId) { this.parentId = parentId; } @Override public Map<String, String> getDetails() { return details; } @Override public void setDetails(Map<String, String> details) { this.details = details; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public DecisionRequirementsDefinitionQuery orderByDecisionRequirementsDefinitionId() { orderBy(DecisionRequirementsDefinitionQueryProperty.DECISION_REQUIREMENTS_DEFINITION_ID); return this; } public DecisionRequirementsDefinitionQuery orderByDecisionRequirementsDefinitionVersion() { orderBy(DecisionRequirementsDefinitionQueryProperty.DECISION_REQUIREMENTS_DEFINITION_VERSION); return this; } 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
请在Spring Boot框架中完成以下Java代码
public KafkaAdmin kafkaAdmin() { Map<String, Object> configs = new HashMap<>(); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); return new KafkaAdmin(configs); } @Bean public NewTopic topic1() { return new NewTopic(topicName, 1, (short) 1); } @Bean public NewTopic topic2() { return new NewTopic(partitionedTopicName, 6, (short) 1); }
@Bean public NewTopic topic3() { return new NewTopic(filteredTopicName, 1, (short) 1); } @Bean public NewTopic topic4() { return new NewTopic(greetingTopicName, 1, (short) 1); } @Bean public NewTopic multiTypeTopic() { return new NewTopic(multiTypeTopicName, 1, (short) 1); } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\retryable\KafkaTopicConfig.java
2
请完成以下Java代码
public class DelegatingSecurityContextExecutor extends AbstractDelegatingSecurityContextSupport implements Executor { private final Executor delegate; /** * Creates a new {@link DelegatingSecurityContextExecutor} that uses the specified * {@link SecurityContext}. * @param delegateExecutor the {@link Executor} to delegate to. Cannot be null. * @param securityContext the {@link SecurityContext} to use for each * {@link DelegatingSecurityContextRunnable} or null to default to the current * {@link SecurityContext} */ public DelegatingSecurityContextExecutor(Executor delegateExecutor, @Nullable SecurityContext securityContext) { super(securityContext); Assert.notNull(delegateExecutor, "delegateExecutor cannot be null"); this.delegate = delegateExecutor; } /** * Creates a new {@link DelegatingSecurityContextExecutor} that uses the current * {@link SecurityContext} from the {@link SecurityContextHolder} at the time the task * is submitted. * @param delegate the {@link Executor} to delegate to. Cannot be null. */ public DelegatingSecurityContextExecutor(Executor delegate) {
this(delegate, null); } @Override public final void execute(Runnable task) { this.delegate.execute(wrap(task)); } protected final Executor getDelegateExecutor() { return this.delegate; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { super.setSecurityContextHolderStrategy(securityContextHolderStrategy); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class ProjectIssueId implements RepoIdAware { @JsonCreator public static ProjectIssueId ofRepoId(final int repoId) { return new ProjectIssueId(repoId); } @Nullable public static ProjectIssueId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? ofRepoId(repoId) : null;} public static int toRepoId(@Nullable final ProjectIssueId id) { return id != null ? id.getRepoId() : -1; } int repoId; private ProjectIssueId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "C_ProjectIssue_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final ProjectIssueId id1, @Nullable final ProjectIssueId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectIssueId.java
2
请在Spring Boot框架中完成以下Java代码
public class TenantEntityProfileCache { private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Map<EntityId, Set<EntityId>> allEntities = new HashMap<>(); public void removeProfileId(EntityId profileId) { lock.writeLock().lock(); try { // Remove from allEntities allEntities.remove(profileId); } finally { lock.writeLock().unlock(); } } public void removeEntityId(EntityId entityId) { lock.writeLock().lock(); try { // Remove from allEntities allEntities.values().forEach(set -> set.remove(entityId)); } finally { lock.writeLock().unlock(); } } public void remove(EntityId profileId, EntityId entityId) { lock.writeLock().lock(); try { // Remove from allEntities removeSafely(allEntities, profileId, entityId); } finally { lock.writeLock().unlock(); } } public void add(EntityId profileId, EntityId entityId) { lock.writeLock().lock(); try { if (EntityType.DEVICE.equals(profileId.getEntityType()) || EntityType.ASSET.equals(profileId.getEntityType())) { throw new RuntimeException("Entity type '" + profileId.getEntityType() + "' is not a profileId."); } allEntities.computeIfAbsent(profileId, k -> new HashSet<>()).add(entityId); } finally { lock.writeLock().unlock(); } }
public void update(EntityId oldProfileId, EntityId newProfileId, EntityId entityId) { remove(oldProfileId, entityId); add(newProfileId, entityId); } public Collection<EntityId> getEntityIdsByProfileId(EntityId profileId) { lock.readLock().lock(); try { var entities = allEntities.getOrDefault(profileId, Collections.emptySet()); List<EntityId> result = new ArrayList<>(entities.size()); result.addAll(entities); return result; } finally { lock.readLock().unlock(); } } private void removeSafely(Map<EntityId, Set<EntityId>> map, EntityId profileId, EntityId entityId) { var set = map.get(profileId); if (set != null) { set.remove(entityId); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\cache\TenantEntityProfileCache.java
2
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<ApiResponse> pauseJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); } jobService.pauseJob(form); return new ResponseEntity<>(ApiResponse.msg("暂停成功"), HttpStatus.OK); } /** * 恢复定时任务 */ @PutMapping(params = "resume") public ResponseEntity<ApiResponse> resumeJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); } jobService.resumeJob(form); return new ResponseEntity<>(ApiResponse.msg("恢复成功"), HttpStatus.OK); } /** * 修改定时任务,定时时间 */
@PutMapping(params = "cron") public ResponseEntity<ApiResponse> cronJob(@Valid JobForm form) { try { jobService.cronJob(form); } catch (Exception e) { return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(ApiResponse.msg("修改成功"), HttpStatus.OK); } @GetMapping public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) { if (ObjectUtil.isNull(currentPage)) { currentPage = 1; } if (ObjectUtil.isNull(pageSize)) { pageSize = 10; } PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize); return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList()))); } }
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\controller\JobController.java
2
请完成以下Java代码
public class CamelTaskJsonConverter extends BaseBpmnJsonConverter { public static void fillTypes( Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { fillJsonTypes(convertersToBpmnMap); fillBpmnTypes(convertersToJsonMap); } public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_CAMEL, CamelTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) {}
protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_CAMEL; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { // done in service task } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ServiceTask task = new ServiceTask(); task.setType("camel"); addField("camelContext", PROPERTY_CAMELTASK_CAMELCONTEXT, elementNode, task); return task; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\CamelTaskJsonConverter.java
1
请完成以下Java代码
public List<ExecutionListener> getExecutionListeners() { if (executionListeners == null) { return Collections.EMPTY_LIST; } return executionListeners; } // getters and setters ////////////////////////////////////////////////////// protected void setSource(ActivityImpl source) { this.source = source; } @Override public ActivityImpl getDestination() { return destination; } public void setExecutionListeners(List<ExecutionListener> executionListeners) { this.executionListeners = executionListeners; }
public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } @Override public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\TransitionImpl.java
1
请完成以下Java代码
public AccountIdentification4Choice getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link AccountIdentification4Choice } * */ public void setId(AccountIdentification4Choice value) { this.id = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link CashAccountType2 } * */ public CashAccountType2 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link CashAccountType2 } * */ public void setTp(CashAccountType2 value) { this.tp = value; } /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } * */ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public void setCcy(String value) { this.ccy = value;
} /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = 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\CashAccount16.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) .formLogin(Customizer.withDefaults()); return http.build(); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient pkceClient = RegisteredClient .withId(UUID.randomUUID().toString()) .clientId("pkce-client") .clientSecret("{noop}obscura") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .scope(OidcScopes.OPENID) .scope(OidcScopes.EMAIL) .scope(OidcScopes.PROFILE) .clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(false) .requireProofKey(true) .build()) .redirectUri("http://127.0.0.1:8080/login/oauth2/code/pkce") // Localhost not allowed .build(); return new InMemoryRegisteredClientRepository(pkceClient); } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings .builder() .build(); } }
repos\tutorials-master\spring-security-modules\spring-security-pkce\pkce-auth-server\src\main\java\com\baeldung\security\pkce\authserver\conf\AuthServerConfiguration.java
2
请完成以下Java代码
public java.lang.String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable java.lang.String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public java.lang.String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); } @Override public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); }
@Override public java.lang.String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournalLine.java
1
请完成以下Spring Boot application配置
spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true image.default=https://static.productionready.io/images/smiley-cyrus.jpg jwt.secret=nRvyYC4soFxBdZ-F-5Nnzz5USXstR1YylsTd-mA0aKtI9HUlriGrtkf-TiuDapkLiUCogO3JOK7kwZisrHp6wA jwt.sessionTime=86400 mybatis.config-location=classpath:mybatis-config
.xml mybatis.mapper-locations=mapper/*.xml logging.level.io.spring.infrastructure.mybatis.readservice.ArticleReadService=DEBUG
repos\spring-boot-realworld-example-app-master (1)\src\main\resources\application.properties
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * AD_RelationType_ID AD_Reference_ID=541357 * Reference name: Product Relation Types */ public static final int AD_RELATIONTYPE_ID_AD_Reference_ID=541357; /** Parent Product = Parent */ public static final String AD_RELATIONTYPE_ID_ParentProduct = "Parent"; @Override public void setAD_RelationType_ID (final java.lang.String AD_RelationType_ID) { set_Value (COLUMNNAME_AD_RelationType_ID, AD_RelationType_ID); } @Override public java.lang.String getAD_RelationType_ID() { return get_ValueAsString(COLUMNNAME_AD_RelationType_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() {
return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Product_Relationship_ID (final int M_Product_Relationship_ID) { if (M_Product_Relationship_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, M_Product_Relationship_ID); } @Override public int getM_Product_Relationship_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Relationship_ID); } @Override public void setRelatedProduct_ID (final int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_Value (COLUMNNAME_RelatedProduct_ID, null); else set_Value (COLUMNNAME_RelatedProduct_ID, RelatedProduct_ID); } @Override public int getRelatedProduct_ID() { return get_ValueAsInt(COLUMNNAME_RelatedProduct_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Relationship.java
1
请完成以下Java代码
public int getMSV3_BestellungAuftrag_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAuftrag_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GebindeId. @param MSV3_GebindeId GebindeId */ @Override public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId) { set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId); } /** Get GebindeId. @return GebindeId */ @Override public java.lang.String getMSV3_GebindeId () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId); }
/** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAuftrag.java
1
请完成以下Java代码
public long getMinimum() { return minimum; } public void setMinimum(long minimum) { this.minimum = minimum; } public long getMaximum() { return maximum; } public void setMaximum(long maximum) { this.maximum = maximum; } public long getAverage() { return average;
} public void setAverage(long average) { this.average = average; } public String toString() { return this.getClass().getSimpleName() + "[period=" + period + ", periodUnit=" + periodUnit + ", minimum=" + minimum + ", maximum=" + maximum + ", average=" + average + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DurationReportResultEntity.java
1
请完成以下Java代码
public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Port. @param Port Port */ @Override public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ @Override public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port); if (ii == null) return 0; return ii.intValue(); } /** * Protocol AD_Reference_ID=540906 * Reference name: C_InboundMailConfig_Protocol */ public static final int PROTOCOL_AD_Reference_ID=540906; /** IMAP = imap */ public static final String PROTOCOL_IMAP = "imap"; /** IMAPS = imaps */ public static final String PROTOCOL_IMAPS = "imaps"; /** Set Protocol. @param Protocol Protocol */ @Override public void setProtocol (java.lang.String Protocol) { set_Value (COLUMNNAME_Protocol, Protocol); } /** Get Protocol. @return Protocol */ @Override public java.lang.String getProtocol () { return (java.lang.String)get_Value(COLUMNNAME_Protocol); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); }
/** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ @Override public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ @Override public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Nutzer-ID/Login. @param UserName Nutzer-ID/Login */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Nutzer-ID/Login. @return Nutzer-ID/Login */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java-gen\de\metas\inbound\mail\model\X_C_InboundMailConfig.java
1