instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Datum. @param ValueDate Datum */ @Override public void setValueDate (java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } /** Get Datum. @return Datum */ @Override public java.sql.Timestamp getValueDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValueDate); } /** Set Zahlwert. @param ValueNumber Numeric Value */ @Override public void setValueNumber (java.math.BigDecimal ValueNumber)
{ set_Value (COLUMNNAME_ValueNumber, ValueNumber); } /** Get Zahlwert. @return Numeric Value */ @Override public java.math.BigDecimal getValueNumber () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeInstance.java
1
请完成以下Java代码
final class HUTraceResultExtender implements SqlDocumentFilterConverter { private static final String WHERE_IN_T_SELECTION = "(M_HU_Trace_ID IN (select T_Selection_ID from T_Selection where AD_PInstance_ID=?))"; public static HUTraceResultExtender createForRepositoryAndconverter( @NonNull final HUTraceRepository huTraceRepository, @NonNull final SqlDocumentFilterConverter converter) { return new HUTraceResultExtender(huTraceRepository, converter); } private final HUTraceRepository huTraceRepository; private final SqlDocumentFilterConverter converter; private HUTraceResultExtender( @NonNull final HUTraceRepository huTraceRepository, @NonNull final SqlDocumentFilterConverter converter) { this.huTraceRepository = huTraceRepository; this.converter = converter; } @Override public boolean canConvert(final String filterId) { return true; }
@Override public FilterSql getSql( @NonNull final DocumentFilter filter, @NonNull final SqlOptions sqlOpts, @NonNull final SqlDocumentFilterConverterContext context) { if (!filter.hasParameters() || isSQLOnly(filter)) { return converter.getSql(filter, sqlOpts, context); // do whatever the system usually does } else { final HUTraceEventQuery huTraceQuery = HuTraceQueryCreator.createTraceQueryFromDocumentFilter(filter); final PInstanceId selectionId = huTraceRepository.queryToSelection(huTraceQuery); return FilterSql.ofWhereClause(WHERE_IN_T_SELECTION, selectionId); } } private static boolean isSQLOnly(final @NonNull DocumentFilter filter) { return filter.getParameters().stream().allMatch(DocumentFilterParam::isSqlFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\trace\HUTraceResultExtender.java
1
请完成以下Java代码
public int getM_ShipperTransportation_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipperTransportation_ID); } @Override public void setNetWeightKg (final @Nullable BigDecimal NetWeightKg) { set_Value (COLUMNNAME_NetWeightKg, NetWeightKg); } @Override public BigDecimal getNetWeightKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NetWeightKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() {
return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrder.java
1
请完成以下Java代码
public abstract class AbstractAppAutoDeploymentStrategy extends CommonAutoDeploymentStrategy<AppEngine> { public AbstractAppAutoDeploymentStrategy() { } public AbstractAppAutoDeploymentStrategy(CommonAutoDeploymentProperties deploymentProperties) { super(deploymentProperties); } @Override protected LockManager getLockManager(AppEngine engine, String deploymentNameHint) { // The app engine does not have deployment name return engine.getAppEngineConfiguration().getLockManager(determineLockName("appDeploymentsLock")); } protected void addResource(Resource resource, AppDeploymentBuilder deploymentBuilder) { String resourceName = determineResourceName(resource); addResource(resource, resourceName, deploymentBuilder); }
protected void addResource(Resource resource, String resourceName, AppDeploymentBuilder deploymentBuilder) { try (InputStream inputStream = resource.getInputStream()) { if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip")) { try (ZipInputStream zipStream = new ZipInputStream(inputStream)) { deploymentBuilder.addZipInputStream(zipStream); } } else { deploymentBuilder.addInputStream(resourceName, inputStream); } } catch (IOException ex) { throw new UncheckedIOException("Failed to read resource " + resource, ex); } } }
repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\autodeployment\AbstractAppAutoDeploymentStrategy.java
1
请完成以下Java代码
public void setM_DistributionRun_ID (int M_DistributionRun_ID) { if (M_DistributionRun_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, Integer.valueOf(M_DistributionRun_ID)); } /** Get Distribution Run. @return Distribution Run create Orders to distribute products to a selected list of partners */ public int getM_DistributionRun_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRun_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRun.java
1
请完成以下Java代码
public int getRefillTokens() { return refillTokens; } public ThrottleGatewayFilter setRefillTokens(int refillTokens) { this.refillTokens = refillTokens; return this; } public int getRefillPeriod() { return refillPeriod; } public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) { this.refillPeriod = refillPeriod; return this; } public TimeUnit getRefillUnit() { return refillUnit; }
public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) { this.refillUnit = refillUnit; return this; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { TokenBucket tokenBucket = getTokenBucket(); // TODO: get a token bucket for a key log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); boolean consumed = tokenBucket.tryConsume(); if (consumed) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-sample\src\main\java\org\springframework\cloud\gateway\sample\ThrottleGatewayFilter.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<Product> importProduct( @NonNull final SyncProduct syncProduct, @Nullable Product product) { final String uuid = syncProduct.getUuid(); if (product != null && !Objects.equals(product.getUuid(), uuid)) { product = null; } if (product == null) { product = productsRepo.findByUuid(uuid); } // // Handle delete request if (syncProduct.isDeleted()) { if (product != null) { deleteProduct(product); } return Optional.empty(); } if (product == null) { product = new Product(); product.setUuid(uuid); } product.setDeleted(false); product.setName(syncProduct.getName()); product.setPackingInfo(syncProduct.getPackingInfo()); product.setShared(syncProduct.isShared()); productsRepo.save(product); logger.debug("Imported: {} -> {}", syncProduct, product); // // Import product translations final Map<String, ProductTrl> productTrls = mapByLanguage(productTrlsRepo.findByRecord(product)); for (final Map.Entry<String, String> lang2nameTrl : syncProduct.getNameTrls().entrySet()) { final String language = lang2nameTrl.getKey();
final String nameTrl = lang2nameTrl.getValue(); ProductTrl productTrl = productTrls.remove(language); if (productTrl == null) { productTrl = new ProductTrl(); productTrl.setLanguage(language); productTrl.setRecord(product); } productTrl.setName(nameTrl); productTrlsRepo.save(productTrl); logger.debug("Imported: {}", productTrl); } for (final ProductTrl productTrl : productTrls.values()) { productTrlsRepo.delete(productTrl); } return Optional.of(product); } private void deleteProduct(final Product product) { if (product.isDeleted()) { return; } product.setDeleted(true); productsRepo.save(product); logger.debug("Deleted: {}", product); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncProductImportService.java
2
请完成以下Java代码
public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions)); } @Override public boolean isStatus_Print_Job_Instructions() { return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); }
@Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } @Override public void setWP_IsError (boolean WP_IsError) { set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError)); } @Override public boolean isWP_IsError() { return get_ValueAsBoolean(COLUMNNAME_WP_IsError); } @Override public void setWP_IsProcessed (boolean WP_IsProcessed) { set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed)); } @Override public boolean isWP_IsProcessed() { return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java
1
请完成以下Java代码
public class MRequestProcessorLog extends X_R_RequestProcessorLog implements AdempiereProcessorLog { /** * */ private static final long serialVersionUID = 3295903266591998482L; /** * Standard Constructor * @param ctx context * @param R_RequestProcessorLog_ID id */ public MRequestProcessorLog (Properties ctx, int R_RequestProcessorLog_ID, String trxName) { super (ctx, R_RequestProcessorLog_ID, trxName); if (R_RequestProcessorLog_ID == 0) { setIsError (false); } } // MRequestProcessorLog /**
* Load Constructor * @param ctx context * @param rs result set */ public MRequestProcessorLog (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MRequestProcessorLog /** * Parent Constructor * @param parent parent * @param summary summary */ public MRequestProcessorLog (MRequestProcessor parent, String summary) { this (parent.getCtx(), 0, parent.get_TrxName()); setClientOrg(parent); setR_RequestProcessor_ID(parent.getR_RequestProcessor_ID()); setSummary(summary); } // MRequestProcessorLog } // MRequestProcessorLog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRequestProcessorLog.java
1
请完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = -2936687026040726549L; private String bookName; private transient String description; private transient int copies; private final transient String bookCategory = "Fiction"; private final transient String bookCategoryNewOperator = new String("Fiction with new Operator"); public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
public int getCopies() { return copies; } public void setCopies(int copies) { this.copies = copies; } public String getBookCategory() { return bookCategory; } public String getBookCategoryNewOperator() { return bookCategoryNewOperator; } }
repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\transientkw\Book.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteVariablesByExecutionId(String executionId) { DbSqlSession dbSqlSession = getDbSqlSession(); if (isEntityInserted(dbSqlSession, "execution", executionId)) { deleteCachedEntities(dbSqlSession, variableInstanceByExecutionIdMatcher, executionId); } else { bulkDelete("deleteVariableInstancesByExecutionId", variableInstanceByExecutionIdMatcher, executionId); } } @Override public void deleteByScopeIdAndScopeType(String scopeId, String scopeType) { Map<String, Object> params = new HashMap<>(3); params.put("scopeId", scopeId); params.put("scopeType", scopeType); bulkDelete("deleteVariablesByScopeIdAndScopeType", variableInstanceByScopeIdAndScopeTypeMatcher, params); } @Override public void deleteByScopeIdAndScopeTypes(String scopeId, Collection<String> scopeTypes) { if (scopeTypes.size() == 1) { deleteByScopeIdAndScopeType(scopeId, scopeTypes.iterator().next()); return; } Map<String, Object> params = new HashMap<>(3); params.put("scopeId", scopeId); params.put("scopeTypes", scopeTypes);
bulkDelete("deleteVariablesByScopeIdAndScopeTypes", variableInstanceByScopeIdAndScopeTypesMatcher, params); } @Override public void deleteBySubScopeIdAndScopeTypes(String subScopeId, Collection<String> scopeTypes) { Map<String, Object> params = new HashMap<>(3); params.put("subScopeId", subScopeId); params.put("scopeTypes", scopeTypes); bulkDelete("deleteVariablesBySubScopeIdAndScopeTypes", variableInstanceBySubScopeIdAndScopeTypesMatcher, params); } @Override protected IdGenerator getIdGenerator() { return variableServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\data\impl\MybatisVariableInstanceDataManager.java
2
请完成以下Java代码
public class DocumentPermissionException extends AdempiereException { private static final long serialVersionUID = -6951387618389868436L; public enum DocumentPermission { WindowAccess, /** * Document view access */ View, /** * Document update access */ Update, } private static final AdMessageKey MSG_NoAccess = AdMessageKey.of("NoAccess"); public static DocumentPermissionException noAccess(final DocumentPermission permissionRequired) { return new DocumentPermissionException(permissionRequired, MSG_NoAccess); } @Deprecated public static DocumentPermissionException of(final DocumentPermission permissionRequired, final AdMessageKey adMessage)
{ return new DocumentPermissionException(permissionRequired, adMessage); } public static DocumentPermissionException of(final DocumentPermission permissionRequired, final ITranslatableString errorMessage) { return new DocumentPermissionException(permissionRequired, errorMessage); } private DocumentPermissionException(final DocumentPermission permissionRequired, final AdMessageKey adMessage) { super(adMessage); setParameter("PermissionRequired", permissionRequired); } private DocumentPermissionException(final DocumentPermission permissionRequired, final ITranslatableString string) { super(string); setParameter("PermissionRequired", permissionRequired); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\exceptions\DocumentPermissionException.java
1
请在Spring Boot框架中完成以下Java代码
public Date getRemitConfirmTime() { return remitConfirmTime; } /** * 打款确认时间 * * @param remitConfirmTime */ public void setRemitConfirmTime(Date remitConfirmTime) { this.remitConfirmTime = remitConfirmTime; } /** * 打款备注 * * @return */ public String getRemitRemark() { return remitRemark; } /** * 打款备注 * * @param remitRemark */ public void setRemitRemark(String remitRemark) { this.remitRemark = remitRemark == null ? null : remitRemark.trim(); } /** * 操作员登录名 * * @return */ public String getOperatorLoginname() { return operatorLoginname; } /** * 操作员登录名 * * @param operatorLoginname */ public void setOperatorLoginname(String operatorLoginname) { this.operatorLoginname = operatorLoginname == null ? null : operatorLoginname.trim(); }
/** * 操作员姓名 * * @return */ public String getOperatorRealname() { return operatorRealname; } /** * 操作员姓名 * * @param operatorRealname */ public void setOperatorRealname(String operatorRealname) { this.operatorRealname = operatorRealname == null ? null : operatorRealname.trim(); } public String getSettStatusDesc() { return SettRecordStatusEnum.getEnum(this.getSettStatus()).getDesc(); } public String getCreateTimeDesc() { return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss"); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettRecord.java
2
请完成以下Java代码
public int getDisplayType() { return m_displayType; } // getDisplayType /** * Get Alias Name * @return alias column name */ public String getAlias() { return m_alias; } // getAlias /** * Column has Alias. * (i.e. has a key) * @return true if Alias */ public boolean hasAlias() { return !m_columnName.equals(m_alias); } // hasAlias /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_pageBreak; } // isPageBreak /** * String Representation * @return info */ public String toString() {
StringBuffer sb = new StringBuffer("PrintDataColumn["); sb.append("ID=").append(m_AD_Column_ID) .append("-").append(m_columnName); if (hasAlias()) sb.append("(").append(m_alias).append(")"); sb.append(",DisplayType=").append(m_displayType) .append(",Size=").append(m_columnSize) .append("]"); return sb.toString(); } // toString public void setFormatPattern(String formatPattern) { m_FormatPattern = formatPattern; } public String getFormatPattern() { return m_FormatPattern; } } // PrintDataColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataColumn.java
1
请在Spring Boot框架中完成以下Java代码
public static class CardReader { @NonNull SumUpCardReaderExternalId externalId; @NonNull String name; } // // // // // // @Value @Builder @Jacksonized @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public static class Card { @NonNull String type; @NonNull String last4Digits; @Override @Deprecated public String toString() {return getAsString();} public String getAsString() {return type + "-" + last4Digits;} } // // // // // // @RequiredArgsConstructor @Getter public enum LastSyncStatus implements ReferenceListAwareEnum { OK(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_OK), Error(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_Error), ; private static final ValuesIndex<LastSyncStatus> index = ReferenceListAwareEnums.index(values()); @NonNull private final String code; public static LastSyncStatus ofCode(@NonNull String code) {return index.ofCode(code);} public static LastSyncStatus ofNullableCode(@Nullable String code) {return index.ofNullableCode(code);}
} // // // // // // @Value @Builder @Jacksonized @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public static class LastSync { @NonNull LastSyncStatus status; @Nullable Instant timestamp; @Nullable AdIssueId errorId; public static LastSync ok() { return builder() .status(LastSyncStatus.OK) .timestamp(SystemTime.asInstant()) .build(); } public static LastSync error(@NonNull final AdIssueId errorId) { return builder() .status(LastSyncStatus.Error) .timestamp(SystemTime.asInstant()) .errorId(errorId) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransaction.java
2
请完成以下Java代码
public int getDIM_Dimension_Spec_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Alle Attributwerte. @param IsIncludeAllAttributeValues Alle Attributwerte */ @Override public void setIsIncludeAllAttributeValues (boolean IsIncludeAllAttributeValues) { set_Value (COLUMNNAME_IsIncludeAllAttributeValues, Boolean.valueOf(IsIncludeAllAttributeValues)); } /** Get Alle Attributwerte. @return Alle Attributwerte */ @Override public boolean isIncludeAllAttributeValues () { Object oo = get_Value(COLUMNNAME_IsIncludeAllAttributeValues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Merkmalswert-Zusammenfassung. @param IsValueAggregate Merkmalswert-Zusammenfassung */ @Override public void setIsValueAggregate (boolean IsValueAggregate) { set_Value (COLUMNNAME_IsValueAggregate, Boolean.valueOf(IsValueAggregate)); } /** Get Merkmalswert-Zusammenfassung. @return Merkmalswert-Zusammenfassung */ @Override public boolean isValueAggregate () { Object oo = get_Value(COLUMNNAME_IsValueAggregate); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Merkmal. @param M_Attribute_ID Produkt-Merkmal */ @Override public void setM_Attribute_ID (int M_Attribute_ID) { if (M_Attribute_ID < 1)
set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID)); } /** Get Merkmal. @return Produkt-Merkmal */ @Override public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gruppenname. @param ValueAggregateName Gruppenname */ @Override public void setValueAggregateName (java.lang.String ValueAggregateName) { set_Value (COLUMNNAME_ValueAggregateName, ValueAggregateName); } /** Get Gruppenname. @return Gruppenname */ @Override public java.lang.String getValueAggregateName () { return (java.lang.String)get_Value(COLUMNNAME_ValueAggregateName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaConsumerConfig { @Bean public ConcurrentKafkaListenerContainerFactory<Object, Object> kafkaListenerContainerFactory(ConsumerFactory<Object, Object> consumerFactory, ListenerContainerRegistry registry, TaskScheduler scheduler) { ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory); KafkaConsumerBackoffManager backOffManager = createBackOffManager(registry, scheduler); factory.getContainerProperties() .setAckMode(ContainerProperties.AckMode.RECORD); factory.setContainerCustomizer(container -> { DelayedMessageListenerAdapter<Object, Object> delayedAdapter = wrapWithDelayedMessageListenerAdapter(backOffManager, container); delayedAdapter.setDelayForTopic("web.orders", Duration.ofSeconds(10)); delayedAdapter.setDefaultDelay(Duration.ZERO); container.setupMessageListener(delayedAdapter); }); return factory; } @Bean public ObjectMapper objectMapper() { return new ObjectMapper().registerModule(new JavaTimeModule()) .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
} @Bean public TaskScheduler taskScheduler() { return new ThreadPoolTaskScheduler(); } @SuppressWarnings("unchecked") private DelayedMessageListenerAdapter<Object, Object> wrapWithDelayedMessageListenerAdapter(KafkaConsumerBackoffManager backOffManager, ConcurrentMessageListenerContainer<Object, Object> container) { return new DelayedMessageListenerAdapter<>((MessageListener<Object, Object>) container.getContainerProperties() .getMessageListener(), backOffManager, container.getListenerId()); } private ContainerPartitionPausingBackOffManager createBackOffManager(ListenerContainerRegistry registry, TaskScheduler scheduler) { return new ContainerPartitionPausingBackOffManager(registry, new ContainerPausingBackOffHandler(new ListenerContainerPauseService(registry, scheduler))); } }
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\delay\KafkaConsumerConfig.java
2
请完成以下Java代码
public List<I_PMM_Product> retrieveByProduct(final I_M_Product product) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_PMM_Product.class, product) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PMM_Product.COLUMN_M_Product_ID, product.getM_Product_ID()) .create() .list(); } @Override public List<I_PMM_Product> retrieveByBPartner(@NonNull final BPartnerId bpartnerId) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_PMM_Product.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PMM_Product.COLUMN_C_BPartner_ID, bpartnerId) .create() .list(); } @Override public List<I_PMM_Product> retrieveForDateAndProduct( @NonNull final Date date, @NonNull final ProductId productId, @Nullable final BPartnerId partnerId, final int huPIPId)
{ return retrievePMMProductsValidOnDateQuery(date) .addInArrayOrAllFilter(I_PMM_Product.COLUMNNAME_C_BPartner_ID, partnerId, null) // for the given partner or Not bound to a particular partner (i.e. C_BPartner_ID is null) .addEqualsFilter(I_PMM_Product.COLUMN_M_Product_ID, productId) .addEqualsFilter(I_PMM_Product.COLUMN_M_HU_PI_Item_Product_ID, huPIPId) .orderBy() .addColumn(I_PMM_Product.COLUMNNAME_SeqNo, Direction.Ascending, Nulls.First) .addColumn(I_PMM_Product.COLUMNNAME_ValidFrom, Direction.Descending, Nulls.Last) .addColumn(I_PMM_Product.COLUMNNAME_PMM_Product_ID) .endOrderBy() .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMProductDAO.java
1
请完成以下Java代码
public SimpleElement getArtifactId() { return this.artifactId; } public SimpleElement getVersion() { return this.version; } public SimpleElement getName() { return this.name; } public SimpleElement getDescription() { return this.description; } public SimpleElement getPackageName() { return this.packageName; } /** * A simple element from the properties. */ public static final class SimpleElement { /** * Element title. */ private String title; /** * Element description. */ private String description; /** * Element default value. */ private String value; /** * Create a new instance with the given value. * @param value the value */ public SimpleElement(String value) { this.value = value; } public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public void apply(TextCapability capability) { if (StringUtils.hasText(this.title)) { capability.setTitle(this.title); } if (StringUtils.hasText(this.description)) { capability.setDescription(this.description); } if (StringUtils.hasText(this.value)) { capability.setContent(this.value); } } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrProperties.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Page URL. @param PageURL Page URL */ public void setPageURL (String PageURL) {
set_Value (COLUMNNAME_PageURL, PageURL); } /** Get Page URL. @return Page URL */ public String getPageURL () { return (String)get_Value(COLUMNNAME_PageURL); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_CounterCount.java
1
请在Spring Boot框架中完成以下Java代码
public static class UploadResultResource { private final String file; private final String text; private final String text1; private final String text2; private final String upstream; public UploadResultResource(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) { this.file = format(file); this.text = text; this.text1 = text1; this.text2 = text2; this.upstream = format(upstream); } private static String format(MultipartFile file) { return file == null ? null : file.getOriginalFilename() + " (size: " + file.getSize() + " bytes)"; } public String getFile() { return file; } public String getText() {
return text; } public String getText1() { return text1; } public String getText2() { return text2; } public String getUpstream() { return upstream; } } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\web\controller\MultipartFileUploadStubController.java
2
请在Spring Boot框架中完成以下Java代码
public AddEvidencePaymentDisputeRequest lineItems(List<OrderLineItems> lineItems) { this.lineItems = lineItems; return this; } public AddEvidencePaymentDisputeRequest addLineItemsItem(OrderLineItems lineItemsItem) { if (this.lineItems == null) { this.lineItems = new ArrayList<>(); } this.lineItems.add(lineItemsItem); return this; } /** * This required array identifies the order line item(s) for which the evidence file(s) will be applicable. Both the itemId and lineItemID fields are needed to identify each order line item, and both of these values are returned under the evidenceRequests.lineItems array in the getPaymentDispute response. * * @return lineItems **/ @javax.annotation.Nullable @ApiModelProperty(value = "This required array identifies the order line item(s) for which the evidence file(s) will be applicable. Both the itemId and lineItemID fields are needed to identify each order line item, and both of these values are returned under the evidenceRequests.lineItems array in the getPaymentDispute response.") public List<OrderLineItems> getLineItems() { return lineItems; } public void setLineItems(List<OrderLineItems> lineItems) { this.lineItems = lineItems; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddEvidencePaymentDisputeRequest addEvidencePaymentDisputeRequest = (AddEvidencePaymentDisputeRequest)o; return Objects.equals(this.evidenceType, addEvidencePaymentDisputeRequest.evidenceType) && Objects.equals(this.files, addEvidencePaymentDisputeRequest.files) && Objects.equals(this.lineItems, addEvidencePaymentDisputeRequest.lineItems); }
@Override public int hashCode() { return Objects.hash(evidenceType, files, lineItems); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AddEvidencePaymentDisputeRequest {\n"); sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n"); sb.append(" files: ").append(toIndentedString(files)).append("\n"); sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AddEvidencePaymentDisputeRequest.java
2
请完成以下Java代码
public abstract class AbstractMigrationStepExecutor implements IMigrationStepExecutor { /** * Migration Step Execution Result */ public static enum ExecutionResult { /** * Migration step was executed successfully. */ Executed, /** * Migration step could not be executed and was skipped <i>(e.g missing column)</i>. */ Skipped, /** * Migration step was ignored <i>(usually because it was already applied or could not be rolled back)</i>. */ Ignored, }; protected final transient Logger logger = LogManager.getLogger(getClass()); private final IMigrationExecutorContext migrationExecutorContext; private final I_AD_MigrationStep step; public AbstractMigrationStepExecutor(final IMigrationExecutorContext migrationCtx, final I_AD_MigrationStep step) { super(); this.migrationExecutorContext = migrationCtx; this.step = step; } /** * Get current migration step. * * @return {@link I_AD_MigrationStep} step */ protected I_AD_MigrationStep getAD_MigrationStep() { return step; } /** * Get current migration executor context. * * @return {@link IMigrationExecutorContext} migrationExecutorContext */ protected IMigrationExecutorContext getMigrationExecutorContext() { return migrationExecutorContext; }
/** * Get current properties context. * * @return {@link Properties} ctx */ protected Properties getCtx() { return migrationExecutorContext.getCtx(); } /** * Log error messages as WARNING and normal ones as INFO. * * @param msg * @param resolution * @param isError */ protected final void log(final String msg, final String resolution, final boolean isError) { final StringBuilder sb = new StringBuilder(); sb.append("Step ").append(step.getSeqNo()); if (!Check.isEmpty(msg, true)) { sb.append(": ").append(msg.trim()); } if (resolution != null) { sb.append(" [").append(resolution).append("]"); } if(isError) { logger.error(sb.toString()); } else { logger.info(sb.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\AbstractMigrationStepExecutor.java
1
请完成以下Java代码
public boolean tenantExists(TenantId tenantId) { return existsTenantCache.getAndPutInTransaction(tenantId, () -> tenantDao.existsById(tenantId, tenantId.getId()), false); } private final PaginatedRemover<TenantId, Tenant> tenantsRemover = new PaginatedRemover<>() { @Override protected PageData<Tenant> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return tenantDao.findTenants(tenantId, pageLink); } @Override protected void removeEntity(TenantId tenantId, Tenant entity) { deleteTenant(TenantId.fromUUID(entity.getUuidId())); } }; @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findTenantById(TenantId.fromUUID(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findTenantByIdAsync(tenantId, TenantId.fromUUID(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.TENANT; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\TenantServiceImpl.java
1
请完成以下Spring Boot application配置
spring.application.name=partitionKeyDemo # PostgreSQL connection properties spring.datasource.url=jdbc:postgresql://localhost:6000/salesTest spring.
datasource.username=username spring.datasource.password=password
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\resources\application-partition.properties
2
请完成以下Java代码
public String getRestTypeName() { return "json"; } @Override public Class<?> getVariableType() { return JsonNode.class; } @Override public Object getVariableValue(EngineRestVariable result) { if (result.getValue() != null) { if (result.getValue() instanceof Map || result.getValue() instanceof List) { // When the variable is coming from the REST API it automatically gets converted to an ArrayList or // LinkedHashMap. In all other cases JSON is saved as ArrayNode or ObjectNode. For consistency the // variable is converted to such an object here. return objectMapper.valueToTree(result.getValue()); } else { return result.getValue(); } }
return null; } @Override public void convertVariableValue(Object variableValue, EngineRestVariable result) { if (variableValue != null) { if (!(variableValue instanceof JsonNode)) { throw new FlowableIllegalArgumentException("Converter can only convert tools.jackson.databind.JsonNode."); } result.setValue(variableValue); } else { result.setValue(null); } } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\JsonObjectRestVariableConverter.java
1
请完成以下Java代码
public class JsonQueryFilteringPropertyConverter extends JsonObjectConverter<QueryEntityRelationCondition> { protected static JsonQueryFilteringPropertyConverter INSTANCE = new JsonQueryFilteringPropertyConverter(); protected static JsonArrayConverter<List<QueryEntityRelationCondition>> ARRAY_CONVERTER = new JsonArrayOfObjectsConverter<>(INSTANCE); public static final String BASE_PROPERTY = "baseField"; public static final String COMPARISON_PROPERTY = "comparisonField"; public static final String SCALAR_VALUE = "value"; public JsonObject toJsonObject(QueryEntityRelationCondition filteringProperty) { JsonObject jsonObject = JsonUtil.createObject(); JsonUtil.addField(jsonObject, BASE_PROPERTY, filteringProperty.getProperty().getName()); QueryProperty comparisonProperty = filteringProperty.getComparisonProperty(); if (comparisonProperty != null) { JsonUtil.addField(jsonObject, COMPARISON_PROPERTY, comparisonProperty.getName()); } Object scalarValue = filteringProperty.getScalarValue(); if (scalarValue != null) { JsonUtil.addFieldRawValue(jsonObject, SCALAR_VALUE, scalarValue); } return jsonObject; } public QueryEntityRelationCondition toObject(JsonObject jsonObject) { // this is limited in that it allows only String values; // that is sufficient for current use case with task filters // but could be extended by a data type in the future String scalarValue = null; if (jsonObject.has(SCALAR_VALUE)) { scalarValue = JsonUtil.getString(jsonObject, SCALAR_VALUE);
} QueryProperty baseProperty = null; if (jsonObject.has(BASE_PROPERTY)) { baseProperty = new QueryPropertyImpl(JsonUtil.getString(jsonObject, BASE_PROPERTY)); } QueryProperty comparisonProperty = null; if (jsonObject.has(COMPARISON_PROPERTY)) { comparisonProperty = new QueryPropertyImpl(JsonUtil.getString(jsonObject, COMPARISON_PROPERTY)); } return new QueryEntityRelationCondition(baseProperty, comparisonProperty, scalarValue); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\json\JsonQueryFilteringPropertyConverter.java
1
请完成以下Java代码
private MenuNode createNewRecordNode(final MenuNode node, final String caption, final String captionBreadcrumb) { final AdWindowId adWindowId = node.getAdWindowIdOrNull(); if (adWindowId == null) { return null; } final ElementPermission windowPermission = getUserRolePermissions().checkWindowPermission(adWindowId); if (!windowPermission.hasWriteAccess()) { return null; } // // Caption (in menu) String captionEffective = caption; if (Check.isBlank(captionEffective)) { captionEffective = "New " + node.getCaption(); } // // Caption (breadcrumb) String captionBreadcrumbEffective = captionBreadcrumb; if (Check.isBlank(captionBreadcrumbEffective)) { captionBreadcrumbEffective = node.getCaptionBreadcrumb(); } return MenuNode.builder() .setAD_Menu_ID(node.getAD_Menu_ID()) .setCaption(captionEffective) .setCaptionBreadcrumb(captionBreadcrumbEffective) .setTypeNewRecord(adWindowId) .setMainTableName(node.getMainTableName()) .build(); } private MTreeNode retrieveRootNodeModel() { final UserMenuInfo userMenuInfo = getUserMenuInfo(); final AdTreeId adTreeId = userMenuInfo.getAdTreeId(); if (adTreeId == null) { throw new AdempiereException("Menu tree not found"); } final MTree mTree = MTree.builder() .setCtx(Env.getCtx()) .setTrxName(ITrx.TRXNAME_None) .setAD_Tree_ID(adTreeId.getRepoId()) .setEditable(false) .setClientTree(true) .setLanguage(getAD_Language()) .build(); final MTreeNode rootNodeModel = mTree.getRoot(); final AdMenuId rootMenuIdEffective = userMenuInfo.getRootMenuId(); if (rootMenuIdEffective != null) { final MTreeNode rootNodeModelEffective = rootNodeModel.findNode(rootMenuIdEffective.getRepoId()); if (rootNodeModelEffective != null) { return rootNodeModelEffective; } else { logger.warn("Cannot find Root_Menu_ID={} in {}", rootMenuIdEffective, mTree); } } return rootNodeModel;
} private UserMenuInfo getUserMenuInfo() { final IUserRolePermissions userRolePermissions = getUserRolePermissions(); if (!userRolePermissions.hasPermission(IUserRolePermissions.PERMISSION_MenuAvailable)) { return UserMenuInfo.NONE; } return userRolePermissions.getMenuInfo(); } public MenuTreeLoader setAD_Language(final String adLanguage) { this._adLanguage = adLanguage; return this; } @NonNull private String getAD_Language() { return _adLanguage; } private long getVersion() { if (_version < 0) { _version = userRolePermissionsDAO.getCacheVersion(); } return _version; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeLoader.java
1
请完成以下Java代码
public void setValues(UserTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers())); setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks); setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); formProperties = new ArrayList<FormProperty>(); if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) { formProperties.add(property.clone()); } } taskListeners = new ArrayList<ActivitiListener>(); if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getTaskListeners()) { taskListeners.add(listener.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
1
请完成以下Java代码
public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Belegart oder Verarbeitungsvorgaben */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document Type Sequence assignment. @param C_DocType_Sequence_ID Document Type Sequence assignment */ @Override public void setC_DocType_Sequence_ID (int C_DocType_Sequence_ID) { if (C_DocType_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, Integer.valueOf(C_DocType_Sequence_ID)); } /** Get Document Type Sequence assignment. @return Document Type Sequence assignment */ @Override public int getC_DocType_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Sequence getDocNoSequence() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class); }
@Override public void setDocNoSequence(org.compiere.model.I_AD_Sequence DocNoSequence) { set_ValueFromPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class, DocNoSequence); } /** Set Nummernfolgen für Belege. @param DocNoSequence_ID Document sequence determines the numbering of documents */ @Override public void setDocNoSequence_ID (int DocNoSequence_ID) { if (DocNoSequence_ID < 1) set_Value (COLUMNNAME_DocNoSequence_ID, null); else set_Value (COLUMNNAME_DocNoSequence_ID, Integer.valueOf(DocNoSequence_ID)); } /** Get Nummernfolgen für Belege. @return Document sequence determines the numbering of documents */ @Override public int getDocNoSequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DocNoSequence_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Sequence.java
1
请在Spring Boot框架中完成以下Java代码
public PhonecallSchedule getById(@NonNull final PhonecallScheduleId scheduleId) { final I_C_Phonecall_Schedule scheduleRecord = load(scheduleId, I_C_Phonecall_Schedule.class); return toPhonecallSchedule(scheduleRecord); } @VisibleForTesting static PhonecallSchedule toPhonecallSchedule(final I_C_Phonecall_Schedule record) { final PhonecallSchemaVersionId schemaVersionId = PhonecallSchemaVersionId.ofRepoId( record.getC_Phonecall_Schema_ID(), record.getC_Phonecall_Schema_Version_ID()); return PhonecallSchedule.builder() .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .bpartnerAndLocationId(BPartnerLocationId.ofRepoId(record.getC_BPartner_ID(), record.getC_BPartner_Location_ID())) .contactId(UserId.ofRepoId(record.getC_BP_Contact_ID())) .date(TimeUtil.asLocalDate(record.getPhonecallDate())) .startTime(TimeUtil.asZonedDateTime(record.getPhonecallTimeMin())) .endTime(TimeUtil.asZonedDateTime(record.getPhonecallTimeMax())) .id(PhonecallScheduleId.ofRepoId(record.getC_Phonecall_Schedule_ID())) .schemaVersionLineId(PhonecallSchemaVersionLineId.ofRepoId( schemaVersionId, record.getC_Phonecall_Schema_Version_Line_ID())) .isOrdered(record.isOrdered()) .isCalled(record.isCalled()) .salesRepId(UserId.ofRepoIdOrNull(record.getSalesRep_ID())) .description(record.getDescription()) .build(); }
public void markAsOrdered(@NonNull final PhonecallSchedule schedule) { final I_C_Phonecall_Schedule scheduleRecord = load(schedule.getId(), I_C_Phonecall_Schedule.class); scheduleRecord.setIsCalled(true); scheduleRecord.setIsOrdered(true); saveRecord(scheduleRecord); } public void markAsCalled(@NonNull final PhonecallSchedule schedule) { final I_C_Phonecall_Schedule scheduleRecord = load(schedule.getId(), I_C_Phonecall_Schedule.class); scheduleRecord.setIsCalled(true); saveRecord(scheduleRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallScheduleRepository.java
2
请完成以下Java代码
public Pipe<M, M> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<M, M>> listIterator() {
return pipeList.listIterator(); } @Override public ListIterator<Pipe<M, M>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<M, M>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java
1
请在Spring Boot框架中完成以下Java代码
public class AsyncJobAddedNotification implements CommandContextCloseListener { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncJobAddedNotification.class); protected JobInfoEntity job; protected AsyncExecutor asyncExecutor; public AsyncJobAddedNotification(JobInfoEntity job, AsyncExecutor asyncExecutor) { this.job = job; this.asyncExecutor = asyncExecutor; } @Override public void closed(CommandContext commandContext) { execute(commandContext); } public void execute(CommandContext commandContext) { asyncExecutor.executeAsyncJob(job); } @Override public void closing(CommandContext commandContext) { } @Override public void afterSessionsFlush(CommandContext commandContext) { }
@Override public void closeFailure(CommandContext commandContext) { } @Override public Integer order() { return 10; } @Override public boolean multipleAllowed() { return true; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobAddedNotification.java
2
请完成以下Java代码
public void addPayload(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setType(type); } else { payload.put(name, new EventPayload(name, type)); } } public void addPayload(EventPayload payload) { this.payload.put(payload.getName(), payload); } public void addCorrelation(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setCorrelationParameter(true);
} else { payload.put(name, EventPayload.correlation(name, type)); } } public void addFullPayload(String name) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setFullPayload(true); eventPayload.setCorrelationParameter(false); eventPayload.setHeader(false); } else { payload.put(name, EventPayload.fullPayload(name)); } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventModel.java
1
请在Spring Boot框架中完成以下Java代码
public OrderDeliveryAddress city(String city) { this.city = city; return this; } /** * Get city * @return city **/ @Schema(example = "Nürnberg", required = true, description = "") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o; return Objects.equals(this.gender, orderDeliveryAddress.gender) && Objects.equals(this.title, orderDeliveryAddress.title) && Objects.equals(this.name, orderDeliveryAddress.name) && Objects.equals(this.address, orderDeliveryAddress.address) && Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) && Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) && Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) && Objects.equals(this.city, orderDeliveryAddress.city); }
@Override public int hashCode() { return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderDeliveryAddress {\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n"); sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
2
请完成以下Java代码
public final class ServletBearerExchangeFilterFunction implements ExchangeFilterFunction { static final String SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES"; @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { // @formatter:off return oauth2Token().map((token) -> bearer(request, token)) .defaultIfEmpty(request) .flatMap(next::exchange); // @formatter:on } private Mono<OAuth2Token> oauth2Token() { // @formatter:off return Mono.deferContextual(Mono::just) .cast(Context.class) .flatMap(this::currentAuthentication) .filter((authentication) -> authentication.getCredentials() instanceof OAuth2Token) .map(Authentication::getCredentials) .cast(OAuth2Token.class); // @formatter:on }
private Mono<Authentication> currentAuthentication(Context ctx) { return Mono.justOrEmpty(getAttribute(ctx, Authentication.class)); } private <T> T getAttribute(Context ctx, Class<T> clazz) { // NOTE: SecurityReactorContextConfiguration.SecurityReactorContextSubscriber adds // this key if (!ctx.hasKey(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY)) { return null; } Map<Class<T>, T> attributes = ctx.get(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY); return attributes.get(clazz); } private ClientRequest bearer(ClientRequest request, OAuth2Token token) { // @formatter:off return ClientRequest.from(request) .headers((headers) -> headers.setBearerAuth(token.getTokenValue())) .build(); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\reactive\function\client\ServletBearerExchangeFilterFunction.java
1
请完成以下Java代码
public MQuery getQuery(MGoalRestriction[] restrictions, String MeasureDisplay, Timestamp date, int R_Status_ID, final IUserRolePermissions role) { String dateColumn = "Created"; String orgColumn = "AD_Org_ID"; String bpColumn = "C_BPartner_ID"; String pColumn = "M_Product_ID"; // MQuery query = new MQuery("R_Request"); query.addRestriction("R_RequestType_ID", Operator.EQUAL, getR_RequestType_ID()); // String where = null; if (R_Status_ID != 0) where = "R_Status_ID=" + R_Status_ID; else { String trunc = "D"; if (MGoal.MEASUREDISPLAY_Year.equals(MeasureDisplay)) trunc = "Y"; else if (MGoal.MEASUREDISPLAY_Quarter.equals(MeasureDisplay)) trunc = "Q";
else if (MGoal.MEASUREDISPLAY_Month.equals(MeasureDisplay)) trunc = "MM"; else if (MGoal.MEASUREDISPLAY_Week.equals(MeasureDisplay)) trunc = "W"; // else if (MGoal.MEASUREDISPLAY_Day.equals(MeasureDisplay)) // trunc = "D"; where = "TRUNC(" + dateColumn + ",'" + trunc + "')=TRUNC(" + DB.TO_DATE(date) + ",'" + trunc + "')"; } String whereRestriction = MMeasureCalc.addRestrictions(where + " AND Processed<>'Y' ", true, restrictions, role, "R_Request", orgColumn, bpColumn, pColumn); query.addRestriction(whereRestriction); query.setRecordCount(1); return query; } // getQuery } // MRequestType
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequestType.java
1
请完成以下Java代码
private static String createJWT() { String jwtToken = JWT.create() .withIssuer(ISSUER) .withSubject(SUBJECT) .withClaim(DATA_CLAIM, DATA) .withIssuedAt(new Date()) .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS)) .withJWTId(UUID.randomUUID() .toString()) .withNotBefore(new Date(System.currentTimeMillis() + 1000L)) .sign(algorithm); return jwtToken; } private static DecodedJWT verifyJWT(String jwtToken) { try { DecodedJWT decodedJWT = verifier.verify(jwtToken); return decodedJWT; } catch (JWTVerificationException e) { System.out.println(e.getMessage()); } return null; } private static boolean isJWTExpired(DecodedJWT decodedJWT) { Date expiresAt = decodedJWT.getExpiresAt(); return expiresAt.getTime() < System.currentTimeMillis(); } private static String getClaim(DecodedJWT decodedJWT, String claimName) { Claim claim = decodedJWT.getClaim(claimName); return claim != null ? claim.asString() : null; } public static void main(String args[]) throws InterruptedException { initialize();
String jwtToken = createJWT(); System.out.println("Created JWT : " + jwtToken); DecodedJWT decodedJWT = verifyJWT(jwtToken); if (decodedJWT == null) { System.out.println("JWT Verification Failed"); } Thread.sleep(1000L); decodedJWT = verifyJWT(jwtToken); if (decodedJWT != null) { System.out.println("Token Issued At : " + decodedJWT.getIssuedAt()); System.out.println("Token Expires At : " + decodedJWT.getExpiresAt()); System.out.println("Subject : " + decodedJWT.getSubject()); System.out.println("Data : " + getClaim(decodedJWT, DATA_CLAIM)); System.out.println("Header : " + decodedJWT.getHeader()); System.out.println("Payload : " + decodedJWT.getPayload()); System.out.println("Signature : " + decodedJWT.getSignature()); System.out.println("Algorithm : " + decodedJWT.getAlgorithm()); System.out.println("JWT Id : " + decodedJWT.getId()); Boolean isExpired = isJWTExpired(decodedJWT); System.out.println("Is Expired : " + isExpired); } } }
repos\tutorials-master\security-modules\jwt\src\main\java\com\baeldung\jwt\auth0\Auth0JsonWebToken.java
1
请完成以下Java代码
public static void changeDLMCoalesceLevel(final Connection c, final int dlmCoalesceLevel) throws SQLException { changeSetting(c, SETTING_DLM_COALESCE_LEVEL, dlmCoalesceLevel); } public static void changeDLMLevel(final Connection c, final int dlmLevel) throws SQLException { changeSetting(c, SETTING_DLM_LEVEL, dlmLevel); } public static int retrieveCurrentDLMLevel(final Connection c) throws SQLException { return restrieveSetting(c, FUNCTION_DLM_LEVEL); } public static int retrieveCurrentDLMCoalesceLevel(final Connection c) throws SQLException { return restrieveSetting(c, FUNCTION_DLM_COALESCE_LEVEL); } private static int restrieveSetting(final Connection c, final String functionName) throws SQLException { final ResultSet rs = c.prepareStatement("SELECT " + functionName).executeQuery(); final Integer dlmLevel = rs.next() ? rs.getInt(1) : null;
Check.errorIf(dlmLevel == null, "Unable to retrieve the current setting for {} from the DB", SETTING_DLM_COALESCE_LEVEL); return dlmLevel; } private static void changeSetting(final Connection c, final String setting, final int value) throws SQLException { final String valueStr = Integer.toString(value); changeSetting(c, setting, valueStr); } private static void changeSetting(final Connection c, final String setting, final String valueStr) throws SQLException { final PreparedStatement ps = c.prepareStatement("select set_config('" + setting + "'::text, ?::text, ?::boolean)"); ps.setString(1, valueStr); ps.setBoolean(2, false); ps.execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMConnectionUtils.java
1
请完成以下Java代码
default I_AD_Org getById(@NonNull final OrgId orgId) { return retrieveOrg(Env.getCtx(), orgId.getRepoId()); } default I_AD_Org getById(final int adOrgId) { return retrieveOrg(Env.getCtx(), adOrgId); } default String retrieveOrgName(final int adOrgId) { return retrieveOrgName(OrgId.ofRepoIdOrNull(adOrgId)); } default String retrieveOrgName(@Nullable final OrgId adOrgId) { if (adOrgId == null) { return "?"; } else if (adOrgId.isAny()) { return "*"; } else { final I_AD_Org orgRecord = getById(adOrgId); return orgRecord != null ? orgRecord.getName() : "<" + adOrgId.getRepoId() + ">"; } } default String retrieveOrgValue(final int adOrgId) { return retrieveOrgValue(OrgId.ofRepoIdOrNull(adOrgId)); } @NonNull default String retrieveOrgValue(@Nullable final OrgId adOrgId) { if (adOrgId == null) { return "?"; } else if (adOrgId.isAny()) { //return "*"; return "0"; // "*" is the name of the "any" org, but it's org-value is 0 } else { final I_AD_Org orgRecord = getById(adOrgId); return orgRecord != null ? orgRecord.getValue() : "<" + adOrgId.getRepoId() + ">"; } } List<I_AD_Org> getByIds(Set<OrgId> orgIds); List<I_AD_Org> getAllActiveOrgs(); OrgInfo createOrUpdateOrgInfo(OrgInfoUpdateRequest request); OrgInfo getOrgInfoById(OrgId adOrgId);
OrgInfo getOrgInfoByIdInTrx(OrgId adOrgId); WarehouseId getOrgWarehouseId(OrgId orgId); WarehouseId getOrgPOWarehouseId(OrgId orgId); WarehouseId getOrgDropshipWarehouseId(OrgId orgId); /** * Search for the organization when the value is known * * @return AD_Org Object if the organization was found, null otherwise. */ I_AD_Org retrieveOrganizationByValue(Properties ctx, String value); List<I_AD_Org> retrieveClientOrgs(Properties ctx, int adClientId); default List<I_AD_Org> retrieveClientOrgs(final int adClientId) { return retrieveClientOrgs(Env.getCtx(), adClientId); } /** @return organization's time zone or system time zone; never returns null */ ZoneId getTimeZone(OrgId orgId); /** * @return true if the given org falls under the european One-Stop-Shop (OSS) regulations */ boolean isEUOneStopShop(@NonNull OrgId orgId); UserGroupId getSupplierApprovalExpirationNotifyUserGroupID(OrgId ofRepoId); UserGroupId getPartnerCreatedFromAnotherOrgNotifyUserGroupID(OrgId orgId); String getOrgName(@NonNull OrgId orgId); boolean isAutoInvoiceFlatrateTerm(OrgId orgId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\IOrgDAO.java
1
请完成以下Java代码
public boolean isIncidentsToInclude() { return includeIncidents || includeIncidentsForType != null; } public String getProcessDefinitionId() { return processDefinitionId; } protected void checkQueryOk() { super.checkQueryOk(); ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } } // getter/setter for authorization check public List<PermissionCheck> getProcessInstancePermissionChecks() { return processInstancePermissionChecks; } public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) { this.processInstancePermissionChecks = processInstancePermissionChecks; } public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) { processInstancePermissionChecks.addAll(permissionChecks);
} public List<PermissionCheck> getJobPermissionChecks() { return jobPermissionChecks; } public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) { this.jobPermissionChecks = jobPermissionChecks; } public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) { jobPermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getIncidentPermissionChecks() { return incidentPermissionChecks; } public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) { this.incidentPermissionChecks = incidentPermissionChecks; } public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) { incidentPermissionChecks.addAll(permissionChecks); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityStatisticsQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; } public Date getDeployedAfter() { return deployedAfter; } public Date getDeployedAt() { return deployedAt; } 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 String getVersionTag() { return versionTag; } public String getVersionTagLike() { return versionTagLike; } public boolean isLatest() { return latest; } public boolean isShouldJoinDeploymentTable() { return shouldJoinDeploymentTable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java
2
请完成以下Java代码
public JacksonJsonSerde<T> noTypeInfo() { this.jsonSerializer.noTypeInfo(); return this; } /** * Don't remove type information headers after deserialization. * @return the serde. */ public JacksonJsonSerde<T> dontRemoveTypeHeaders() { this.jsonDeserializer.dontRemoveTypeHeaders(); return this; } /** * Ignore type information headers and use the configured target class. * @return the serde. */
public JacksonJsonSerde<T> ignoreTypeHeaders() { this.jsonDeserializer.ignoreTypeHeaders(); return this; } /** * Use the supplied {@link JacksonJavaTypeMapper}. * @param mapper the mapper. * @return the serde. */ public JacksonJsonSerde<T> typeMapper(JacksonJavaTypeMapper mapper) { this.jsonSerializer.setTypeMapper(mapper); this.jsonDeserializer.setTypeMapper(mapper); return this; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JacksonJsonSerde.java
1
请完成以下Java代码
public void setIsCreateCounter (boolean IsCreateCounter) { set_Value (COLUMNNAME_IsCreateCounter, Boolean.valueOf(IsCreateCounter)); } /** Get Create Counter Document. @return Create Counter Document */ public boolean isCreateCounter () { Object oo = get_Value(COLUMNNAME_IsCreateCounter); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity
*/ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocTypeCounter.java
1
请完成以下Java代码
public static Optional<ExternalSystemId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } @JsonCreator public static ExternalSystemId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, ExternalSystemId.class, ExternalSystemId::ofRepoId); } public static int toRepoId(@Nullable final ExternalSystemId id) { return id != null ? id.getRepoId() : -1; }
private ExternalSystemId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, I_ExternalSystem.COLUMNNAME_ExternalSystem_ID); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final ExternalSystemId o1, @Nullable final ExternalSystemId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemId.java
1
请完成以下Java代码
public String getName() { return name; } public EnableProcessApplication getAnnotation() { return annotation; } @Override public int hashCode() { return Objects.hash(name, annotation); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof AnnotatedBean)) { return false; } AnnotatedBean other = (AnnotatedBean) obj; return Objects.equals(name, other.name) && Objects.equals(annotation, other.annotation); } @Override public String toString() { return "AnnotatedBean [name=" + name + ", annotation=" + annotation + "]"; } } /** * Finds all beans with annotation. * * @throws IllegalStateException if more than one bean is found */ public static Function<ApplicationContext, Optional<AnnotatedBean>> getAnnotatedBean = applicationContext -> { final Set<Entry<String, Object>> beans = Optional.ofNullable(applicationContext.getBeansWithAnnotation(EnableProcessApplication.class)) .map(Map::entrySet) .orElse(Collections.emptySet()); return beans.stream().filter(ANNOTATED_WITH_ENABLEPROCESSAPPLICATION) .map(e -> AnnotatedBean.of(e.getKey(), e.getValue())) .reduce( (u,v) -> { throw new IllegalStateException("requires exactly one bean to be annotated with @EnableProcessApplication, found: " + beans);
}); }; public static Function<EnableProcessApplication, Optional<String>> getAnnotationValue = annotation -> Optional.of(annotation) .map(EnableProcessApplication::value) .filter(StringUtils::isNotBlank); public static Function<AnnotatedBean, String> getName = pair -> Optional.of(pair.getAnnotation()).flatMap(getAnnotationValue).orElse(pair.getName()); public static Function<ApplicationContext, Optional<String>> getProcessApplicationName = applicationContext -> getAnnotatedBean.apply(applicationContext).map(getName); @Override public Optional<String> get() { return getProcessApplicationName.apply(applicationContext); } @Override public Optional<String> apply(Optional<String> springApplicationName) { Optional<String> processApplicationName = GetProcessApplicationNameFromAnnotation.getProcessApplicationName.apply(applicationContext); if (processApplicationName.isPresent()) { return processApplicationName; } else if (springApplicationName.isPresent()) { return springApplicationName; } return Optional.empty(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\GetProcessApplicationNameFromAnnotation.java
1
请完成以下Java代码
public int getAD_User_Import_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Import_ID); } @Override public void setDescription (final @Nullable String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setEndpointName (final String EndpointName) { set_Value (COLUMNNAME_EndpointName, EndpointName); } @Override public String getEndpointName() { return get_ValueAsString(COLUMNNAME_EndpointName); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); }
@Override public void setExternalSystem_Config_ScriptedImportConversion_ID (final int ExternalSystem_Config_ScriptedImportConversion_ID) { if (ExternalSystem_Config_ScriptedImportConversion_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, ExternalSystem_Config_ScriptedImportConversion_ID); } @Override public int getExternalSystem_Config_ScriptedImportConversion_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setScriptIdentifier (final String ScriptIdentifier) { set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier); } @Override public String getScriptIdentifier() { return get_ValueAsString(COLUMNNAME_ScriptIdentifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedImportConversion.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isCountEnabled() { return isCountEnabled; } public boolean getIsCountEnabled() { return isCountEnabled; } @Override public void setCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } public void setIsCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } @Override public void setVariableCount(int variableCount) { this.variableCount = variableCount; } @Override public int getVariableCount() { return variableCount; } @Override public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount;
} @Override public int getIdentityLinkCount() { return identityLinkCount; } @Override public int getSubTaskCount() { return subTaskCount; } @Override public void setSubTaskCount(int subTaskCount) { this.subTaskCount = subTaskCount; } @Override public boolean isIdentityLinksInitialized() { return isIdentityLinksInitialized; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\TaskEntityImpl.java
2
请完成以下Java代码
protected void ensureCaseExecutionInitialized() { if ((caseExecution == null) && (caseExecutionId != null)) { caseExecution = findCaseExecutionById(caseExecutionId); } } public void setCaseExecution(CmmnExecution caseExecution) { this.caseExecution = (CaseExecutionEntity) caseExecution; if (caseExecution != null) { caseExecutionId = caseExecution.getId(); } else { caseExecutionId = null; } } // source case execution id ////////////////////////////////////////////////// public String getSourceCaseExecutionId() { return sourceCaseExecutionId; } public CmmnExecution getSourceCaseExecution() { ensureSourceCaseExecutionInitialized(); return sourceCaseExecution; } protected void ensureSourceCaseExecutionInitialized() { if ((sourceCaseExecution == null) && (sourceCaseExecutionId != null)) { sourceCaseExecution = findCaseExecutionById(sourceCaseExecutionId); } } public void setSourceCaseExecution(CmmnExecution sourceCaseExecution) { this.sourceCaseExecution = (CaseExecutionEntity) sourceCaseExecution; if (sourceCaseExecution != null) { sourceCaseExecutionId = sourceCaseExecution.getId(); } else { sourceCaseExecutionId = null; } } // persistence ///////////////////////////////////////////////////////// public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public int getRevisionNext() { return revision + 1; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void forceUpdate() {
this.forcedUpdate = true; } public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("satisfied", isSatisfied()); if (forcedUpdate) { persistentState.put("forcedUpdate", Boolean.TRUE); } return persistentState; } // helper //////////////////////////////////////////////////////////////////// protected CaseExecutionEntity findCaseExecutionById(String caseExecutionId) { return Context .getCommandContext() .getCaseExecutionManager() .findCaseExecutionById(caseExecutionId); } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); if (caseExecutionId != null) { referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } if (caseInstanceId != null) { referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class); } return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLike() { return tenantIdLike; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public Boolean getWithoutProcessInstanceId() { return withoutProcessInstanceId; } public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) { this.withoutProcessInstanceId = withoutProcessInstanceId; } public String getCandidateOrAssigned() { return candidateOrAssigned; } public void setCandidateOrAssigned(String candidateOrAssigned) { this.candidateOrAssigned = candidateOrAssigned; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public List<String> getCategoryIn() { return categoryIn; } public void setCategoryIn(List<String> categoryIn) { this.categoryIn = categoryIn; }
public List<String> getCategoryNotIn() { return categoryNotIn; } public void setCategoryNotIn(List<String> categoryNotIn) { this.categoryNotIn = categoryNotIn; } public Boolean getWithoutCategory() { return withoutCategory; } public void setWithoutCategory(Boolean withoutCategory) { this.withoutCategory = withoutCategory; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java
2
请完成以下Java代码
public static PurchaseOrderFromItemsAggregator newInstance() { return new PurchaseOrderFromItemsAggregator(); } public static PurchaseOrderFromItemsAggregator newInstance(@Nullable final DocTypeId docType) { return new PurchaseOrderFromItemsAggregator(docType); } private final OrderUserNotifications userNotifications = OrderUserNotifications.newInstance(); private final DocTypeId docType; private final List<I_C_Order> createdPurchaseOrders = new ArrayList<>(); @VisibleForTesting PurchaseOrderFromItemsAggregator() { this(null); } @VisibleForTesting PurchaseOrderFromItemsAggregator(@Nullable final DocTypeId docType) { setItemAggregationKeyBuilder(PurchaseOrderAggregationKey::fromPurchaseOrderItem); this.docType = docType; } @Override protected PurchaseOrderFromItemFactory createGroup( @NonNull final Object itemHashKey, final PurchaseOrderItem item_NOTUSED) { final PurchaseOrderAggregationKey orderAggregationKey = PurchaseOrderAggregationKey.cast(itemHashKey); return PurchaseOrderFromItemFactory.builder() .orderAggregationKey(orderAggregationKey) .userNotifications(userNotifications) .docType(docType) .build(); }
@Override protected void closeGroup(@NonNull final PurchaseOrderFromItemFactory orderFactory) { final I_C_Order newPurchaseOrder = orderFactory.createAndComplete(); createdPurchaseOrders.add(newPurchaseOrder); } @Override protected void addItemToGroup( @NonNull final PurchaseOrderFromItemFactory orderFactory, @NonNull final PurchaseOrderItem candidate) { orderFactory.addCandidate(candidate); } @VisibleForTesting List<I_C_Order> getCreatedPurchaseOrders() { return ImmutableList.copyOf(createdPurchaseOrders); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseOrderFromItemsAggregator.java
1
请完成以下Java代码
public class SignalValidator extends ValidatorImpl { @Override public void validate(BpmnModel bpmnModel, List<ValidationError> errors) { Collection<Signal> signals = bpmnModel.getSignals(); if (signals != null && !signals.isEmpty()) { for (Signal signal : signals) { if (StringUtils.isEmpty(signal.getId())) { addError(errors, Problems.SIGNAL_MISSING_ID, signal); } if (StringUtils.isEmpty(signal.getName())) { addError(errors, Problems.SIGNAL_MISSING_NAME, signal); } if ( !StringUtils.isEmpty(signal.getName()) && duplicateName(signals, signal.getId(), signal.getName()) ) { addError(errors, Problems.SIGNAL_DUPLICATE_NAME, signal); } if ( signal.getScope() != null && !signal.getScope().equals(Signal.SCOPE_GLOBAL) &&
!signal.getScope().equals(Signal.SCOPE_PROCESS_INSTANCE) ) { addError(errors, Problems.SIGNAL_INVALID_SCOPE, signal); } } } } protected boolean duplicateName(Collection<Signal> signals, String id, String name) { for (Signal signal : signals) { if (id != null && signal.getId() != null) { if (name.equals(signal.getName()) && !id.equals(signal.getId())) { return true; } } } return false; } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\SignalValidator.java
1
请完成以下Java代码
public class MTask extends X_AD_Task { /** * */ private static final long serialVersionUID = -3798377076931060582L; /** * Standard Constructor * @param ctx context * @param AD_Task_ID id * @param trxName trx */ public MTask (Properties ctx, int AD_Task_ID, String trxName) { super (ctx, AD_Task_ID, trxName); } // MTask /** * Load Cosntructor * @param ctx ctx * @param rs result set * @param trxName trx */ public MTask (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MTask /** Actual Task */ private Task m_task = null; /** * Execute Task and wait * @return execution info */ public String execute() { String cmd = Msg.parseTranslation(Env.getCtx(), getOS_Command()).trim(); if (cmd == null || cmd.equals("")) return "Cannot execute '" + getOS_Command() + "'"; // if (isServerProcess()) return executeRemote(cmd); return executeLocal(cmd); } // execute /** * Execute Task locally and wait * @param cmd command * @return execution info */ public String executeLocal(String cmd) { log.info(cmd); if (m_task != null && m_task.isAlive()) m_task.interrupt(); m_task = new Task(cmd); m_task.start(); StringBuffer sb = new StringBuffer(); while (true) {
// Give it a bit of time try { Thread.sleep(500); } catch (InterruptedException ioe) { log.error(cmd, ioe); } // Info to user //metas: c.ghita@metas.ro : start sb.append(m_task.getOut()); if (m_task.getOut().length() > 0) sb.append("\n-----------\n"); sb.append(m_task.getErr()); if (m_task.getErr().length() > 0) sb.append("\n-----------"); //metas: c.ghita@metas.ro : end // Are we done? if (!m_task.isAlive()) break; } log.info("done"); return sb.toString(); } // executeLocal /** * Execute Task locally and wait * @param cmd command * @return execution info */ public String executeRemote(String cmd) { log.info(cmd); return "Remote:\n"; } // executeRemote /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MTask["); sb.append(get_ID()) .append("-").append(getName()) .append(";Server=").append(isServerProcess()) .append(";").append(getOS_Command()) .append ("]"); return sb.toString (); } // toString /* * metas: c.ghita@metas.ro * get Task */ public Task getTask() { return m_task; } } // MTask
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTask.java
1
请在Spring Boot框架中完成以下Java代码
public void updateEventSubscription(EventSubscriptionEntity eventSubscription) { getEventSubscriptionEntityManager().update(eventSubscription); } @Override public boolean lockEventSubscription(String eventSubscriptionId) { return getEventSubscriptionEntityManager().lockEventSubscription(eventSubscriptionId); } @Override public void unlockEventSubscription(String eventSubscriptionId) { getEventSubscriptionEntityManager().unlockEventSubscription(eventSubscriptionId); } @Override public void deleteEventSubscription(EventSubscriptionEntity eventSubscription) { getEventSubscriptionEntityManager().delete(eventSubscription); } @Override public void deleteEventSubscriptionsByExecutionId(String executionId) { getEventSubscriptionEntityManager().deleteEventSubscriptionsByExecutionId(executionId); } @Override public void deleteEventSubscriptionsForScopeIdAndType(String scopeId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeIdAndType(scopeId, scopeType); } @Override public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinition(processDefinitionId); } @Override public void deleteEventSubscriptionsForScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndType(scopeDefinitionId, scopeType); } @Override public void deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(String scopeDefinitionId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(scopeDefinitionId, scopeType); } @Override public void deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(String processDefinitionId, String eventType, String activityId, String configuration) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(processDefinitionId, eventType, activityId, configuration); } @Override public void deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(String scopeDefinitionId, String eventType, String configuration) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(scopeDefinitionId, eventType, configuration); } public EventSubscription createEventSubscription(EventSubscriptionBuilder builder) { return getEventSubscriptionEntityManager().createEventSubscription(builder); } public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return configuration.getEventSubscriptionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionServiceImpl.java
2
请完成以下Java代码
public void setU_RoleMenu_ID (int U_RoleMenu_ID) { if (U_RoleMenu_ID < 1) set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, null); else set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, Integer.valueOf(U_RoleMenu_ID)); } /** Get Role Menu. @return Role Menu */ public int getU_RoleMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_RoleMenu_ID); if (ii == null) return 0; return ii.intValue(); } public I_U_WebMenu getU_WebMenu() throws RuntimeException { return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name) .getPO(getU_WebMenu_ID(), get_TrxName()); } /** Set Web Menu. @param U_WebMenu_ID Web Menu */ public void setU_WebMenu_ID (int U_WebMenu_ID)
{ if (U_WebMenu_ID < 1) set_Value (COLUMNNAME_U_WebMenu_ID, null); else set_Value (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID)); } /** Get Web Menu. @return Web Menu */ public int getU_WebMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_RoleMenu.java
1
请完成以下Java代码
private AllocableHUsList getAvailableHusForLine( @NonNull final PPOrderBOMLineId orderBOMLineId, @NonNull final LocatorId pickFromLocatorId) { final I_PP_Order_BOMLine orderBOMLine = ppOrderBOMBL.getOrderBOMLineById(orderBOMLineId); final RawMaterialsIssueStrategy issueStrategy = ppOrderRouting.getIssueStrategyForRawMaterialsActivity(); final RawMaterialsIssueStrategy actualStrategy = issueStrategy.applies(BOMComponentIssueMethod.ofNullableCode(orderBOMLine.getIssueMethod())) ? issueStrategy : RawMaterialsIssueStrategy.DEFAULT; final ProductId productId = ProductId.ofRepoId(orderBOMLine.getM_Product_ID()); switch (actualStrategy) { case AssignedHUsOnly: return allocableHUsMap.getAllocableHUs(AllocableHUsGroupingKey.onlySourceHUs(productId)); case DEFAULT: return allocableHUsMap.getAllocableHUs(AllocableHUsGroupingKey.of(productId, pickFromLocatorId)); default: throw new AdempiereException("Unknown RawMaterialsIssueStrategy") .appendParametersToMessage() .setParameter("RawMaterialsIssueStrategy", issueStrategy); } }
@NonNull private Stream<I_M_HU> streamIncludedTUs(@NonNull final AllocableHU allocableHU) { if (!handlingUnitsBL.isLoadingUnit(allocableHU.getTopLevelHU())) { return Stream.empty(); } return handlingUnitsDAO.retrieveIncludedHUs(allocableHU.getTopLevelHU()) .stream() .filter(handlingUnitsBL::isTransportUnitOrAggregate); } private static LocatorId getPickFromLocatorId(@NonNull final I_PP_Order_BOMLine orderBOMLine) { return LocatorId.ofRepoId(orderBOMLine.getM_Warehouse_ID(), orderBOMLine.getM_Locator_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\manufacturing\issue\plan\PPOrderIssuePlanCreateCommand.java
1
请完成以下Java代码
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { RuleEngineOriginatedNotificationInfo notificationInfo = RuleEngineOriginatedNotificationInfo.builder() .msgOriginator(msg.getOriginator()) .msgCustomerId(msg.getOriginator().getEntityType() == EntityType.CUSTOMER && msg.getOriginator().equals(msg.getCustomerId()) ? null : msg.getCustomerId()) .msgMetadata(msg.getMetaData().getData()) .msgData(JacksonUtil.toFlatMap(JacksonUtil.toJsonNode(msg.getData()))) .msgType(msg.getType()) .build(); NotificationRequest notificationRequest = NotificationRequest.builder() .tenantId(ctx.getTenantId()) .targets(config.getTargets()) .templateId(config.getTemplateId()) .info(notificationInfo) .additionalConfig(new NotificationRequestConfig()) .originatorEntityId(ctx.getSelf().getRuleChainId()) .build(); var tbMsg = ackIfNeeded(ctx, msg); var callback = new FutureCallback<NotificationRequestStats>() {
@Override public void onSuccess(NotificationRequestStats stats) { TbMsgMetaData metaData = tbMsg.getMetaData().copy(); metaData.putValue("notificationRequestResult", JacksonUtil.toString(stats)); tellSuccess(ctx, tbMsg.transform() .metaData(metaData) .build()); } @Override public void onFailure(Throwable e) { tellFailure(ctx, tbMsg, e); } }; var future = ctx.getNotificationExecutor().executeAsync(() -> ctx.getNotificationCenter().processNotificationRequest(ctx.getTenantId(), notificationRequest, callback)); DonAsynchron.withCallback(future, r -> {}, callback::onFailure); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\notification\TbNotificationNode.java
1
请完成以下Java代码
public class SizeBasedWorkpackagePrio implements IWorkpackagePrioStrategy { /** * Returns an instance with a <code>medium</code> default prio. The default prio will be used if there is no size-based configuration available. */ public static final IWorkpackagePrioStrategy INSTANCE = new SizeBasedWorkpackagePrio(ConstantWorkpackagePrio.medium()); private final ConstantWorkpackagePrio defaultPrio; /** * can be set from the outside to change the behavior for testing. */ private Function<Integer, ConstantWorkpackagePrio> alternativeSize2constantPrio = null; private SizeBasedWorkpackagePrio(final ConstantWorkpackagePrio defaultPrio) { this.defaultPrio = defaultPrio; } /** * Allow to inject an alternative function. Currently this is intended only for testing purposes, but that might change in future. * Note that by default this implementation uses {@link SysconfigBackedSizeBasedWorkpackagePrioConfig}. */ @VisibleForTesting public void setAlternativeSize2constantPrio(@Nullable final Function<Integer, ConstantWorkpackagePrio> size2constantPrio) { this.alternativeSize2constantPrio = size2constantPrio; }
@Override public String getPrioriy(final IWorkPackageQueue queue) { final int packageCount = queue.getLocalPackageCount(); final Function<Integer, ConstantWorkpackagePrio> size2constantPrioToUse; if (alternativeSize2constantPrio == null) { size2constantPrioToUse = new SysconfigBackedSizeBasedWorkpackagePrioConfig( queue.getCtx(), queue.getEnquingPackageProcessorInternalName(), defaultPrio); } else { size2constantPrioToUse = alternativeSize2constantPrio; } final ConstantWorkpackagePrio constantPrioForSize = size2constantPrioToUse.apply(packageCount); final IWorkPackageQueue ignored = null; return constantPrioForSize.getPrioriy(ignored); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\SizeBasedWorkpackagePrio.java
1
请完成以下Java代码
public final class CsrfAuthenticationStrategy implements SessionAuthenticationStrategy { private final Log logger = LogFactory.getLog(getClass()); private final CsrfTokenRepository tokenRepository; private CsrfTokenRequestHandler requestHandler = new XorCsrfTokenRequestAttributeHandler(); /** * Creates a new instance * @param tokenRepository the {@link CsrfTokenRepository} to use */ public CsrfAuthenticationStrategy(CsrfTokenRepository tokenRepository) { Assert.notNull(tokenRepository, "tokenRepository cannot be null"); this.tokenRepository = tokenRepository; } /** * Specify a {@link CsrfTokenRequestHandler} to use for making the {@code CsrfToken} * available as a request attribute. * @param requestHandler the {@link CsrfTokenRequestHandler} to use */
public void setRequestHandler(CsrfTokenRequestHandler requestHandler) { Assert.notNull(requestHandler, "requestHandler cannot be null"); this.requestHandler = requestHandler; } @Override public void onAuthentication(@Nullable Authentication authentication, HttpServletRequest request, HttpServletResponse response) throws SessionAuthenticationException { boolean containsToken = this.tokenRepository.loadToken(request) != null; if (containsToken) { this.tokenRepository.saveToken(null, request, response); DeferredCsrfToken deferredCsrfToken = this.tokenRepository.loadDeferredToken(request, response); this.requestHandler.handle(request, response, deferredCsrfToken); this.logger.debug("Replaced CSRF Token"); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfAuthenticationStrategy.java
1
请完成以下Java代码
public Boolean getUseCreateTime() { return useCreateTime; } public void setUseCreateTime(Boolean useCreateTime) { this.useCreateTime = useCreateTime; } public Boolean getDisableAutoFetching() { return disableAutoFetching; } public void setDisableAutoFetching(Boolean disableAutoFetching) { this.disableAutoFetching = disableAutoFetching; } public Boolean getDisableBackoffStrategy() { return disableBackoffStrategy; } public void setDisableBackoffStrategy(Boolean disableBackoffStrategy) { this.disableBackoffStrategy = disableBackoffStrategy; } public void fromAnnotation(EnableExternalTaskClient annotation) { String baseUrl = annotation.baseUrl(); setBaseUrl(isNull(baseUrl) ? null : baseUrl); int maxTasks = annotation.maxTasks(); setMaxTasks(isNull(maxTasks) ? null : maxTasks); String workerId = annotation.workerId(); setWorkerId(isNull(workerId) ? null : workerId); setUsePriority(annotation.usePriority()); setUseCreateTime(annotation.useCreateTime()); configureOrderByCreateTime(annotation);
long asyncResponseTimeout = annotation.asyncResponseTimeout(); setAsyncResponseTimeout(isNull(asyncResponseTimeout) ? null : asyncResponseTimeout); setDisableAutoFetching(annotation.disableAutoFetching()); setDisableBackoffStrategy(annotation.disableBackoffStrategy()); long lockDuration = annotation.lockDuration(); setLockDuration(isNull(lockDuration) ? null : lockDuration); String dateFormat = annotation.dateFormat(); setDateFormat(isNull(dateFormat) ? null : dateFormat); String serializationFormat = annotation.defaultSerializationFormat(); setDefaultSerializationFormat(isNull(serializationFormat) ? null : serializationFormat); } protected void configureOrderByCreateTime(EnableExternalTaskClient annotation) { if (EnableExternalTaskClient.STRING_NULL_VALUE.equals(annotation.orderByCreateTime())) { setOrderByCreateTime(null); } else { setOrderByCreateTime(annotation.orderByCreateTime()); } } protected static boolean isNull(String value) { return ExternalTaskSubscription.STRING_NULL_VALUE.equals(value); } protected static boolean isNull(long value) { return LONG_NULL_VALUE == value; } protected static boolean isNull(int value) { return INT_NULL_VALUE == value; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientConfiguration.java
1
请完成以下Java代码
private <T> ReferenceBean<T> getConsumerBean(String beanName, Field field, Reference reference) throws BeansException { ReferenceBean<T> referenceBean = new ReferenceBean<T>(reference); if ((reference.interfaceClass() == null || reference.interfaceClass() == void.class) && (reference.interfaceName() == null || "".equals(reference.interfaceName()))) { referenceBean.setInterface(field.getType()); } Environment environment = this.applicationContext.getEnvironment(); String application = reference.application(); referenceBean.setApplication(this.parseApplication(application, this.properties, environment, beanName, field.getName(), "application", application)); String module = reference.module(); referenceBean.setModule(this.parseModule(module, this.properties, environment, beanName, field.getName(), "module", module)); String[] registries = reference.registry(); referenceBean.setRegistries(this.parseRegistries(registries, this.properties, environment, beanName, field.getName(), "registry")); String monitor = reference.monitor(); referenceBean.setMonitor(this.parseMonitor(monitor, this.properties, environment, beanName, field.getName(), "monitor", monitor));
String consumer = reference.consumer(); referenceBean.setConsumer(this.parseConsumer(consumer, this.properties, environment, beanName, field.getName(), "consumer", consumer)); referenceBean.setApplicationContext(DubboConsumerAutoConfiguration.this.applicationContext); return referenceBean; } @Override protected String buildErrorMsg(String... errors) { if (errors == null || errors.length != 4) { return super.buildErrorMsg(errors); } return new StringBuilder().append("beanName=").append(errors[0]).append(", field=") .append(errors[1]).append(", ").append(errors[2]).append("=").append(errors[3]) .append(" not found in multi configs").toString(); } }
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboConsumerAutoConfiguration.java
1
请完成以下Java代码
public void setCurrency(String currency) { this.currency = currency; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public List<String> getImageUrls() { return imageUrls; } public void setImageUrls(List<String> imageUrls) { this.imageUrls = imageUrls; } public List<String> getVideoUrls() { return videoUrls; } public void setVideoUrls(List<String> videoUrls) { this.videoUrls = videoUrls; } public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; } @Override public String toString() { return "ProductModel{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", status='" + status + '\'' + ", currency='" + currency + '\'' + ", price=" + price + ", imageUrls=" + imageUrls + ", videoUrls=" + videoUrls + ", stock=" + stock + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\model\ProductModel.java
1
请完成以下Java代码
private void registerCredential(HttpServletRequest request, HttpServletResponse response) throws IOException { WebAuthnRegistrationRequest registrationRequest = readRegistrationRequest(request); if (registrationRequest == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } PublicKeyCredentialCreationOptions options = this.creationOptionsRepository.load(request); if (options == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } this.creationOptionsRepository.save(request, response, null); CredentialRecord credentialRecord = this.rpOptions.registerCredential( new ImmutableRelyingPartyRegistrationRequest(options, registrationRequest.getPublicKey())); SuccessfulUserRegistrationResponse registrationResponse = new SuccessfulUserRegistrationResponse( credentialRecord); ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response); this.converter.write(registrationResponse, MediaType.APPLICATION_JSON, outputMessage); } private @Nullable WebAuthnRegistrationRequest readRegistrationRequest(HttpServletRequest request) { HttpInputMessage inputMessage = new ServletServerHttpRequest(request); try { return (WebAuthnRegistrationRequest) this.converter.read(WebAuthnRegistrationRequest.class, inputMessage); } catch (Exception ex) { logger.debug("Unable to parse WebAuthnRegistrationRequest", ex); return null; } } private void removeCredential(HttpServletRequest request, HttpServletResponse response, @Nullable String id) throws IOException {
this.userCredentials.delete(Bytes.fromBase64(id)); response.setStatus(HttpStatus.NO_CONTENT.value()); } static class WebAuthnRegistrationRequest { private @Nullable RelyingPartyPublicKey publicKey; @Nullable RelyingPartyPublicKey getPublicKey() { return this.publicKey; } void setPublicKey(RelyingPartyPublicKey publicKey) { this.publicKey = publicKey; } } public static class SuccessfulUserRegistrationResponse { private final CredentialRecord credentialRecord; SuccessfulUserRegistrationResponse(CredentialRecord credentialRecord) { this.credentialRecord = credentialRecord; } public boolean isSuccess() { return true; } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\registration\WebAuthnRegistrationFilter.java
1
请完成以下Java代码
public int getAD_WF_Node_Para_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Para_ID); } @Override public void setAttributeName (final java.lang.String AttributeName) { set_Value (COLUMNNAME_AttributeName, AttributeName); } @Override public java.lang.String getAttributeName() { return get_ValueAsString(COLUMNNAME_AttributeName); } @Override public void setAttributeValue (final java.lang.String AttributeValue) { set_Value (COLUMNNAME_AttributeValue, AttributeValue); } @Override public java.lang.String getAttributeValue() { return get_ValueAsString(COLUMNNAME_AttributeValue); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description);
} @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Para.java
1
请完成以下Java代码
public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11;
} public boolean isDisableHistory() { return disableHistory; } public void setDisableHistory(boolean disableHistory) { this.disableHistory = disableHistory; } public DmnElement getDmnElement() { return dmnElement; } public void setDmnElement(DmnElement dmnElement) { this.dmnElement = dmnElement; } public DecisionExecutionAuditContainer getDecisionExecution() { return decisionExecution; } public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) { this.decisionExecution = decisionExecution; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java
1
请在Spring Boot框架中完成以下Java代码
public void setAuthoritiesClaimName(String authoritiesClaimName) { this.authoritiesClaimName = authoritiesClaimName; } public void setAuthorityPrefix(String authorityPrefix) { this.authorityPrefix = authorityPrefix; } @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<String> tokenScopes = parseScopesClaim(jwt); if ( tokenScopes.isEmpty()) { return Collections.emptyList(); } return tokenScopes.stream() .map(s -> scopes.getOrDefault(s, s)) .map(s -> this.authorityPrefix + s) .map(SimpleGrantedAuthority::new) .collect(Collectors.toCollection(HashSet::new)); } protected Collection<String> parseScopesClaim(Jwt jwt) { String scopeClaim; if ( this.authoritiesClaimName == null ) { scopeClaim = WELL_KNOWN_AUTHORITIES_CLAIM_NAMES.stream() .filter(jwt::hasClaim) .findFirst() .orElse(null); if ( scopeClaim == null ) { return Collections.emptyList(); } } else { scopeClaim = this.authoritiesClaimName;
} Object v = jwt.getClaim(scopeClaim); if ( v == null ) { return Collections.emptyList(); } if ( v instanceof String) { return Arrays.asList(v.toString().split(" ")); } else if ( v instanceof Collection ) { return ((Collection<?>)v).stream() .map(Object::toString) .collect(Collectors.toCollection(HashSet::new)); } return Collections.emptyList(); } }
repos\tutorials-master\spring-security-modules\spring-security-oidc\src\main\java\com\baeldung\openid\oidc\jwtauthorities\config\MappingJwtGrantedAuthoritiesConverter.java
2
请完成以下Java代码
public java.lang.String getIsInvoiceEmailEnabled() { return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled); } @Override public void setIsMembershipContact (final boolean IsMembershipContact) { set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact); } @Override public boolean isMembershipContact() { return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact); } @Override public void setIsNewsletter (final boolean IsNewsletter) { set_Value (COLUMNNAME_IsNewsletter, IsNewsletter); } @Override public boolean isNewsletter() { return get_ValueAsBoolean(COLUMNNAME_IsNewsletter); } @Override public void setLastname (final @Nullable java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); } @Override public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone);
} @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
1
请完成以下Java代码
public synchronized Object put(Object key, Object value) { if (gridTab == null) throw new IllegalStateException("Method not supported (gridTab is null)"); if (gridTab.getCurrentRow() != row) { return ctx.put(key, value); } String columnName = getColumnName(key); if (columnName == null) { return ctx.put(key, value); } GridField field = gridTab.getField(columnName); if (field == null) { return ctx.put(key, value); } Object valueOld = field.getValue(); field.setValue(value, false); // inserting=false return valueOld; } @Override public synchronized void putAll(Map<? extends Object, ? extends Object> t) { for (Map.Entry<? extends Object, ? extends Object> e : t.entrySet()) put(e.getKey(), e.getValue()); } @Override public synchronized Object remove(Object key) { // TODO: implement for GridField values too return ctx.remove(key); } @Override public synchronized int size() { // TODO: implement for GridField values too return ctx.size(); } @Override public synchronized String toString() { // TODO: implement for GridField values too return ctx.toString(); } @Override public Collection<Object> values()
{ return ctx.values(); } @Override public String getProperty(String key) { // I need to override this method, because Properties.getProperty method // is calling super.get() instead of get() Object oval = get(key); return oval == null ? null : oval.toString(); } @Override public String get_ValueAsString(String variableName) { final int windowNo = getWindowNo(); final int tabNo = getTabNo(); // Check value at Tab level, fallback to Window level final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
1
请完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? authorities : Collections.emptyList(); } @Override public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; } @Override public boolean isAccountNonExpired() { return true; }
@Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return Boolean.TRUE.equals(active); } @InstanceName @DependsOnProperties({"firstName", "lastName", "username"}) public String getDisplayName() { return String.format("%s %s [%s]", (firstName != null ? firstName : ""), (lastName != null ? lastName : ""), username).trim(); } @Override public String getTimeZoneId() { return timeZoneId; } public void setTimeZoneId(final String timeZoneId) { this.timeZoneId = timeZoneId; } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java
1
请完成以下Java代码
public static class DisplayQRCode { @JsonProperty("code") String code; @lombok.Builder @JsonCreator private DisplayQRCode(@JsonProperty("code") @NonNull final String code) { this.code = code; } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Value @lombok.Builder public static class WebuiNewRecord { /** * If this string is used as field value * then the frontend will try to open the new record modal window to populate that field. * <p>
* Used mainly to trigger new BPartner. */ public static final String FIELD_VALUE_NEW = "NEW"; @NonNull String windowId; /** * Field values to be set by frontend, after the NEW record is created */ @NonNull @Singular Map<String, String> fieldValues; public enum TargetTab { SAME_TAB, NEW_TAB, } @NonNull @Builder.Default TargetTab targetTab = TargetTab.SAME_TAB; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutionResult.java
1
请在Spring Boot框架中完成以下Java代码
public T findOne(final long id) { return super.findOne(id); } @Override public List<T> findAll() { return super.findAll(); } @Override public void create(final T entity) { super.create(entity); } @Override
public T update(final T entity) { return super.update(entity); } @Override public void delete(final T entity) { super.delete(entity); } @Override public void deleteById(final long entityId) { super.deleteById(entityId); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\service\common\AbstractHibernateService.java
2
请在Spring Boot框架中完成以下Java代码
private JsonAuthenticateRequest getJsonAuthenticateRequest(@NonNull final JsonExternalSystemRequest request) { if (request.getAdPInstanceId() == null) { throw new RuntimeCamelException("Missing pInstance identifier!"); } final String authKey = request.getParameters().get(ExternalSystemConstants.PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY); if (authKey == null) { throw new RuntimeCamelException("Missing authKey from request!"); } final String externalSystemValue = request.getParameters().get(ExternalSystemConstants.PARAM_CHILD_CONFIG_VALUE); final String auditTrailEndpoint = request.getWriteAuditEndpoint(); return JsonAuthenticateRequest.builder() .grantedAuthority(RestServiceAuthority.WOO.getValue()) .authKey(authKey) .pInstance(request.getAdPInstanceId()) .externalSystemValue(externalSystemValue) .auditTrailEndpoint(auditTrailEndpoint) .orgCode(request.getOrgCode()) .build(); } private void prepareRestAPIContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final WOORestAPIContext context = WOORestAPIContext.builder() .request(request) .build(); exchange.setProperty(ROUTE_PROPERTY_WOO_REST_API_CONTEXT, context); } private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus status) { final WOORestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_WOO_REST_API_CONTEXT, WOORestAPIContext.class); final JsonExternalSystemRequest request = context.getRequest(); final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder() .status(status) .pInstanceId(request.getAdPInstanceId()) .build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder() .jsonStatusRequest(jsonStatusRequest) .externalSystemConfigType(getExternalSystemTypeCode()) .externalSystemChildConfigValue(request.getExternalSystemChildConfigValue()) .serviceValue(getServiceValue()) .build(); exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class); } @Override public String getServiceValue() { return "defaultRestAPIWOO"; } @Override public String getExternalSystemTypeCode() { return WOO_EXTERNAL_SYSTEM_NAME; } @Override public String getEnableCommand() { return ENABLE_RESOURCE_ROUTE; } @Override public String getDisableCommand() { return DISABLE_RESOURCE_ROUTE; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-woocommerce\src\main\java\de\metas\camel\externalsystems\woocommerce\restapi\RestAPIRouteBuilder.java
2
请完成以下Java代码
public void setQuickInput_CloseButton_Caption (final @Nullable java.lang.String QuickInput_CloseButton_Caption) { set_Value (COLUMNNAME_QuickInput_CloseButton_Caption, QuickInput_CloseButton_Caption); } @Override public java.lang.String getQuickInput_CloseButton_Caption() { return get_ValueAsString(COLUMNNAME_QuickInput_CloseButton_Caption); } @Override public void setQuickInput_OpenButton_Caption (final @Nullable java.lang.String QuickInput_OpenButton_Caption) { set_Value (COLUMNNAME_QuickInput_OpenButton_Caption, QuickInput_OpenButton_Caption); } @Override public java.lang.String getQuickInput_OpenButton_Caption() { return get_ValueAsString(COLUMNNAME_QuickInput_OpenButton_Caption); } @Override public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic) { set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic); } @Override public java.lang.String getReadOnlyLogic() { return get_ValueAsString(COLUMNNAME_ReadOnlyLogic); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTabLevel (final int TabLevel) { set_Value (COLUMNNAME_TabLevel, TabLevel); } @Override public int getTabLevel() { return get_ValueAsInt(COLUMNNAME_TabLevel); } @Override public org.compiere.model.I_AD_Tab getTemplate_Tab() { return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class); } @Override public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab)
{ set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab); } @Override public void setTemplate_Tab_ID (final int Template_Tab_ID) { if (Template_Tab_ID < 1) set_Value (COLUMNNAME_Template_Tab_ID, null); else set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID); } @Override public int getTemplate_Tab_ID() { return get_ValueAsInt(COLUMNNAME_Template_Tab_ID); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java
1
请在Spring Boot框架中完成以下Java代码
public class BookService implements IBookService { private static final Set<Book> BOOKS_DATA = initializeData(); @GraphQLQuery(name = "getBookWithTitle") public Book getBookWithTitle(@GraphQLArgument(name = "title") String title) { return BOOKS_DATA.stream() .filter(book -> book.getTitle().equals(title)) .findFirst() .orElse(null); } @GraphQLQuery(name = "getAllBooks", description = "Get all books") public List<Book> getAllBooks() { return new ArrayList<>(BOOKS_DATA); } @GraphQLMutation(name = "addBook") public Book addBook(@GraphQLArgument(name = "newBook") Book book) { BOOKS_DATA.add(book); return book; }
@GraphQLMutation(name = "updateBook") public Book updateBook(@GraphQLArgument(name = "modifiedBook") Book book) { BOOKS_DATA.removeIf(b -> Objects.equals(b.getId(), book.getId())); BOOKS_DATA.add(book); return book; } @GraphQLMutation(name = "deleteBook") public boolean deleteBook(@GraphQLArgument(name = "book") Book book) { return BOOKS_DATA.remove(book); } private static Set<Book> initializeData() { Book book = new Book(1, "J.R.R. Tolkien", "The Lord of the Rings"); Set<Book> books = new HashSet<>(); books.add(book); return books; } }
repos\tutorials-master\graphql-modules\graphql-spqr-boot-starter\src\main\java\com\baeldung\spqr\BookService.java
2
请完成以下Java代码
public Void execute(CommandContext commandContext) { JobEntity jobToDelete = null; for (String jobId : jobIds) { jobToDelete = commandContext.getJobEntityManager().findById(jobId); if (jobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete) ); } commandContext.getJobEntityManager().delete(jobToDelete); } else { TimerJobEntity timerJobToDelete = commandContext.getTimerJobEntityManager().findById(jobId);
if (timerJobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, timerJobToDelete) ); } commandContext.getTimerJobEntityManager().delete(timerJobToDelete); } } } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\CancelJobsCmd.java
1
请完成以下Java代码
public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_DI_EXTENSION; } @Override public boolean hasChildElements() { return false; } @Override protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { CmmnDiEdge edgeInfo = conversionHelper.getCurrentDiEdge(); if (edgeInfo == null) { return null; } boolean readyWithChildElements = false; try { while (!readyWithChildElements && xtr.hasNext()) { xtr.next(); if (xtr.isStartElement()) { if (CmmnXmlConstants.ELEMENT_DI_DOCKER.equals(xtr.getLocalName())) { String type = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TYPE); if ("source".equals(type) || "target".equals(type)) { GraphicInfo graphicInfo = new GraphicInfo(); graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_X))); graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_Y))); if ("source".equals(type)) { edgeInfo.setSourceDockerInfo(graphicInfo); } else { edgeInfo.setTargetDockerInfo(graphicInfo); }
} } } else if (xtr.isEndElement()) { if (CmmnXmlConstants.ELEMENT_DI_EXTENSION.equalsIgnoreCase(xtr.getLocalName())) { readyWithChildElements = true; } } } } catch (Exception ex) { LOGGER.error("Error processing CMMN document", ex); throw new XMLException("Error processing CMMN document", ex); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CmmnDiExtensionXmlConverter.java
1
请完成以下Java代码
public class JSONArrayToHashMapConverter { public static Map<String, Integer> convertUsingIterative (JsonArray jsonArray) { Map<String, Integer> hashMap = new HashMap<>(); for (JsonElement element : jsonArray) { JsonObject jsonObject = element.getAsJsonObject(); String type = jsonObject.get("name").getAsString(); Integer amount = jsonObject.get("age").getAsInt(); hashMap.put(type, amount); } return hashMap; } public static Map<String, Integer> convertUsingStreams (JsonArray jsonArray) { return StreamSupport.stream(jsonArray.spliterator(), false) .map(JsonElement::getAsJsonObject) .collect(Collectors.toMap(
jsonObject -> jsonObject.get("name").getAsString(), jsonObject -> jsonObject.get("age").getAsInt() )); } public static Map<String, Integer> convertUsingGson(JsonArray jsonArray) { Map<String, Integer> hashMap = new HashMap<>(); Gson gson = new Gson(); List<Map<String, Object>> list = new Gson().fromJson(jsonArray, List.class); for (Map<String, Object> map : list) { String type = (String) map.get("name"); Integer amount = ((Double) map.get("age")).intValue(); // Gson parses numbers as Double hashMap.put(type, amount); } return hashMap; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\jsonarraytohashmap\JSONArrayToHashMapConverter.java
1
请完成以下Java代码
public class StreamVsCollectionExample { static ArrayList<String> userNameSource = new ArrayList<>(); static { userNameSource.add("john"); userNameSource.add("smith"); userNameSource.add("tom"); userNameSource.add("rob"); userNameSource.add("charlie"); userNameSource.add("alfred"); } public static Stream<String> userNames() { return userNameSource.stream(); } public static List<String> userNameList() { return userNames().collect(Collectors.toList()); } public static Set<String> userNameSet() { return userNames().collect(Collectors.toSet()); } public static Map<String, String> userNameMap() { return userNames().collect(Collectors.toMap(u1 -> u1.toString(), u1 -> u1.toString())); } public static Stream<String> filterUserNames() { return userNames().filter(i -> i.length() >= 4); } public static Stream<String> sortUserNames() { return userNames().sorted(); } public static Stream<String> limitUserNames() { return userNames().limit(3); } public static Stream<String> sortFilterLimitUserNames() { return filterUserNames().sorted().limit(3); }
public static void printStream(Stream<String> stream) { stream.forEach(System.out::println); } public static void modifyList() { userNameSource.remove(2); } public static Map<String, String> modifyMap() { Map<String, String> userNameMap = userNameMap(); userNameMap.put("bob", "bob"); userNameMap.remove("alfred"); return userNameMap; } public static void tryStreamTraversal() { Stream<String> userNameStream = userNames(); userNameStream.forEach(System.out::println); try { userNameStream.forEach(System.out::println); } catch(IllegalStateException e) { System.out.println("stream has already been operated upon or closed"); } } public static void main(String[] args) { System.out.println(userNameMap()); System.out.println(modifyMap()); tryStreamTraversal(); Set<String> set = userNames().collect(Collectors.toCollection(TreeSet::new)); set.forEach(val -> System.out.println(val)); } }
repos\tutorials-master\core-java-modules\core-java-streams-3\src\main\java\com\baeldung\streams\streamvscollection\StreamVsCollectionExample.java
1
请完成以下Java代码
protected void updateProcessInstanceComment(String processInstanceId, CommandContext commandContext, CommentEntity comment) { checkUpdateProcessInstanceById(processInstanceId, commandContext); updateComment(commandContext, comment); } protected CommentEntity getComment(CommandContext commandContext) { if (taskId != null) { return commandContext.getCommentManager().findCommentByTaskIdAndCommentId(taskId, commentId); } return commandContext.getCommentManager().findCommentByProcessInstanceIdAndCommentId(processInstanceId, commentId); } protected PropertyChange getPropertyChange(String oldMessage) { return new PropertyChange("comment", oldMessage, message); } protected void checkTaskWork(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskWork(task); } }
protected void checkUpdateProcessInstanceById(String processInstanceId, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstanceById(processInstanceId); } } private void updateComment(CommandContext commandContext, CommentEntity comment) { String eventMessage = comment.toEventMessage(message); String userId = commandContext.getAuthenticatedUserId(); comment.setMessage(eventMessage); comment.setFullMessage(message); comment.setTime(ClockUtil.getCurrentTime()); comment.setAction(UserOperationLogEntry.OPERATION_TYPE_UPDATE_COMMENT); comment.setUserId(userId); commandContext.getDbEntityManager().update(CommentEntity.class, "updateComment", comment); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateCommentCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class UmsMemberReceiveAddressServiceImpl implements UmsMemberReceiveAddressService { @Autowired private UmsMemberService memberService; @Autowired private UmsMemberReceiveAddressMapper addressMapper; @Override public int add(UmsMemberReceiveAddress address) { UmsMember currentMember = memberService.getCurrentMember(); address.setMemberId(currentMember.getId()); return addressMapper.insert(address); } @Override public int delete(Long id) { UmsMember currentMember = memberService.getCurrentMember(); UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample(); example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andIdEqualTo(id); return addressMapper.deleteByExample(example); } @Override public int update(Long id, UmsMemberReceiveAddress address) { address.setId(null); UmsMember currentMember = memberService.getCurrentMember(); UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample(); example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andIdEqualTo(id); if(address.getDefaultStatus()==null){ address.setDefaultStatus(0); } if(address.getDefaultStatus()==1){ //先将原来的默认地址去除 UmsMemberReceiveAddress record= new UmsMemberReceiveAddress(); record.setDefaultStatus(0); UmsMemberReceiveAddressExample updateExample = new UmsMemberReceiveAddressExample();
updateExample.createCriteria() .andMemberIdEqualTo(currentMember.getId()) .andDefaultStatusEqualTo(1); addressMapper.updateByExampleSelective(record,updateExample); } return addressMapper.updateByExampleSelective(address,example); } @Override public List<UmsMemberReceiveAddress> list() { UmsMember currentMember = memberService.getCurrentMember(); UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample(); example.createCriteria().andMemberIdEqualTo(currentMember.getId()); return addressMapper.selectByExample(example); } @Override public UmsMemberReceiveAddress getItem(Long id) { UmsMember currentMember = memberService.getCurrentMember(); UmsMemberReceiveAddressExample example = new UmsMemberReceiveAddressExample(); example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andIdEqualTo(id); List<UmsMemberReceiveAddress> addressList = addressMapper.selectByExample(example); if(!CollectionUtils.isEmpty(addressList)){ return addressList.get(0); } return null; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberReceiveAddressServiceImpl.java
2
请完成以下Java代码
protected void putIntoCache(List<HalResource<?>> notCachedResources) { Cache cache = getCache(); for (HalResource<?> notCachedResource : notCachedResources) { cache.put(getResourceId(notCachedResource), notCachedResource); } } /** * @return the class of the entity which is resolved */ protected abstract Class<?> getHalResourceClass(); /** * @return a comparator for this HAL resource if not overridden sorting is skipped */
protected Comparator<HalResource<?>> getResourceComparator() { return null; } /** * @return the resolved resources which are currently not cached */ protected abstract List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine); /** * @return the id which identifies a resource in the cache */ protected abstract String getResourceId(HalResource<?> resource); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalCachingLinkResolver.java
1
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { if (!success) return success; updateHeader(); return true; } // afterSave @Override protected boolean afterDelete(boolean success) { if (!success) return success; updateHeader();
return true; } // afterDelete private void updateHeader() { String sql = "UPDATE M_Requisition r" + " SET TotalLines=" + "(SELECT COALESCE(SUM(LineNetAmt),0) FROM M_RequisitionLine rl " + "WHERE r.M_Requisition_ID=rl.M_Requisition_ID) " + "WHERE M_Requisition_ID=?"; DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { getM_Requisition_ID() }, ITrx.TRXNAME_ThreadInherited); m_parent = null; } } // MRequisitionLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisitionLine.java
1
请完成以下Java代码
public boolean initWindow (@Nullable final AdWindowId adWindowId, MQuery query) { this.setName("AWindow_" + (adWindowId != null ? adWindowId.getRepoId() : 0)); setAdWindowId(adWindowId); // boolean loadedOK = m_APanel.initPanel (0, adWindowId, query); if (loadedOK) { commonInit(); } return loadedOK; } // initWindow /** * Common Init. * After APanel loaded */ private void commonInit() { this.setJMenuBar(m_APanel.getMenuBar()); this.setTitle(m_APanel.getTitle()); // Image image = m_APanel.getImage(); if (image != null) { setIconImage(image); } this.setTransferHandler(new AttachmentDnDTransferHandler(m_APanel)); // metas: drag&drop support for attachments } // commonInit /************************************************************************* * Set Window Busy * @param busy busy */ public void setBusy (final boolean busy) { if (busy == m_glassPane.isVisible()) { return; } log.debug("set busy: {}, window={}", busy, this); m_glassPane.setMessage(null); m_glassPane.setVisible(busy); if (busy) { m_glassPane.requestFocus(); } } // setBusy /** * Set Busy Message * @param AD_Message message */ public void setBusyMessage (String AD_Message) { m_glassPane.setMessage(AD_Message); } public void setBusyMessagePlain(final String messagePlain) { m_glassPane.setMessagePlain(messagePlain); } /** * Set and start Busy Counter * @param time in seconds */ public void setBusyTimer (int time) { m_glassPane.setBusyTimer (time); } // setBusyTimer /** * Window Events * @param e event */ @Override protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); // System.out.println(">> Apps WE_" + e.getID() // + " Frames=" + getFrames().length // + " " + e); } // processWindowEvent /** * Get Application Panel * @return application panel */ public APanel getAPanel() { return m_APanel; } // getAPanel /** * Dispose */
@Override public void dispose() { if (Env.hideWindow(this)) { return; } log.debug("disposing: {}", this); if (m_APanel != null) { m_APanel.dispose(); } m_APanel = null; this.removeAll(); super.dispose(); // System.gc(); } // dispose /** * Get Window No of Panel * @return window no */ public int getWindowNo() { if (m_APanel != null) { return m_APanel.getWindowNo(); } return 0; } // getWindowNo /** * String Representation * @return Name */ @Override public String toString() { return getName() + "_" + getWindowNo(); } // toString // metas: begin public GridWindow getGridWindow() { if (m_APanel == null) { return null; } return m_APanel.getGridWorkbench().getMWindowById(getAdWindowId()); } // metas: end } // AWindow
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AWindow.java
1
请在Spring Boot框架中完成以下Java代码
public static PackingItemParts newInstance() { return new PackingItemParts(); } public static PackingItemParts of(@NonNull final PackingItemPart part) { return new PackingItemParts(ImmutableList.of(part)); } public static Collector<PackingItemPart, ?, PackingItemParts> collect() { return GuavaCollectors.collectUsingListAccumulator(PackingItemParts::new); } private final LinkedHashMap<PackingItemPartId, PackingItemPart> partsMap; private PackingItemParts() { partsMap = new LinkedHashMap<>(); } private PackingItemParts(@NonNull final PackingItemParts from) { partsMap = new LinkedHashMap<>(from.partsMap); } private PackingItemParts(@NonNull final List<PackingItemPart> partsList) { this.partsMap = partsList.stream() .map(part -> GuavaCollectors.entry(part.getId(), part)) .collect(GuavaCollectors.toMap(LinkedHashMap::new)); } public PackingItemParts copy() { return new PackingItemParts(this); } public boolean isEmpty() { return partsMap.isEmpty(); } public Object size() { return partsMap.size(); } public <T> Stream<T> map(@NonNull final Function<PackingItemPart, T> mapper) { return partsMap .values() .stream() .map(mapper); } public <T> Optional<T> mapReduce(@NonNull final Function<PackingItemPart, T> mapper) { final ImmutableSet<T> result = map(mapper) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (result.isEmpty()) { return Optional.empty(); } else if (result.size() == 1) { final T singleResult = result.iterator().next(); return Optional.of(singleResult); } else { throw new AdempiereException("Got more than one result: " + result); } } public void setFrom(final PackingItemParts from) { partsMap.clear(); partsMap.putAll(from.partsMap); } public Optional<Quantity> getQtySum() { return map(PackingItemPart::getQty) .reduce(Quantity::add); } public List<PackingItemPart> toList()
{ return ImmutableList.copyOf(partsMap.values()); } public I_C_UOM getCommonUOM() { //validate that all qtys have the same UOM mapReduce(part -> part.getQty().getUomId()) .orElseThrow(()-> new AdempiereException("Missing I_C_UOM!") .appendParametersToMessage() .setParameter("Parts", this)); return toList().get(0).getQty().getUOM(); } @Override public Iterator<PackingItemPart> iterator() { return toList().iterator(); } public void clear() { partsMap.clear(); } public void addQtys(final PackingItemParts partsToAdd) { partsToAdd.toList() .forEach(this::addQty); } private void addQty(final PackingItemPart part) { partsMap.compute(part.getId(), (id, existingPart) -> existingPart != null ? existingPart.addQty(part.getQty()) : part); } public void removePart(final PackingItemPart part) { partsMap.remove(part.getId(), part); } public void updatePart(@NonNull final PackingItemPart part) { partsMap.put(part.getId(), part); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemParts.java
2
请在Spring Boot框架中完成以下Java代码
public void changePassword(String currentClearTextPassword, String newPassword) { SecurityUtils.getCurrentUserLogin() .flatMap(userRepository::findOneByLogin) .ifPresent(user -> { String currentEncryptedPassword = user.getPassword(); if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { throw new InvalidPasswordException(); } String encryptedPassword = passwordEncoder.encode(newPassword); user.setPassword(encryptedPassword); log.debug("Changed password for User: {}", user); }); } @Transactional(readOnly = true) public Page<UserDTO> getAllManagedUsers(Pageable pageable) { return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthorities(Long id) { return userRepository.findOneWithAuthoritiesById(id); }
@Transactional(readOnly = true) public Optional<User> getUserWithAuthorities() { return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { userRepository .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) .forEach(user -> { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); }); } /** * @return a list of all the authorities */ public List<String> getAuthorities() { return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList()); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
private static void generate(File oldDir, File newDir, File out) throws IOException { String oldVersionNumber = oldDir.getName(); ConfigurationMetadataRepository oldMetadata = buildRepository(oldDir); String newVersionNumber = newDir.getName(); ConfigurationMetadataRepository newMetadata = buildRepository(newDir); Changelog changelog = Changelog.of(oldVersionNumber, oldMetadata, newVersionNumber, newMetadata); try (ChangelogWriter writer = new ChangelogWriter(out)) { writer.write(changelog); } System.out.println("%nConfiguration metadata changelog written to '%s'".formatted(out)); } static ConfigurationMetadataRepository buildRepository(File directory) { ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); File[] files = directory.listFiles(); if (files == null) { throw new IllegalStateException("'files' must not be null"); }
for (File file : files) { try (JarFile jarFile = new JarFile(file)) { JarEntry metadataEntry = jarFile.getJarEntry("META-INF/spring-configuration-metadata.json"); if (metadataEntry != null) { builder.withJsonResource(jarFile.getInputStream(metadataEntry)); } } catch (IOException ex) { throw new RuntimeException(ex); } } return builder.build(); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata-changelog-generator\src\main\java\org\springframework\boot\configurationmetadata\changelog\ChangelogGenerator.java
2
请在Spring Boot框架中完成以下Java代码
public String[] getRoles(String token) { String username = JwtUtil.getUsername(token); Set roles = sysBaseApi.getUserRoleSet(username); if(CollectionUtils.isEmpty(roles)){ return null; } return (String[]) roles.toArray(new String[roles.size()]); } @Override public Boolean verifyToken(String token) { return TokenUtils.verifyToken(token, sysBaseApi, redisUtil); } @Override public Map<String, Object> getUserInfo(String token) { Map<String, Object> map = new HashMap(5); String username = JwtUtil.getUsername(token); //此处通过token只能拿到一个信息 用户账号 后面的就是根据账号获取其他信息 查询数据或是走redis 用户根据自身业务可自定义 SysUserCacheInfo userInfo = null; try { userInfo = sysBaseApi.getCacheUser(username); } catch (Exception e) { log.error("获取用户信息异常:"+ e.getMessage()); return map; } //设置账号名 map.put(SYS_USER_CODE, userInfo.getSysUserCode()); //设置部门编码 map.put(SYS_ORG_CODE, userInfo.getSysOrgCode());
// 将所有信息存放至map 解析sql/api会根据map的键值解析 return map; } /** * 将jeecgboot平台的权限传递给积木报表 * @param token * @return */ @Override public String[] getPermissions(String token) { // 获取用户信息 String username = JwtUtil.getUsername(token); SysUserCacheInfo userInfo = null; try { userInfo = sysBaseApi.getCacheUser(username); } catch (Exception e) { log.error("获取用户信息异常:"+ e.getMessage()); } if(userInfo == null){ return null; } // 查询权限 Set<String> userPermissions = sysBaseApi.getUserPermissionSet(userInfo.getSysUserId()); if(CollectionUtils.isEmpty(userPermissions)){ return null; } return userPermissions.toArray(new String[0]); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\config\jimureport\JimuReportTokenService.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Integer getLoginType() { return loginType; } public void setLoginType(Integer loginType) { this.loginType = loginType;
} public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberId=").append(memberId); sb.append(", createTime=").append(createTime); sb.append(", ip=").append(ip); sb.append(", city=").append(city); sb.append(", loginType=").append(loginType); sb.append(", province=").append(province); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLoginLog.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { // Data Binding try { fireVetoableChange(m_columnName, m_oldText, getText()); } catch (PropertyVetoException pve) { } } // actionPerformed /** * Set Field/WindowNo for ValuePreference * @param mField field */ @Override public void setField (GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * Feature Request [1707462] * Set VFormat * @param strMask mask * @author fer_luck */ public void setVFormat (String strMask) { m_VFormat = strMask; //Get the actual caret from the field, if there's no //caret then just catch the exception and continue //creating the new caret. try{ CaretListener [] cl = this.getCaretListeners(); this.removeCaretListener(cl[0]); } catch(ClassCastException ex ){ log.debug("VString.setVFormat - No caret Listeners"); } //hengsin: [ adempiere-Bugs-1891037 ], preserve current data before change of format String s = getText(); setDocument(new MDocString(m_VFormat, m_fieldLength, this)); setText(s); } // setVFormat /** * Set Text (optionally obscured) * @param text text */ @Override public void setText (String text) { if (m_obscure != null && !m_infocus) { super.setFont(m_obscureFont); super.setText (m_obscure.getObscuredValue(text)); super.setForeground(Color.gray); } else { if (m_stdFont != null) { super.setFont(m_stdFont); super.setForeground(AdempierePLAF.getTextColor_Normal()); } super.setText (text); } } // setText /** * Get Text (clear) * @return text */ @Override
public String getText () { String text = super.getText(); if (m_obscure != null && text != null && text.length() > 0) { if (text.equals(m_obscure.getObscuredValue())) text = m_obscure.getClearValue(); } return text; } // getText /** * Feature Request [1707462] * Get VFormat * @return strMask mask * @author fer_luck */ public String getVFormat () { return this.m_VFormat; } // getVFormat /** * Focus Gained. * Enabled with Obscure * @param e event */ @Override public void focusGained (FocusEvent e) { m_infocus = true; setText(getText()); // clear } // focusGained /** * Focus Lost * Enabled with Obscure * @param e event */ @Override public void focusLost (FocusEvent e) { m_infocus = false; setText(getText()); // obscure } // focus Lost @Override public void setFont(Font f) { super.setFont(f); m_stdFont = f; m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize()); } // metas @Override public boolean isAutoCommit() { return true; } } // VString
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VString.java
1
请完成以下Java代码
public void updateCurrencyRate() { setCurrencyRate(computeCurrencyRate()); } public void setTaxIdAndUpdateVatCode(@Nullable final TaxId taxId) { if (TaxId.equals(this.taxId, taxId)) { return; } this.taxId = taxId; this.vatCode = computeVATCode().map(VATCode::getCode).orElse(null); } private Optional<VATCode> computeVATCode() { if (taxId == null) { return Optional.empty(); } final boolean isSOTrx = m_docLine != null ? m_docLine.isSOTrx() : m_doc.isSOTrx(); return services.findVATCode(VATCodeMatchingRequest.builder() .setC_AcctSchema_ID(getAcctSchemaId().getRepoId()) .setC_Tax_ID(taxId.getRepoId()) .setIsSOTrx(isSOTrx) .setDate(this.dateAcct) .build()); } public void updateFAOpenItemTrxInfo() { if (openItemTrxInfo != null) { return;
} this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null); } void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo) { this.openItemTrxInfo = openItemTrxInfo; } public void updateFrom(@NonNull FactAcctChanges changes) { setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr()); setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr()); updateCurrencyRate(); if (changes.getAccountId() != null) { this.accountId = changes.getAccountId(); } setTaxIdAndUpdateVatCode(changes.getTaxId()); setDescription(changes.getDescription()); this.M_Product_ID = changes.getProductId(); this.userElementString1 = changes.getUserElementString1(); this.C_OrderSO_ID = changes.getSalesOrderId(); this.C_Activity_ID = changes.getActivityId(); this.appliedUserChanges = changes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(pcn, quantity, unit, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractQuantity {\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}");
return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractQuantity.java
2
请完成以下Java代码
private void addIfHasValue(Properties properties, String name, @Nullable String value) { if (StringUtils.hasText(value)) { properties.put(name, value); } } /** * Build-system agnostic details of a project. */ public static final class ProjectDetails { private final @Nullable String group; private final @Nullable String artifact; private final @Nullable String name; private final @Nullable String version; private final @Nullable Instant time; private final @Nullable Map<String, String> additionalProperties; public ProjectDetails(@Nullable String group, @Nullable String artifact, @Nullable String version, @Nullable String name, @Nullable Instant time, @Nullable Map<String, String> additionalProperties) { this.group = group; this.artifact = artifact; this.name = name; this.version = version; this.time = time; validateAdditionalProperties(additionalProperties); this.additionalProperties = additionalProperties; } private static void validateAdditionalProperties(@Nullable Map<String, String> additionalProperties) { if (additionalProperties != null) { additionalProperties.forEach((name, value) -> { if (value == null) { throw new NullAdditionalPropertyValueException(name); } }); } } public @Nullable String getGroup() { return this.group; } public @Nullable String getArtifact() { return this.artifact;
} public @Nullable String getName() { return this.name; } public @Nullable String getVersion() { return this.version; } public @Nullable Instant getTime() { return this.time; } public @Nullable Map<String, String> getAdditionalProperties() { return this.additionalProperties; } } /** * Exception thrown when an additional property with a null value is encountered. */ public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\BuildPropertiesWriter.java
1
请完成以下Java代码
public long lRemove(String key, long count, Object value) { try { return redisTemplate.opsForList().remove(key, count, value); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * @param prefix 前缀 * @param ids id */ public void delByKeys(String prefix, Set<Long> ids) { Set<Object> keys = new HashSet<>(); for (Long id : ids) { keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString())); } long count = redisTemplate.delete(keys); }
// ============================incr============================= /** * 递增 * @param key * @return */ public Long increment(String key) { return redisTemplate.opsForValue().increment(key); } /** * 递减 * @param key * @return */ public Long decrement(String key) { return redisTemplate.opsForValue().decrement(key); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\RedisUtils.java
1
请在Spring Boot框架中完成以下Java代码
public int delete(List<Long> ids) { SmsHomeBrandExample example = new SmsHomeBrandExample(); example.createCriteria().andIdIn(ids); return homeBrandMapper.deleteByExample(example); } @Override public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) { SmsHomeBrandExample example = new SmsHomeBrandExample(); example.createCriteria().andIdIn(ids); SmsHomeBrand record = new SmsHomeBrand(); record.setRecommendStatus(recommendStatus); return homeBrandMapper.updateByExampleSelective(record,example); }
@Override public List<SmsHomeBrand> list(String brandName, Integer recommendStatus, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); SmsHomeBrandExample example = new SmsHomeBrandExample(); SmsHomeBrandExample.Criteria criteria = example.createCriteria(); if(!StrUtil.isEmpty(brandName)){ criteria.andBrandNameLike("%"+brandName+"%"); } if(recommendStatus!=null){ criteria.andRecommendStatusEqualTo(recommendStatus); } example.setOrderByClause("sort desc"); return homeBrandMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeBrandServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @ApiModelProperty(example = "oneMilestoneCase%3A1%3A4") public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-milestone-instances/5") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getHistoricCaseInstanceUrl() { return historicCaseInstanceUrl; } public void setHistoricCaseInstanceUrl(String historicCaseInstanceUrl) { this.historicCaseInstanceUrl = historicCaseInstanceUrl; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/oneMilestoneCase%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceResponse.java
2
请完成以下Java代码
public boolean isFulfilled(ScopeImpl element) { Boolean consumesCompensationProperty = (Boolean) element.getProperty(BpmnParse.PROPERTYNAME_CONSUMES_COMPENSATION); return consumesCompensationProperty == null || consumesCompensationProperty == Boolean.TRUE; } }); return new ArrayList<EventSubscriptionEntity>(subscriptions); } /** * Collect all compensate event subscriptions for activity on the scope of * given execution. */ public static List<EventSubscriptionEntity> collectCompensateEventSubscriptionsForActivity(ActivityExecution execution, String activityRef) { final List<EventSubscriptionEntity> eventSubscriptions = collectCompensateEventSubscriptionsForScope(execution); final String subscriptionActivityId = getSubscriptionActivityId(execution, activityRef); List<EventSubscriptionEntity> eventSubscriptionsForActivity = new ArrayList<EventSubscriptionEntity>(); for (EventSubscriptionEntity subscription : eventSubscriptions) { if (subscriptionActivityId.equals(subscription.getActivityId())) { eventSubscriptionsForActivity.add(subscription); } } return eventSubscriptionsForActivity; } public static ExecutionEntity getCompensatingExecution(EventSubscriptionEntity eventSubscription) { String configuration = eventSubscription.getConfiguration(); if (configuration != null) { return Context.getCommandContext().getExecutionManager().findExecutionById(configuration); } else { return null; } }
private static String getSubscriptionActivityId(ActivityExecution execution, String activityRef) { ActivityImpl activityToCompensate = ((ExecutionEntity) execution).getProcessDefinition().findActivity(activityRef); if (activityToCompensate.isMultiInstance()) { ActivityImpl flowScope = (ActivityImpl) activityToCompensate.getFlowScope(); return flowScope.getActivityId(); } else { ActivityImpl compensationHandler = activityToCompensate.findCompensationHandler(); if (compensationHandler != null) { return compensationHandler.getActivityId(); } else { // if activityRef = subprocess and subprocess has no compensation handler return activityRef; } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\CompensationUtil.java
1
请完成以下Java代码
public void delete(HistoricDetailEntity entity, boolean fireDeleteEvent) { super.delete(entity, fireDeleteEvent); if (entity instanceof HistoricDetailVariableInstanceUpdateEntity) { HistoricDetailVariableInstanceUpdateEntity historicDetailVariableInstanceUpdateEntity = ((HistoricDetailVariableInstanceUpdateEntity) entity); if (historicDetailVariableInstanceUpdateEntity.getByteArrayRef() != null) { historicDetailVariableInstanceUpdateEntity.getByteArrayRef().delete(); } } } @Override public void deleteHistoricDetailsByProcessInstanceId(String historicProcessInstanceId) { if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.AUDIT)) { List<HistoricDetailEntity> historicDetails = historicDetailDataManager.findHistoricDetailsByProcessInstanceId(historicProcessInstanceId); for (HistoricDetailEntity historicDetail : historicDetails) { delete(historicDetail); } } } @Override public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) { return historicDetailDataManager.findHistoricDetailCountByQueryCriteria(historicVariableUpdateQuery); } @Override public List<HistoricDetail> findHistoricDetailsByQueryCriteria( HistoricDetailQueryImpl historicVariableUpdateQuery, Page page ) { return historicDetailDataManager.findHistoricDetailsByQueryCriteria(historicVariableUpdateQuery, page); } @Override
public void deleteHistoricDetailsByTaskId(String taskId) { if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.FULL)) { List<HistoricDetailEntity> details = historicDetailDataManager.findHistoricDetailsByTaskId(taskId); for (HistoricDetail detail : details) { delete((HistoricDetailEntity) detail); } } } @Override public List<HistoricDetail> findHistoricDetailsByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return historicDetailDataManager.findHistoricDetailsByNativeQuery(parameterMap, firstResult, maxResults); } @Override public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) { return historicDetailDataManager.findHistoricDetailCountByNativeQuery(parameterMap); } public HistoricDetailDataManager getHistoricDetailDataManager() { return historicDetailDataManager; } public void setHistoricDetailDataManager(HistoricDetailDataManager historicDetailDataManager) { this.historicDetailDataManager = historicDetailDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityManagerImpl.java
1
请完成以下Java代码
public class TbJson { public static String stringify(Object value) { return value != null ? JacksonUtil.toString(value) : "null"; } public static Object parse(ExecutionContext ctx, String value) throws IOException { if (value != null) { JsonNode node = JacksonUtil.toJsonNode(value); if (node.isObject()) { return ArgsRepackUtil.repack(ctx, JacksonUtil.convertValue(node, Map.class)); } else if (node.isArray()) { return ArgsRepackUtil.repack(ctx, JacksonUtil.convertValue(node, List.class)); } else if (node.isDouble()) { return node.doubleValue(); } else if (node.isLong()) { return node.longValue(); } else if (node.isInt()) { return node.intValue(); } else if (node.isBoolean()) {
return node.booleanValue(); } else if (node.isTextual()) { return node.asText(); } else if (node.isBinary()) { return node.binaryValue(); } else if (node.isNull()) { return null; } else { return node.asText(); } } else { return null; } } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\tbel\TbJson.java
1
请完成以下Java代码
public class C_BPartner_Location_Tab_Callout extends TabCalloutAdapter { @Override public void onNew(final ICalloutRecord calloutRecord) { final IBPartnerDAO bPartnerPA = Services.get(IBPartnerDAO.class); final I_C_BPartner_Location address = calloutRecord.getModel(I_C_BPartner_Location.class); if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsShipToDefault)) { address.setIsShipTo(true); address.setIsShipToDefault(true); } else { address.setIsShipTo(false); address.setIsShipToDefault(false); } if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsBillToDefault)) { address.setIsBillTo(true); address.setIsBillToDefault(true); } else { address.setIsBillTo(false); address.setIsBillToDefault(false); } if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsHandOverLocation)) {
address.setIsHandOverLocation(true); } else { address.setIsHandOverLocation(false); } // TODO: needs to be moved into de.metas.contracts project // if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsSubscriptionToDefault)) // { // address.setIsSubscriptionTo(true); // address.setIsSubscriptionToDefault(true); // } // else // { // address.setIsSubscriptionTo(false); // address.setIsSubscriptionToDefault(false); // } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\callout\C_BPartner_Location_Tab_Callout.java
1
请在Spring Boot框架中完成以下Java代码
class FavoriteSong { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private Song song; @ManyToOne private User user; @Column(name = "arrangement_index", nullable = false) private int arrangementIndex; FavoriteSong(Song song, User user) { this.song = song; this.user = user; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass())
return false; FavoriteSong likedSong = (FavoriteSong) o; return Objects.equals(id, likedSong.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } protected FavoriteSong() { } }
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\multiplebagfetchexception\FavoriteSong.java
2