instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public org.compiere.model.I_C_Region getTo_Region() { return get_ValueAsPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class); } @Override public void setTo_Region(final org.compiere.model.I_C_Region To_Region) { set_ValueFromPO(COLUMNNAME_To_Region_ID, org.compiere.model.I_C_Region.class, To_Region); } @Override public void setTo_Region_ID (final int To_Region_ID) { if (To_Region_ID < 1) set_Value (COLUMNNAME_To_Region_ID, null); else set_Value (COLUMNNAME_To_Region_ID, To_Region_ID); } @Override public int getTo_Region_ID() { return get_ValueAsInt(COLUMNNAME_To_Region_ID); } /** * TypeOfDestCountry AD_Reference_ID=541323 * Reference name: TypeDestCountry */ public static final int TYPEOFDESTCOUNTRY_AD_Reference_ID=541323; /** Domestic = DOMESTIC */ public static final String TYPEOFDESTCOUNTRY_Domestic = "DOMESTIC"; /** EU-foreign = WITHIN_COUNTRY_AREA */ public static final String TYPEOFDESTCOUNTRY_EU_Foreign = "WITHIN_COUNTRY_AREA"; /** Non-EU country = OUTSIDE_COUNTRY_AREA */ public static final String TYPEOFDESTCOUNTRY_Non_EUCountry = "OUTSIDE_COUNTRY_AREA"; @Override public void setTypeOfDestCountry (final @Nullable java.lang.String TypeOfDestCountry) { set_Value (COLUMNNAME_TypeOfDestCountry, TypeOfDestCountry); } @Override public java.lang.String getTypeOfDestCountry() {
return get_ValueAsString(COLUMNNAME_TypeOfDestCountry); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax.java
1
请在Spring Boot框架中完成以下Java代码
public DeploymentBuilder key(String key) { deployment.setKey(key); return this; } @Override public DeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public DeploymentBuilder disableBpmnValidation() { this.isProcessValidationEnabled = false; return this; } @Override public DeploymentBuilder disableSchemaValidation() { this.isBpmn20XsdValidationEnabled = false; return this; } @Override public DeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } @Override public DeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this; } @Override public DeploymentBuilder activateProcessDefinitionsOn(Date date) { this.processDefinitionsActivationDate = date; return this; } @Override public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) { deploymentProperties.put(propertyKey, propertyValue); return this; }
@Override public Deployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public DeploymentEntity getDeployment() { return deployment; } public boolean isProcessValidationEnabled() { return isProcessValidationEnabled; } public boolean isBpmn20XsdValidationEnabled() { return isBpmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; } public Map<String, Object> getDeploymentProperties() { return deploymentProperties; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\repository\DeploymentBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setPurpose(String value) { this.purpose = value; } /** * Gets the value of the bankCode property. * * @return * possible object is * {@link String } * */ public String getBankCode() { return bankCode; } /** * Sets the value of the bankCode property. * * @param value * allowed object is * {@link String } * */ public void setBankCode(String value) { this.bankCode = value; } /** * Gets the value of the bankName property. * * @return * possible object is * {@link String } * */ public String getBankName() { return bankName; } /** * Sets the value of the bankName property. * * @param value * allowed object is * {@link String } * */ public void setBankName(String value) { this.bankName = value; } /** * Gets the value of the bankAccountNumber property. * * @return * possible object is * {@link String } * */ public String getBankAccountNumber() { return bankAccountNumber; } /** * Sets the value of the bankAccountNumber property. * * @param value * allowed object is * {@link String } * */ public void setBankAccountNumber(String value) { this.bankAccountNumber = value; } /** * Gets the value of the bankAccountHolder property. * * @return * possible object is * {@link String } * */ public String getBankAccountHolder() { return bankAccountHolder; } /** * Sets the value of the bankAccountHolder property. * * @param value * allowed object is * {@link String } * */ public void setBankAccountHolder(String value) { this.bankAccountHolder = value; } /** * Gets the value of the iban property. * * @return
* possible object is * {@link String } * */ public String getIban() { return iban; } /** * Sets the value of the iban property. * * @param value * allowed object is * {@link String } * */ public void setIban(String value) { this.iban = value; } /** * Gets the value of the bic property. * * @return * possible object is * {@link String } * */ public String getBic() { return bic; } /** * Sets the value of the bic property. * * @param value * allowed object is * {@link String } * */ public void setBic(String value) { this.bic = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Cod.java
2
请完成以下Java代码
public int getAD_Column_ID() { return m_AD_Column_ID; } // getAD_Column_ID /** * Get Column Name * @return column name */ public String getColumnName() { return m_columnName; } // getColumnName /** * Get Display Type * @return display type */ 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
请完成以下Java代码
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID) { if (PP_Product_BOM_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID)); } /** Get BOM & Formula. @return BOM & Formula */ public int getPP_Product_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed
The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeRequest.java
1
请完成以下Java代码
public void onChargeAmtChanged(final @NonNull I_C_BankStatementLine bsl) { getAmountsCallout(bsl).onChargeAmtChanged(bsl); } @CalloutMethod(columnNames = I_C_BankStatementLine.COLUMNNAME_InterestAmt) public void onInterestAmtChanged(final @NonNull I_C_BankStatementLine bsl) { getAmountsCallout(bsl).onInterestAmtChanged(bsl); } @CalloutMethod(columnNames = I_C_BankStatementLine.COLUMNNAME_C_Invoice_ID) public void onC_Invoice_ID_Changed(@NonNull final I_C_BankStatementLine bsl) { final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(bsl.getC_Invoice_ID()); if (invoiceId == null) { return; } bankStatementBL.updateLineFromInvoice(bsl, invoiceId); } private static void updateTrxAmt(final I_C_BankStatementLine bsl) { bsl.setTrxAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToTrxAmt() .getTrxAmt()); } private interface AmountsCallout { void onStmtAmtChanged(final I_C_BankStatementLine bsl); void onTrxAmtChanged(final I_C_BankStatementLine bsl); void onBankFeeAmtChanged(final I_C_BankStatementLine bsl); void onChargeAmtChanged(final I_C_BankStatementLine bsl); void onInterestAmtChanged(final I_C_BankStatementLine bsl); } public static class BankStatementLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToBankFeeAmt() .getBankFeeAmt()); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) {
updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } } public static class CashJournalLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { // i.e. set the TrxAmt back. // user shall not be allowed to change it // instead, StmtAmt can be changed updateTrxAmt(bsl); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setChargeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) { bsl.setInterestAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\callout\C_BankStatementLine.java
1
请完成以下Java代码
public AssociationDirection getAssociationDirection() { return associationDirectionAttribute.getValue(this); } public void setAssociationDirection(AssociationDirection associationDirection) { associationDirectionAttribute.setValue(this, associationDirection); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, CMMN_ELEMENT_ASSOCIATION) .namespaceUri(CMMN11_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); }
}); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(CmmnElement.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF) .idAttributeReference(CmmnElement.class) .build(); associationDirectionAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\AssociationImpl.java
1
请完成以下Spring Boot application配置
spring.jpa.properties.hibernate.jdbc.batch_size=4 spring.jpa.properties.hibernate.order_inserts=true spring.jpa.properties.hibernate.order_updates=tr
ue spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public Duration getPushRate() { return this.pushRate; } public void setPushRate(Duration pushRate) { this.pushRate = pushRate; } public @Nullable String getJob() { return this.job; } public void setJob(@Nullable String job) { this.job = job; } public Map<String, String> getGroupingKey() { return this.groupingKey; } public void setGroupingKey(Map<String, String> groupingKey) { this.groupingKey = groupingKey; } public ShutdownOperation getShutdownOperation() { return this.shutdownOperation; } public void setShutdownOperation(ShutdownOperation shutdownOperation) { this.shutdownOperation = shutdownOperation; } public Scheme getScheme() { return this.scheme; } public void setScheme(Scheme scheme) { this.scheme = scheme; } public @Nullable String getToken() { return this.token; } public void setToken(@Nullable String token) { this.token = token; }
public Format getFormat() { return this.format; } public void setFormat(Format format) { this.format = format; } public enum Format { /** * Push metrics in text format. */ TEXT, /** * Push metrics in protobuf format. */ PROTOBUF } public enum Scheme { /** * Use HTTP to push metrics. */ HTTP, /** * Use HTTPS to push metrics. */ HTTPS } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusProperties.java
2
请完成以下Java代码
public int getPP_Product_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeRequest.java
1
请完成以下Java代码
public ImmutableList<MinimalColumnInfo> getByIds(final Collection<AdColumnId> adColumnIds) { if (adColumnIds.isEmpty()) { return ImmutableList.of(); } return adColumnIds.stream() .distinct() .map(byId::get) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Override public ImmutableList<MinimalColumnInfo> getByColumnName(@NonNull final String columnName) { return byId.values() .stream() .filter(columnInfo -> columnInfo.isColumnNameMatching(columnName)) .collect(ImmutableList.toImmutableList()); } @Nullable @Override public MinimalColumnInfo getByColumnNameOrNull(final AdTableId adTableId, final String columnName) { final AdTableIdAndColumnName key = new AdTableIdAndColumnName(adTableId, columnName);
return byColumnName.get(key); } // // // @Value static class AdTableIdAndColumnName { @NonNull AdTableId adTableId; @NonNull String columnNameUC; AdTableIdAndColumnName(@NonNull final AdTableId adTableId, @NonNull final String columnName) { this.adTableId = adTableId; this.columnNameUC = columnName.toUpperCase(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\ImmutableMinimalColumnInfoMap.java
1
请完成以下Java代码
public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) { advisedRequest = this.before(advisedRequest); AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest); this.observeAfter(advisedResponse); return advisedResponse; } private void observeAfter(AdvisedResponse advisedResponse) { logger.info(advisedResponse.response() .getResult() .getOutput() .getText()); }
private AdvisedRequest before(AdvisedRequest advisedRequest) { logger.info(advisedRequest.userText()); return advisedRequest; } @Override public String getName() { return "CustomLoggingAdvisor"; } @Override public int getOrder() { return Integer.MAX_VALUE; } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\advisors\CustomLoggingAdvisor.java
1
请完成以下Java代码
public static ADColumnNameFQ missing(final String missing) { return builder().missing(missing).build(); } @Override public String toString() {return toShortString();} public String toShortString() { if (missing != null) { return missing; } else { final StringBuilder sb = new StringBuilder(); if (tableName != null)
{ sb.append(tableName.toShortString()); } if (sb.length() > 0) { sb.append("."); } sb.append(columnName); return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\ADColumnNameFQ.java
1
请完成以下Java代码
public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void 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 setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{ set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
static IHUAware fromHU(final I_M_HU hu) { return () -> hu; } /** * @return live collection, where each HU is wrapped as {@link IHUAware} */ static Collection<IHUAware> transformHUCollection(final Collection<I_M_HU> hus) { return Collections2.transform(hus, IHUAware::fromHU); } /** * @return {@link I_M_HU} or <code>null</code> */
@Nullable static I_M_HU getM_HUOrNull(final Object model) { if(model instanceof IHUAware) { return ((IHUAware)model).getM_HU(); } else { return null; } } I_M_HU getM_HU(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUAware.java
1
请完成以下Java代码
public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Read Only. @param IsReadOnly Field is read only */ public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Read Only. @return Field is read only */ public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set User updateable. @param IsUserUpdateable The field can be updated by the user */ public void setIsUserUpdateable (boolean IsUserUpdateable) { set_Value (COLUMNNAME_IsUserUpdateable, Boolean.valueOf(IsUserUpdateable)); } /** Get User updateable. @return The field can be updated by the user */ public boolean isUserUpdateable () { Object oo = get_Value(COLUMNNAME_IsUserUpdateable); 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Win.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<ServerResponse> handle(ServerRequest request) { // 查询列表 List<UserVO> result = new ArrayList<>(); result.add(new UserVO().setId(1).setUsername("yudaoyuanma")); result.add(new UserVO().setId(2).setUsername("woshiyutou")); result.add(new UserVO().setId(3).setUsername("chifanshuijiao")); // 返回列表 return ServerResponse.ok().bodyValue(result); } }); } @Bean public RouterFunction<ServerResponse> userGetRouterFunction() { return RouterFunctions.route(RequestPredicates.GET("/users2/get"), new HandlerFunction<ServerResponse>() { @Override public Mono<ServerResponse> handle(ServerRequest request) { // 获得编号 Integer id = request.queryParam("id")
.map(s -> StringUtils.isEmpty(s) ? null : Integer.valueOf(s)).get(); // 查询用户 UserVO user = new UserVO().setId(id).setUsername(UUID.randomUUID().toString()); // 返回列表 return ServerResponse.ok().bodyValue(user); } }); } @Bean public RouterFunction<ServerResponse> demoRouterFunction() { return route(GET("/users2/demo"), request -> ok().bodyValue("demo")); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserRouter.java
2
请在Spring Boot框架中完成以下Java代码
public class Passenger { @Id @GeneratedValue @Column(nullable = false) private Long id; @Basic(optional = false) @Column(nullable = false) private String firstName; @Basic(optional = false) @Column(nullable = false) private String lastName; private Passenger(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public static Passenger from(String firstName, String lastName) { return new Passenger(firstName, lastName); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }
@Override public String toString() { return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Passenger passenger = (Passenger) o; return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\jpa\domain\Passenger.java
2
请完成以下Java代码
public final String getSql() { buildSql(); return sqlWhereClause; } @Override public final List<Object> getSqlParams(final Properties ctx) { buildSql(); return sqlParams; } private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null; private void buildSql() { if (sqlBuilt) { return; } final Operator operator = getOperator(); final String operand1ColumnName = operand1.getColumnName(); final String operand1ColumnSql = operand1Modifier.getColumnSql(operand1ColumnName); final String operatorSql = operator.getSql(); sqlParams = new ArrayList<>(); final String operand2Sql = operand2 == null ? null : operand2Modifier.getValueSql(operand2, sqlParams); if (operand2 == null && Operator.EQUAL == operator) { sqlWhereClause = operand1ColumnName + " IS NULL"; sqlParams = Collections.emptyList(); }
else if (operand2 == null && Operator.NOT_EQUAL == operator) { sqlWhereClause = operand1ColumnName + " IS NOT NULL"; sqlParams = Collections.emptyList(); } else { sqlWhereClause = operand1ColumnSql + " " + operatorSql + " " + operand2Sql; } // Corner case: we are asked for Operand1 <> SomeValue // => we need to create an SQL which is also taking care about the NULL value // i.e. (Operand1 <> SomeValue OR Operand1 IS NULL) if (operand2 != null && Operator.NOT_EQUAL == operator) { sqlWhereClause = "(" + sqlWhereClause + " OR " + operand1ColumnSql + " IS NULL" + ")"; } sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompareQueryFilter.java
1
请完成以下Java代码
public ResponseEntity<Object> createMenu(@Validated @RequestBody Menu resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } menuService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改菜单") @ApiOperation("修改菜单") @PutMapping @PreAuthorize("@el.check('menu:edit')") public ResponseEntity<Object> updateMenu(@Validated(Menu.Update.class) @RequestBody Menu resources){ menuService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
@Log("删除菜单") @ApiOperation("删除菜单") @DeleteMapping @PreAuthorize("@el.check('menu:del')") public ResponseEntity<Object> deleteMenu(@RequestBody Set<Long> ids){ Set<Menu> menuSet = new HashSet<>(); for (Long id : ids) { List<MenuDto> menuList = menuService.getMenus(id); menuSet.add(menuService.findOne(id)); menuSet = menuService.getChildMenus(menuMapper.toEntity(menuList), menuSet); } menuService.delete(menuSet); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\MenuController.java
1
请完成以下Java代码
public void setAge(byte age) { this.age = age; } public short getUidNumber() { return uidNumber; } public void setUidNumber(short uidNumber) { this.uidNumber = uidNumber; } public int getPinCode() { return pinCode; } public void setPinCode(int pinCode) { this.pinCode = pinCode; } public long getContactNumber() { return contactNumber; } public void setContactNumber(long contactNumber) { this.contactNumber = contactNumber; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height;
} public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\core-java-modules\core-java-reflection\src\main\java\com\baeldung\reflection\access\privatefields\Person.java
1
请完成以下Java代码
final class OAuth2AuthorizationRequestDeserializer extends JsonDeserializer<OAuth2AuthorizationRequest> { @Override public OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context) throws IOException { ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode root = mapper.readTree(parser); return deserialize(parser, mapper, root); } private OAuth2AuthorizationRequest deserialize(JsonParser parser, ObjectMapper mapper, JsonNode root) throws JsonParseException { AuthorizationGrantType authorizationGrantType = convertAuthorizationGrantType( JsonNodeUtils.findObjectNode(root, "authorizationGrantType")); Builder builder = getBuilder(parser, authorizationGrantType); builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri")); builder.clientId(JsonNodeUtils.findStringValue(root, "clientId")); builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri")); builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, mapper)); builder.state(JsonNodeUtils.findStringValue(root, "state")); builder.additionalParameters( JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, mapper)); builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri"));
builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, mapper)); return builder.build(); } private Builder getBuilder(JsonParser parser, AuthorizationGrantType authorizationGrantType) throws JsonParseException { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) { return OAuth2AuthorizationRequest.authorizationCode(); } throw new JsonParseException(parser, "Invalid authorizationGrantType"); } private static AuthorizationGrantType convertAuthorizationGrantType(JsonNode jsonNode) { String value = JsonNodeUtils.findStringValue(jsonNode, "value"); if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) { return AuthorizationGrantType.AUTHORIZATION_CODE; } return null; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\jackson2\OAuth2AuthorizationRequestDeserializer.java
1
请完成以下Java代码
public JsonMetasfreshId asJsonMetasfreshId() { Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this); final int repoId = Integer.parseInt(value); return JsonMetasfreshId.of(repoId); } public <T extends RepoIdAware> T asMetasfreshId(@NonNull final IntFunction<T> mapper) { Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this); final int repoId = Integer.parseInt(value); return mapper.apply(repoId); } public GLN asGLN() { Check.assume(Type.GLN.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN, this); return GLN.ofString(value); } public GlnWithLabel asGlnWithLabel() { Check.assume(Type.GLN_WITH_LABEL.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN_WITH_LABEL, this); return GlnWithLabel.ofString(value); } public String asDoc() { Check.assume(Type.DOC.equals(type), "The type of this instance needs to be {}; this={}", Type.DOC, this); return value; } public String asValue() { Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this); return value; } public String asInternalName() {
Check.assume(Type.INTERNALNAME.equals(type), "The type of this instance needs to be {}; this={}", Type.INTERNALNAME, this); return value; } public boolean isMetasfreshId() { return Type.METASFRESH_ID.equals(type); } public boolean isExternalId() { return Type.EXTERNAL_ID.equals(type); } public boolean isValue() { return Type.VALUE.equals(type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\IdentifierString.java
1
请完成以下Java代码
public class CorrelationKeyImpl extends BaseElementImpl implements CorrelationKey { protected static Attribute<String> nameAttribute; protected static ElementReferenceCollection<CorrelationProperty, CorrelationPropertyRef> correlationPropertyRefCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CorrelationKey.class, BPMN_ELEMENT_CORRELATION_KEY) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<CorrelationKey>() { public CorrelationKey newInstance(ModelTypeInstanceContext instanceContext) { return new CorrelationKeyImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); correlationPropertyRefCollection = sequenceBuilder.elementCollection(CorrelationPropertyRef.class) .qNameElementReferenceCollection(CorrelationProperty.class) .build();
typeBuilder.build(); } public CorrelationKeyImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<CorrelationProperty> getCorrelationProperties() { return correlationPropertyRefCollection.getReferenceTargetElements(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CorrelationKeyImpl.java
1
请完成以下Java代码
public void onInit(final ICalloutRecord calloutRecord) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if(gridTab == null) { return; } final ISideActionsGroupsListModel sideActionsGroupsModel = gridTab.getSideActionsGroupsModel(); // // Add action: Approve For Invoicing (08602) { action_ApproveForInvoicing = new IC_ApproveForInvoicing_Action(gridTab); sideActionsGroupsModel .getGroupById(GridTab.SIDEACTIONS_Actions_GroupId) .addAction(action_ApproveForInvoicing); } // // Setup facet filtering engine (08602) { gridTabFacetExecutor = new FacetExecutor<>(I_C_Invoice_Candidate.class); // Current facets will be displayed in GridTab's right-side panel final IFacetsPool<I_C_Invoice_Candidate> facetsPool = new SideActionFacetsPool<>(sideActionsGroupsModel); gridTabFacetExecutor.setFacetsPool(facetsPool); // The datasource which will be filtered by our facets is actually THIS grid tab final IFacetFilterable<I_C_Invoice_Candidate> facetFilterable = new GridTabFacetFilterable<>(I_C_Invoice_Candidate.class, gridTab); gridTabFacetExecutor.setFacetFilterable(facetFilterable); // We will use service registered collectors to collect the facets from invoice candidates final IFacetCollector<I_C_Invoice_Candidate> facetCollectors = Services.get(IInvoiceCandidateFacetCollectorFactory.class).createFacetCollectors(); gridTabFacetExecutor.addFacetCollector(facetCollectors); } } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { updateFacets(calloutRecord); } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { // NOTE: we are not updating the facets on refresh all because following case would fail: // Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid, // but user is not expecting to have all it's facets reset. // updateFacets(gridTab);
} /** * Retrieve invoice candidates facets from current grid tab rows and add them to window side panel * * @param calloutRecord * @param http://dewiki908/mediawiki/index.php/08602_Rechnungsdispo_UI_%28106621797084%29 */ private void updateFacets(final ICalloutRecord calloutRecord) { // // If user asked to approve for invoicing some ICs, the grid will be asked to refresh all, // but in this case we don't want to reset current facets and recollect them if (action_ApproveForInvoicing.isRunning()) { return; } // // Collect the facets from current grid tab rows and fully update the facets pool. gridTabFacetExecutor.collectFacetsAndResetPool(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\C_Invoice_Candidate_TabCallout.java
1
请完成以下Java代码
public class MultiplePeakFinder { public static List<Integer> findPeaks(int[] arr) { List<Integer> peaks = new ArrayList<>(); if (arr == null || arr.length == 0) { return peaks; } findPeakElements(arr, 0, arr.length - 1, peaks, arr.length); return peaks; } private static void findPeakElements(int[] arr, int low, int high, List<Integer> peaks, int length) { if (low > high) { return;
} int mid = low + (high - low) / 2; boolean isPeak = (mid == 0 || arr[mid] > arr[mid - 1]) && (mid == length - 1 || arr[mid] > arr[mid + 1]); boolean isFirstInSequence = mid > 0 && arr[mid] == arr[mid - 1] && arr[mid] > arr[mid + 1]; if (isPeak || isFirstInSequence) { if (!peaks.contains(arr[mid])) { peaks.add(arr[mid]); } } findPeakElements(arr, low, mid - 1, peaks, length); findPeakElements(arr, mid + 1, high, peaks, length); } }
repos\tutorials-master\core-java-modules\core-java-collections-array-list-2\src\main\java\com\baeldung\peakelements\MultiplePeakFinder.java
1
请在Spring Boot框架中完成以下Java代码
public List<QueryVariable> getProcessInstanceVariables() { return processInstanceVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public void setProcessInstanceVariables(List<QueryVariable> processInstanceVariables) { this.processInstanceVariables = processInstanceVariables; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessBusinessKey() { return processBusinessKey; } public void setProcessBusinessKey(String processBusinessKey) { this.processBusinessKey = processBusinessKey; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getSignalEventSubscriptionName() { return signalEventSubscriptionName; } public void setSignalEventSubscriptionName(String signalEventSubscriptionName) { this.signalEventSubscriptionName = signalEventSubscriptionName; } public String getMessageEventSubscriptionName() { return messageEventSubscriptionName; } public void setMessageEventSubscriptionName(String messageEventSubscriptionName) { this.messageEventSubscriptionName = messageEventSubscriptionName; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; }
public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(Set<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java
2
请完成以下Java代码
public void parseDependentInstances(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { parseContext.handleDependentVariables(migratingInstance, collectActivityInstanceVariables(migratingInstance)); parseContext.handleDependentActivityInstanceJobs(migratingInstance, collectActivityInstanceJobs(migratingInstance)); parseContext.handleDependentEventSubscriptions(migratingInstance, collectActivityInstanceEventSubscriptions(migratingInstance)); } protected List<VariableInstanceEntity> collectActivityInstanceVariables(MigratingActivityInstance instance) { List<VariableInstanceEntity> variables = new ArrayList<VariableInstanceEntity>(); ExecutionEntity representativeExecution = instance.resolveRepresentativeExecution(); ExecutionEntity parentExecution = representativeExecution.getParent(); // decide for representative execution and parent execution whether to none/all/concurrentLocal variables // belong to this activity instance boolean addAllRepresentativeExecutionVariables = instance.getSourceScope().isScope() || representativeExecution.isConcurrent(); if (addAllRepresentativeExecutionVariables) { variables.addAll(representativeExecution.getVariablesInternal()); } else { variables.addAll(getConcurrentLocalVariables(representativeExecution)); } boolean addAnyParentExecutionVariables = parentExecution != null && instance.getSourceScope().isScope(); if (addAnyParentExecutionVariables) { boolean addAllParentExecutionVariables = parentExecution.isConcurrent(); if (addAllParentExecutionVariables) { variables.addAll(parentExecution.getVariablesInternal()); } else { variables.addAll(getConcurrentLocalVariables(parentExecution)); } } return variables; } protected List<EventSubscriptionEntity> collectActivityInstanceEventSubscriptions(MigratingActivityInstance migratingInstance) { if (migratingInstance.getSourceScope().isScope()) { return migratingInstance.resolveRepresentativeExecution().getEventSubscriptions(); }
else { return Collections.emptyList(); } } protected List<JobEntity> collectActivityInstanceJobs(MigratingActivityInstance migratingInstance) { if (migratingInstance.getSourceScope().isScope()) { return migratingInstance.resolveRepresentativeExecution().getJobs(); } else { return Collections.emptyList(); } } public static List<VariableInstanceEntity> getConcurrentLocalVariables(ExecutionEntity execution) { List<VariableInstanceEntity> variables = new ArrayList<VariableInstanceEntity>(); for (VariableInstanceEntity variable : execution.getVariablesInternal()) { if (variable.isConcurrentLocal()) { variables.add(variable); } } return variables; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\ActivityInstanceHandler.java
1
请完成以下Java代码
public void setM_BOM_ID (int M_BOM_ID) { if (M_BOM_ID < 1) set_ValueNoCheck (COLUMNNAME_M_BOM_ID, null); else set_ValueNoCheck (COLUMNNAME_M_BOM_ID, Integer.valueOf(M_BOM_ID)); } /** Get BOM. @return Bill of Material */ public int getM_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_BOM_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_ChangeNotice getM_ChangeNotice() throws RuntimeException { return (I_M_ChangeNotice)MTable.get(getCtx(), I_M_ChangeNotice.Table_Name) .getPO(getM_ChangeNotice_ID(), get_TrxName()); } /** Set Change Notice. @param M_ChangeNotice_ID Bill of Materials (Engineering) Change Notice (Version) */ public void setM_ChangeNotice_ID (int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_Value (COLUMNNAME_M_ChangeNotice_ID, null); else set_Value (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID)); } /** Get Change Notice. @return Bill of Materials (Engineering) Change Notice (Version) */ public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_BOM.java
1
请完成以下Java代码
public void deleteHistoricIdentityLink(String id) { if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) { getHistoricIdentityLinkEntityManager().delete(id); } } /* * (non-Javadoc) * * @see org.activiti.engine.impl.history.HistoryManagerInterface# updateProcessBusinessKeyInHistory (org.activiti.engine.impl.persistence.entity.ExecutionEntity) */ @Override public void updateProcessBusinessKeyInHistory(ExecutionEntity processInstance) { if (isHistoryEnabled()) { if (log.isDebugEnabled()) { log.debug("updateProcessBusinessKeyInHistory : {}", processInstance.getId()); } if (processInstance != null) { HistoricProcessInstanceEntity historicProcessInstance = getHistoricProcessInstanceEntityManager().findById(processInstance.getId()); if (historicProcessInstance != null) { historicProcessInstance.setBusinessKey(processInstance.getProcessInstanceBusinessKey()); getHistoricProcessInstanceEntityManager().update(historicProcessInstance, false); } } } } @Override public void recordVariableRemoved(VariableInstanceEntity variable) { if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) { HistoricVariableInstanceEntity historicProcessVariable = getEntityCache().findInCache( HistoricVariableInstanceEntity.class,
variable.getId() ); if (historicProcessVariable == null) { historicProcessVariable = getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceByVariableInstanceId( variable.getId() ); } if (historicProcessVariable != null) { getHistoricVariableInstanceEntityManager().delete(historicProcessVariable); } } } protected String parseActivityType(FlowElement element) { String elementType = element.getClass().getSimpleName(); elementType = elementType.substring(0, 1).toLowerCase() + elementType.substring(1); return elementType; } protected EntityCache getEntityCache() { return getSession(EntityCache.class); } public HistoryLevel getHistoryLevel() { return historyLevel; } public void setHistoryLevel(HistoryLevel historyLevel) { this.historyLevel = historyLevel; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\history\DefaultHistoryManager.java
1
请在Spring Boot框架中完成以下Java代码
public class SetStatusGatewayFilterFactory extends AbstractGatewayFilterFactory<SetStatusGatewayFilterFactory.Config> { /** * Status key. */ public static final String STATUS_KEY = "status"; /** * The name of the header which contains http code of the proxied request. */ private @Nullable String originalStatusHeaderName; public SetStatusGatewayFilterFactory() { super(Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(STATUS_KEY); } @Override public GatewayFilter apply(Config config) { String status = Objects.requireNonNull(config.status, "status must not be null"); HttpStatusHolder statusHolder = HttpStatusHolder.parse(status); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // option 1 (runs in filter order) /* * exchange.getResponse().beforeCommit(() -> { * exchange.getResponse().setStatusCode(finalStatus); return Mono.empty(); * }); return chain.filter(exchange); */ // option 2 (runs in reverse filter order) return chain.filter(exchange).then(Mono.fromRunnable(() -> { // check not really needed, since it is guarded in setStatusCode, // but it's a good example HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); boolean isStatusCodeUpdated = setResponseStatus(exchange, statusHolder); if (isStatusCodeUpdated && originalStatusHeaderName != null && statusCode != null) { exchange.getResponse() .getHeaders() .set(originalStatusHeaderName, singletonList(statusCode.value()).toString());
} })); } @Override public String toString() { return filterToStringCreator(SetStatusGatewayFilterFactory.this).append("status", config.getStatus()) .toString(); } }; } public @Nullable String getOriginalStatusHeaderName() { return originalStatusHeaderName; } public void setOriginalStatusHeaderName(String originalStatusHeaderName) { this.originalStatusHeaderName = originalStatusHeaderName; } public static class Config { // TODO: relaxed HttpStatus converter private @Nullable String status; public @Nullable String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetStatusGatewayFilterFactory.java
2
请在Spring Boot框架中完成以下Java代码
public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public String getProcessInstanceId() {
return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentResponse.java
2
请完成以下Java代码
public GroupHeader42 getGrpHdr() { return grpHdr; } /** * Sets the value of the grpHdr property. * * @param value * allowed object is * {@link GroupHeader42 } * */ public void setGrpHdr(GroupHeader42 value) { this.grpHdr = value; } /** * Gets the value of the ntfctn property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ntfctn property. * * <p> * For example, to add a new item, do as follows: * <pre>
* getNtfctn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AccountNotification2 } * * */ public List<AccountNotification2> getNtfctn() { if (ntfctn == null) { ntfctn = new ArrayList<AccountNotification2>(); } return this.ntfctn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_02\de\metas\payment\camt054_001_02\BankToCustomerDebitCreditNotificationV02.java
1
请完成以下Java代码
public void addBelow (Dimension dim) { addBelow (dim.width, dim.height); } // addBelow /** * Round to next Int value */ public void roundUp() { width = Math.ceil(width); height = Math.ceil(height); } // roundUp /** * Get Width * @return width */ public double getWidth() { return width; } // getWidth /** * Get Height * @return height */ public double getHeight() { return height; } // getHeight /*************************************************************************/ /** * Hash Code * @return hash code */ public int hashCode() { long bits = Double.doubleToLongBits(width); bits ^= Double.doubleToLongBits(height) * 31; return (((int) bits) ^ ((int) (bits >> 32))); } // hashCode
/** * Equals * @param obj object * @return true if w/h is same */ public boolean equals (Object obj) { if (obj != null && obj instanceof Dimension2D) { Dimension2D d = (Dimension2D)obj; if (d.getWidth() == width && d.getHeight() == height) return true; } return false; } // equals /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]"); return sb.toString(); } // toString } // Dimension2DImpl
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Dimension2DImpl.java
1
请完成以下Java代码
private void fireEventOnWebsocket(final JSONNotificationEvent event) { websocketSender.convertAndSend(websocketEndpoint, event); logger.trace("Fired notification to WS {}: {}", websocketEndpoint, event); } public UserNotificationsList getNotificationsAsList(@NonNull final QueryLimit limit) { final List<UserNotification> notifications = notificationsRepo.getByUserId(userId, limit); final boolean fullyLoaded = limit.isNoLimit() || notifications.size() <= limit.toInt(); final int totalCount; final int unreadCount; if (fullyLoaded) { totalCount = notifications.size(); unreadCount = (int)notifications.stream().filter(UserNotification::isNotRead).count(); } else { totalCount = notificationsRepo.getTotalCountByUserId(userId); unreadCount = notificationsRepo.getUnreadCountByUserId(userId); } return UserNotificationsList.of(notifications, totalCount, unreadCount); } public void addActiveSessionId(final WebuiSessionId sessionId) { Check.assumeNotNull(sessionId, "Parameter sessionId is not null"); activeSessions.add(sessionId); logger.debug("Added sessionId '{}' to {}", sessionId, this); } public void removeActiveSessionId(final WebuiSessionId sessionId) { activeSessions.remove(sessionId); logger.debug("Removed sessionId '{}' to {}", sessionId, this); } public boolean hasActiveSessions() { return !activeSessions.isEmpty(); } /* package */void addNotification(@NonNull final UserNotification notification) { final UserId adUserId = getUserId();
Check.assume(notification.getRecipientUserId() == adUserId.getRepoId(), "notification's recipient user ID shall be {}: {}", adUserId, notification); final JSONNotification jsonNotification = JSONNotification.of(notification, jsonOptions); fireEventOnWebsocket(JSONNotificationEvent.eventNew(jsonNotification, getUnreadCount())); } public void markAsRead(final String notificationId) { notificationsRepo.markAsReadById(Integer.parseInt(notificationId)); fireEventOnWebsocket(JSONNotificationEvent.eventRead(notificationId, getUnreadCount())); } public void markAllAsRead() { logger.trace("Marking all notifications as read (if any) for {}...", this); notificationsRepo.markAllAsReadByUserId(getUserId()); fireEventOnWebsocket(JSONNotificationEvent.eventReadAll()); } public int getUnreadCount() { return notificationsRepo.getUnreadCountByUserId(getUserId()); } public void setLanguage(@NonNull final String adLanguage) { this.jsonOptions = jsonOptions.withAdLanguage(adLanguage); } public void delete(final String notificationId) { notificationsRepo.deleteById(Integer.parseInt(notificationId)); fireEventOnWebsocket(JSONNotificationEvent.eventDeleted(notificationId, getUnreadCount())); } public void deleteAll() { notificationsRepo.deleteAllByUserId(getUserId()); fireEventOnWebsocket(JSONNotificationEvent.eventDeletedAll()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsQueue.java
1
请完成以下Java代码
public String getText() { return text; } public void setText(String text) { this.text = text; } public String getShortText() { return shortText; } public void setShortText(String shortText) { this.shortText = shortText; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((shortText == null) ? 0 : shortText.hashCode()); result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false;
Exam other = (Exam) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (shortText == null) { if (other.shortText != null) return false; } else if (!shortText.equals(other.shortText)) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\text\Exam.java
1
请完成以下Java代码
public abstract class EventEntity<T extends Event> implements BaseEntity<T> { public static final Map<String, String> eventColumnMap = new HashMap<>(); static { eventColumnMap.put("createdTime", "ts"); } @Id @Column(name = ModelConstants.ID_PROPERTY, columnDefinition = "uuid") protected UUID id; @Column(name = EVENT_TENANT_ID_PROPERTY, columnDefinition = "uuid") protected UUID tenantId; @Column(name = EVENT_ENTITY_ID_PROPERTY, columnDefinition = "uuid") protected UUID entityId; @Column(name = EVENT_SERVICE_ID_PROPERTY) protected String serviceId; @Column(name = TS_COLUMN) protected long ts; public EventEntity(UUID id, UUID tenantId, UUID entityId, String serviceId, long ts) { this.id = id; this.tenantId = tenantId; this.entityId = entityId; this.serviceId = serviceId; this.ts = ts; } public EventEntity(Event event) { this.id = event.getId().getId(); this.tenantId = event.getTenantId().getId(); this.entityId = event.getEntityId(); this.serviceId = event.getServiceId(); this.ts = event.getCreatedTime(); }
@Override public UUID getUuid() { return id; } @Override public void setUuid(UUID id) { this.id = id; } @Override public long getCreatedTime() { return ts; } @Override public void setCreatedTime(long createdTime) { ts = createdTime; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\EventEntity.java
1
请完成以下Java代码
public List<ProcessDefinitionEntity> getProcessDefinitions() { return processDefinitions; } public String getTargetNamespace() { return targetNamespace; } public BpmnParseHandlers getBpmnParserHandlers() { return bpmnParserHandlers; } public void setBpmnParserHandlers(BpmnParseHandlers bpmnParserHandlers) { this.bpmnParserHandlers = bpmnParserHandlers; } public DeploymentEntity getDeployment() { return deployment; } public void setDeployment(DeploymentEntity deployment) { this.deployment = deployment; } public BpmnModel getBpmnModel() { return bpmnModel; } public void setBpmnModel(BpmnModel bpmnModel) { this.bpmnModel = bpmnModel; } public ActivityBehaviorFactory getActivityBehaviorFactory() { return activityBehaviorFactory; } public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) { this.activityBehaviorFactory = activityBehaviorFactory; } public ListenerFactory getListenerFactory() { return listenerFactory; } public void setListenerFactory(ListenerFactory listenerFactory) { this.listenerFactory = listenerFactory;
} public Map<String, SequenceFlow> getSequenceFlows() { return sequenceFlows; } public ProcessDefinitionEntity getCurrentProcessDefinition() { return currentProcessDefinition; } public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public Process getCurrentProcess() { return currentProcess; } public void setCurrentProcess(Process currentProcess) { this.currentProcess = currentProcess; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek(); } public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
public final class OAuth2TokenRevocationAuthenticationProvider implements AuthenticationProvider { private final Log logger = LogFactory.getLog(getClass()); private final OAuth2AuthorizationService authorizationService; /** * Constructs an {@code OAuth2TokenRevocationAuthenticationProvider} using the * provided parameters. * @param authorizationService the authorization service */ public OAuth2TokenRevocationAuthenticationProvider(OAuth2AuthorizationService authorizationService) { Assert.notNull(authorizationService, "authorizationService cannot be null"); this.authorizationService = authorizationService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = (OAuth2TokenRevocationAuthenticationToken) authentication; OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils .getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication); RegisteredClient registeredClient = clientPrincipal.getRegisteredClient(); OAuth2Authorization authorization = this.authorizationService .findByToken(tokenRevocationAuthentication.getToken(), null); if (authorization == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Did not authenticate token revocation request since token was not found"); } // Return the authentication request when token not found return tokenRevocationAuthentication;
} if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); } OAuth2Authorization.Token<OAuth2Token> token = authorization.getToken(tokenRevocationAuthentication.getToken()); authorization = OAuth2Authorization.from(authorization).invalidate(token.getToken()).build(); this.authorizationService.save(authorization); if (this.logger.isTraceEnabled()) { this.logger.trace("Saved authorization with revoked token"); // This log is kept separate for consistency with other providers this.logger.trace("Authenticated token revocation request"); } return new OAuth2TokenRevocationAuthenticationToken(token.getToken(), clientPrincipal); } @Override public boolean supports(Class<?> authentication) { return OAuth2TokenRevocationAuthenticationToken.class.isAssignableFrom(authentication); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenRevocationAuthenticationProvider.java
1
请完成以下Java代码
public final class PaymentBatch implements IPaymentBatch { public static Builder builder() { return new Builder(); } private final String id; private final String name; private final Date date; private final ITableRecordReference record; private final IPaymentBatchProvider paymentBatchProvider; private PaymentBatch(final Builder builder) { super(); id = builder.getId(); name = builder.getName(); date = builder.getDate(); record = builder.getRecord(); paymentBatchProvider = builder.getPaymentBatchProvider(); } @Override public String toString() { // NOTE: this is used in list/combo/table renderers return name; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final PaymentBatch other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(id, other.id) .isEqual(); } @Override public String getId() { return id; } @Override public Date getDate() { return date; } @Override public ITableRecordReference getRecord() { return record; } public static final class Builder { private String id; private String name; private Date date; private ITableRecordReference record; private IPaymentBatchProvider paymentBatchProvider; private Builder() { super(); } public PaymentBatch build() { return new PaymentBatch(this); } public Builder setId(final String id) { this.id = id; return this; } private String getId() { if (id != null) { return id; } if (record != null) { return record.getTableName() + "#" + record.getRecord_ID(); } throw new IllegalStateException("id is null"); } public Builder setName(final String name) { this.name = name; return this;
} private String getName() { if (name != null) { return name; } if (record != null) { return Services.get(IMsgBL.class).translate(Env.getCtx(), record.getTableName()) + " #" + record.getRecord_ID(); } return ""; } public Builder setDate(final Date date) { this.date = date; return this; } private Date getDate() { if (date == null) { return null; } return (Date)date.clone(); } public Builder setRecord(final Object record) { this.record = TableRecordReference.of(record); return this; } private ITableRecordReference getRecord() { return record; } public Builder setPaymentBatchProvider(IPaymentBatchProvider paymentBatchProvider) { this.paymentBatchProvider = paymentBatchProvider; return this; } private IPaymentBatchProvider getPaymentBatchProvider() { return paymentBatchProvider; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\bankstatement\match\spi\PaymentBatch.java
1
请完成以下Java代码
public java.lang.String getDocumentNo () { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_RV_Prepared_And_Drafted_Documents.java
1
请在Spring Boot框架中完成以下Java代码
protected void startResetExpiredJobsThread() { if (configuration.isResetExpiredJobEnabled()) { if (resetExpiredJobThread == null) { resetExpiredJobThread = new Thread(resetExpiredJobsRunnable); } resetExpiredJobThread.start(); } } /** Stops the reset expired jobs thread */ protected void stopResetExpiredJobsThread() { if (resetExpiredJobThread != null) { try { resetExpiredJobThread.join(); } catch (InterruptedException e) { LOGGER.warn("Interrupted while waiting for the reset expired jobs thread to terminate", e); } resetExpiredJobThread = null; } } public boolean isAsyncJobAcquisitionEnabled() { return configuration.isAsyncJobAcquisitionEnabled(); } public void setAsyncJobAcquisitionEnabled(boolean isAsyncJobAcquisitionEnabled) { configuration.setAsyncJobAcquisitionEnabled(isAsyncJobAcquisitionEnabled); } public boolean isTimerJobAcquisitionEnabled() { return configuration.isTimerJobAcquisitionEnabled(); } public void setTimerJobAcquisitionEnabled(boolean isTimerJobAcquisitionEnabled) { configuration.setTimerJobAcquisitionEnabled(isTimerJobAcquisitionEnabled); } public boolean isResetExpiredJobEnabled() { return configuration.isResetExpiredJobEnabled(); } public void setResetExpiredJobEnabled(boolean isResetExpiredJobEnabled) { configuration.setResetExpiredJobEnabled(isResetExpiredJobEnabled); } public Thread getTimerJobAcquisitionThread() { return timerJobAcquisitionThread; } public void setTimerJobAcquisitionThread(Thread timerJobAcquisitionThread) { this.timerJobAcquisitionThread = timerJobAcquisitionThread; } public Thread getAsyncJobAcquisitionThread() { return asyncJobAcquisitionThread; }
public void setAsyncJobAcquisitionThread(Thread asyncJobAcquisitionThread) { this.asyncJobAcquisitionThread = asyncJobAcquisitionThread; } public Thread getResetExpiredJobThread() { return resetExpiredJobThread; } public void setResetExpiredJobThread(Thread resetExpiredJobThread) { this.resetExpiredJobThread = resetExpiredJobThread; } public boolean isUnlockOwnedJobs() { return configuration.isUnlockOwnedJobs(); } public void setUnlockOwnedJobs(boolean unlockOwnedJobs) { configuration.setUnlockOwnedJobs(unlockOwnedJobs); } @Override public AsyncTaskExecutor getTaskExecutor() { return taskExecutor; } @Override public void setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultAsyncJobExecutor.java
2
请完成以下Java代码
public class BitSetsBenchmark { private RoaringBitmap rb1; private BitSet bs1; private RoaringBitmap rb2; private BitSet bs2; private final static int SIZE = 10_000_000; @Setup public void setup() { rb1 = new RoaringBitmap(); bs1 = new BitSet(SIZE); rb2 = new RoaringBitmap(); bs2 = new BitSet(SIZE); for (int i = 0; i < SIZE / 2; i++) { rb1.add(i); bs1.set(i); } for (int i = SIZE / 2; i < SIZE; i++) { rb2.add(i); bs2.set(i); } } @Benchmark public RoaringBitmap roaringBitmapUnion() { return RoaringBitmap.or(rb1, rb2); } @Benchmark public BitSet bitSetUnion() { BitSet result = (BitSet) bs1.clone(); result.or(bs2); return result; } @Benchmark public RoaringBitmap roaringBitmapIntersection() { return RoaringBitmap.and(rb1, rb2); } @Benchmark public BitSet bitSetIntersection() {
BitSet result = (BitSet) bs1.clone(); result.and(bs2); return result; } @Benchmark public RoaringBitmap roaringBitmapDifference() { return RoaringBitmap.andNot(rb1, rb2); } @Benchmark public BitSet bitSetDifference() { BitSet result = (BitSet) bs1.clone(); result.andNot(bs2); return result; } @Benchmark public RoaringBitmap roaringBitmapXOR() { return RoaringBitmap.xor(rb1, rb2); } @Benchmark public BitSet bitSetXOR() { BitSet result = (BitSet) bs1.clone(); result.xor(bs2); return result; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\roaringbitmap\BitSetsBenchmark.java
1
请完成以下Java代码
public class CashAccountType2 { @XmlElement(name = "Cd") @XmlSchemaType(name = "string") protected CashAccountType4Code cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link CashAccountType4Code } * */ public CashAccountType4Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link CashAccountType4Code } * */ public void setCd(CashAccountType4Code value) { this.cd = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link String }
* */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashAccountType2.java
1
请完成以下Java代码
public JsonExternalStatusResponse getStatusInfo(@NonNull final ExternalSystemType externalSystemType) { return JsonExternalStatusResponse.builder() .externalStatusResponses(externalServices.getStatusInfo(externalSystemType)) .build(); } @NonNull public JsonExternalSystemInfo getExternalSystemInfo(@NonNull final ExternalSystemType externalSystemType, @NonNull final String childConfigValue) { final Optional<ExternalSystemParentConfig> parentConfig = getByTypeAndValue(externalSystemType, childConfigValue); if (!parentConfig.isPresent()) { throw MissingResourceException.builder() .resourceName("ExternalSystemConfig") .resourceIdentifier("ExternalSystemType=" + externalSystemType + "; childConfigValue=" + childConfigValue) .build(); } return jsonRetriever.retrieveExternalSystemInfo(parentConfig.get()); } @NonNull private InsertRemoteIssueRequest createInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem, final PInstanceId pInstanceId) { return InsertRemoteIssueRequest.builder() .issueCategory(jsonErrorItem.getIssueCategory()) .issueSummary(StringUtils.isEmpty(jsonErrorItem.getMessage()) ? DEFAULT_ISSUE_SUMMARY : jsonErrorItem.getMessage()) .sourceClassName(jsonErrorItem.getSourceClassName()) .sourceMethodName(jsonErrorItem.getSourceMethodName()) .stacktrace(jsonErrorItem.getStackTrace())
.errorCode(jsonErrorItem.getErrorCode()) .pInstance_ID(pInstanceId) .orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode())) .build(); } @Nullable public ExternalSystemType getExternalSystemTypeByCodeOrNameOrNull(@Nullable final String value) { final ExternalSystem externalSystem = value != null ? externalSystemRepository.getByLegacyCodeOrValueOrNull(value) : null; return externalSystem != null ? externalSystem.getType() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\ExternalSystemService.java
1
请完成以下Java代码
public List<Map.Entry<K, Float>> nearest(Vector vector, int size) { MaxHeap<Map.Entry<K, Float>> maxHeap = new MaxHeap<Map.Entry<K, Float>>(size, new Comparator<Map.Entry<K, Float>>() { @Override public int compare(Map.Entry<K, Float> o1, Map.Entry<K, Float> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<K, Vector> entry : storage.entrySet()) { maxHeap.add(new AbstractMap.SimpleEntry<K, Float>(entry.getKey(), entry.getValue().cosineForUnitVector(vector))); } return maxHeap.toList(); } /** * 获取与向量最相似的词语(默认10个) * * @param vector 向量 * @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 */ public List<Map.Entry<K, Float>> nearest(Vector vector) { return nearest(vector, 10); } /** * 查询与词语最相似的词语 * * @param key 词语 * @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 */ public List<Map.Entry<K, Float>> nearest(K key) { return nearest(key, 10); } /** * 执行查询最相似的对象(子类通过query方法决定如何解析query,然后通过此方法执行查询) * * @param query 查询语句(或者说一个对象的内容) * @param size 需要返回前多少个对象 * @return */ final List<Map.Entry<K, Float>> queryNearest(String query, int size) { if (query == null || query.length() == 0) { return Collections.emptyList(); } try { return nearest(query(query), size); } catch (Exception e) { return Collections.emptyList(); } } /** * 查询抽象文本对应的向量。此方法应当保证返回单位向量。 * * @param query * @return */ public abstract Vector query(String query);
/** * 模型中的词向量总数(词表大小) * * @return */ public int size() { return storage.size(); } /** * 模型中的词向量维度 * * @return */ public int dimension() { if (storage == null || storage.isEmpty()) { return 0; } return storage.values().iterator().next().size(); } /** * 删除元素 * * @param key * @return */ public Vector remove(K key) { return storage.remove(key); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractVectorModel.java
1
请在Spring Boot框架中完成以下Java代码
public void shutdown() { if (isStarted) server.shutdown(); } private void configurePlugins(Configuration config, RestExpress server) { configureMetrics(config, server); new SwaggerPlugin() .flag(Flags.Auth.PUBLIC_ROUTE) .register(server); new CacheControlPlugin() .register(server); new HyperExpressPlugin(Linkable.class) .register(server); new CorsHeaderPlugin("*") .flag(PUBLIC_ROUTE) .allowHeaders(CONTENT_TYPE, ACCEPT, AUTHORIZATION, REFERER, LOCATION) .exposeHeaders(LOCATION) .register(server); } private void configureMetrics(Configuration config, RestExpress server) { MetricsConfig mc = config.getMetricsConfig(); if (mc.isEnabled()) { MetricRegistry registry = new MetricRegistry(); new MetricsPlugin(registry) .register(server);
if (mc.isGraphiteEnabled()) { final Graphite graphite = new Graphite(new InetSocketAddress(mc.getGraphiteHost(), mc.getGraphitePort())); final GraphiteReporter reporter = GraphiteReporter.forRegistry(registry) .prefixedWith(mc.getPrefix()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite); reporter.start(mc.getPublishSeconds(), TimeUnit.SECONDS); } else { LOG.warn("*** Graphite Metrics Publishing is Disabled ***"); } } else { LOG.warn("*** Metrics Generation is Disabled ***"); } } private void mapExceptions(RestExpress server) { server .mapException(ItemNotFoundException.class, NotFoundException.class) .mapException(DuplicateItemException.class, ConflictException.class) .mapException(ValidationException.class, BadRequestException.class) .mapException(InvalidObjectIdException.class, BadRequestException.class); } }
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\Server.java
2
请完成以下Java代码
private long getPreloadSecondTime(String name) { // 自动刷新时间,默认是0 CacheTime cacheTime = null; if (!CollectionUtils.isEmpty(cacheTimes)) { cacheTime = cacheTimes.get(name); } Long preloadSecondTime = cacheTime != null ? cacheTime.getPreloadSecondTime() : 0; return preloadSecondTime < 0 ? 0 : preloadSecondTime; } /** * 创建缓存 * * @param cacheName 缓存名称 * @return */ @Override public CustomizedRedisCache getMissingCache(String cacheName) { // 有效时间,初始化获取默认的有效时间 Long expirationSecondTime = getExpirationSecondTime(cacheName); // 自动刷新时间,默认是0 Long preloadSecondTime = getPreloadSecondTime(cacheName); logger.info("缓存 cacheName:{},过期时间:{}, 自动刷新时间:{}", cacheName, expirationSecondTime, preloadSecondTime); // 是否在运行时创建Cache Boolean dynamic = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_DYNAMIC); // 是否允许存放NULL Boolean cacheNullValues = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHENULLVALUES); return dynamic ? new CustomizedRedisCache(cacheName, (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null),
this.getRedisOperations(), expirationSecondTime, preloadSecondTime, cacheNullValues) : null; } /** * 根据缓存名称设置缓存的有效时间和刷新时间,单位秒 * * @param cacheTimes */ public void setCacheTimess(Map<String, CacheTime> cacheTimes) { this.cacheTimes = (cacheTimes != null ? new ConcurrentHashMap<String, CacheTime>(cacheTimes) : null); } /** * 设置默认的过去时间, 单位:秒 * * @param defaultExpireTime */ @Override public void setDefaultExpiration(long defaultExpireTime) { super.setDefaultExpiration(defaultExpireTime); this.defaultExpiration = defaultExpireTime; } @Deprecated @Override public void setExpires(Map<String, Long> expires) { } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-2\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCacheManager.java
1
请在Spring Boot框架中完成以下Java代码
class ManageArticlesController { private final CreateArticleUseCase createArticle; private final EditArticleUseCase editArticle; private final DeleteArticleUseCase deleteArticle; private final ViewArticleUseCase viewArticle; @PostMapping void createArticle(@RequestBody CreateArticleRequest request) { createArticle.createArticle(request); } @PutMapping void editArticle(@RequestBody EditArticleUseCase.Request request) { editArticle.edit(request); } @DeleteMapping("/{slug}")
void deleteArticle(@PathVariable String slug) { deleteArticle.delete(slug); } @GetMapping("/{slug}") void viewArticle(@PathVariable String slug) { viewArticle.view(slug); } ManageArticlesController(CreateArticleUseCase createArticle, EditArticleUseCase editArticle, DeleteArticleUseCase deleteArticle, ViewArticleUseCase viewArticle) { this.createArticle = createArticle; this.editArticle = editArticle; this.deleteArticle = deleteArticle; this.viewArticle = viewArticle; } }
repos\tutorials-master\patterns-modules\vertical-slice-architecture\src\main\java\com\baeldung\verticalslices\author\usecases\ManageArticlesController.java
2
请在Spring Boot框架中完成以下Java代码
public Optional<Percent> getFeePercentageOfGrandTotalByBpartner(@NonNull final BPartnerId bpartnerId, @Nullable final DocTypeId invoiceDocTypeId) { final ImmutableCollection<InvoiceProcessingServiceCompanyConfigBPartnerDetails> detailsList = bpartnerDetails.get(bpartnerId); if (isEmpty(detailsList)) { return Optional.empty(); } if (invoiceDocTypeId != null) { final Optional<Percent> matchingDocTypePercent = detailsList.stream() .filter(InvoiceProcessingServiceCompanyConfigBPartnerDetails::isActive) .filter(details -> invoiceDocTypeId.equals(details.getDocTypeId())) .map(InvoiceProcessingServiceCompanyConfigBPartnerDetails::getPercent) .findFirst(); if (matchingDocTypePercent.isPresent()) { return matchingDocTypePercent; } } return detailsList.stream() .filter(InvoiceProcessingServiceCompanyConfigBPartnerDetails::isActive) .filter(details -> details.getDocTypeId() == null) .map(InvoiceProcessingServiceCompanyConfigBPartnerDetails::getPercent) .findFirst(); } public boolean isBPartnerDetailsActive(@NonNull final BPartnerId bpartnerId) { final ImmutableCollection<InvoiceProcessingServiceCompanyConfigBPartnerDetails> detailsList = bpartnerDetails.get(bpartnerId); if (detailsList.isEmpty()) { return false; }
return detailsList.stream() .anyMatch(InvoiceProcessingServiceCompanyConfigBPartnerDetails::isActive); } public boolean isValid(@NonNull final ZonedDateTime validFrom) { return this.validFrom.isBefore(validFrom) || this.validFrom.isEqual(validFrom); } } @Builder @Value /* package */ class InvoiceProcessingServiceCompanyConfigBPartnerDetails { @NonNull BPartnerId bpartnerId; @NonNull Percent percent; @Nullable DocTypeId docTypeId; @Default boolean isActive = true; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\invoiceProcessingServiceCompany\InvoiceProcessingServiceCompanyConfig.java
2
请完成以下Java代码
public void setEnvironment(ConfigurableEnvironment environment) { super.setEnvironment(environment); this.reader.setEnvironment(getEnvironment()); } /** * Load bean definitions from the given XML resources. * @param resources one or more resources to load from */ public final void load(Resource... resources) { this.reader.loadBeanDefinitions(resources); } /** * Load bean definitions from the given XML resources. * @param resourceLocations one or more resource locations to load from */ public final void load(String... resourceLocations) {
this.reader.loadBeanDefinitions(resourceLocations); } /** * Load bean definitions from the given XML resources. * @param relativeClass class whose package will be used as a prefix when loading each * specified resource name * @param resourceNames relatively-qualified names of resources to load */ public final void load(Class<?> relativeClass, String... resourceNames) { Resource[] resources = new Resource[resourceNames.length]; for (int i = 0; i < resourceNames.length; i++) { resources[i] = new ClassPathResource(resourceNames[i], relativeClass); } this.reader.loadBeanDefinitions(resources); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\XmlServletWebServerApplicationContext.java
1
请完成以下Java代码
public <T> ImmutableSet<T> toSet(@NonNull final Function<DocumentId, T> mapper) { assertNotAll(); if (documentIds.isEmpty()) { return ImmutableSet.of(); } return documentIds.stream().map(mapper).collect(ImmutableSet.toImmutableSet()); } @NonNull public ImmutableList<DocumentId> toImmutableList() { assertNotAll(); if (documentIds.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(documentIds); } @NonNull public <T> ImmutableList<T> toImmutableList(@NonNull final Function<DocumentId, T> mapper) { assertNotAll(); if (documentIds.isEmpty()) { return ImmutableList.of(); } return documentIds.stream().map(mapper).collect(ImmutableList.toImmutableList()); } public Set<Integer> toIntSet() { return toSet(DocumentId::toInt); } public <ID extends RepoIdAware> ImmutableSet<ID> toIds(@NonNull final Function<Integer, ID> idMapper) { return toSet(idMapper.compose(DocumentId::toInt)); } public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper) { return toSet(documentId -> idMapper.apply(documentId.toInt())); } /** * Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order */ public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper) { return toImmutableList(idMapper.compose(DocumentId::toInt)); } public Set<String> toJsonSet() {
if (all) { return ALL_StringSet; } return toSet(DocumentId::toJson); } public SelectionSize toSelectionSize() { if (isAll()) { return SelectionSize.ofAll(); } return SelectionSize.ofSize(size()); } public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection) { if (this.isEmpty()) { return documentIdsSelection; } else if (documentIdsSelection.isEmpty()) { return this; } if (this.all) { return this; } else if (documentIdsSelection.all) { return documentIdsSelection; } final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet()); final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds); if (this.equals(result)) { return this; } else if (documentIdsSelection.equals(result)) { return documentIdsSelection; } else { return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
1
请完成以下Java代码
public long getHitInTrxCount() { return hitInTrxCount.longValue(); } @Override public void incrementHitInTrxCount() { hitInTrxCount.incrementAndGet(); } @Override public long getMissCount() { return missCount.longValue(); } @Override public void incrementMissCount() { missCount.incrementAndGet(); } @Override public long getMissInTrxCount() {
return missInTrxCount.longValue(); } @Override public void incrementMissInTrxCount() { missInTrxCount.incrementAndGet(); } @Override public boolean isCacheEnabled() { if (cacheConfig != null) { return cacheConfig.isEnabled(); } // if no caching config is provided, it means we are dealing with an overall statistics // so we consider caching as Enabled return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheStatistics.java
1
请完成以下Java代码
public class RegulatoryAuthority2 { @XmlElement(name = "Nm") protected String nm; @XmlElement(name = "Ctry") protected String ctry; /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /**
* Gets the value of the ctry property. * * @return * possible object is * {@link String } * */ public String getCtry() { return ctry; } /** * Sets the value of the ctry property. * * @param value * allowed object is * {@link String } * */ public void setCtry(String value) { this.ctry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\RegulatoryAuthority2.java
1
请完成以下Java代码
public abstract class EDI_GenerateCSV_FileForSSCC_Labels extends JavaProcess implements IProcessPrecondition { protected final IQueryBL queryBL = Services.get(IQueryBL.class); protected final ZebraConfigRepository zebraConfigRepository = SpringContextHolder.instance.getBean(ZebraConfigRepository.class); protected static final AdMessageKey MSG_DIFFERENT_ZEBRA_CONFIG_NOT_SUPPORTED = AdMessageKey.of("WEBUI_ZebraConfigError"); private final ZebraPrinterService zebraPrinterService = SpringContextHolder.instance.getBean(ZebraPrinterService.class); private final EDIDesadvPackRepository EDIDesadvPackRepository = SpringContextHolder.instance.getBean(EDIDesadvPackRepository.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (context.getSelectionSize().isMoreThanOneSelected()) { final IQueryFilter<I_EDI_Desadv> selectedRecordsFilter = context.getQueryFilter(I_EDI_Desadv.class); final int differentConfigsSize = queryBL .createQueryBuilder(I_EDI_Desadv.class) .filter(selectedRecordsFilter) .create() .list() .stream() .map(ediDesadv -> BPartnerId.ofRepoId(ediDesadv.getC_BPartner_ID())) .map(bpartnerId -> zebraConfigRepository.retrieveZebraConfigId(bpartnerId, zebraConfigRepository.getDefaultZebraConfigId())) .collect(Collectors.toSet()) .size();
if (differentConfigsSize > 1) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(MSG_DIFFERENT_ZEBRA_CONFIG_NOT_SUPPORTED)); } } return ProcessPreconditionsResolution.accept(); } void generateCSV_FileForSSCC_Labels(@NonNull final List<EDIDesadvPackId> desadvPackIDsToPrint) { final BPartnerId bPartnerId = EDIDesadvPackRepository.retrieveBPartnerFromEdiDesadvPack(desadvPackIDsToPrint.get(0)); final ZebraConfigId zebraConfigId = zebraConfigRepository.retrieveZebraConfigId(bPartnerId, zebraConfigRepository.getDefaultZebraConfigId()); final ReportResultData reportResultData = zebraPrinterService .createCSV_FileForSSCC18_Labels(desadvPackIDsToPrint, zebraConfigId, getProcessInfo().getPinstanceId()); getProcessInfo().getResult().setReportData(reportResultData); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_GenerateCSV_FileForSSCC_Labels.java
1
请在Spring Boot框架中完成以下Java代码
public User createUser(final UserDto userDto) { final var roles = repository.findRoles(userDto.roles()); if (roles.size() != userDto.roles().size()) { throw new InvalidRolesProvidedException("Unknown role provided"); } final var user = new User(); user.setUsername(userDto.username()); user.setPassword(BcryptUtil.bcryptHash(userDto.password())); user.setRoles(new HashSet<>(roles)); user.setEmail(userDto.email());
repository.persist(user); return user; } public boolean checkUserCredentials(String username, String password) { final User user = findByUsername(username); return BcryptUtil.matches(password, user.getPassword()); } public User findByUsername(String username) { return repository.find("username", username).firstResultOptional() .orElseThrow(() -> new EntityNotFoundException(username)); } }
repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\java\com\baeldung\quarkus\rbac\users\UserService.java
2
请完成以下Java代码
public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessingTag (final @Nullable java.lang.String ProcessingTag) { set_Value (COLUMNNAME_ProcessingTag, ProcessingTag); } @Override public java.lang.String getProcessingTag() { return get_ValueAsString(COLUMNNAME_ProcessingTag); } @Override public void setSource_Record_ID (final int Source_Record_ID) { if (Source_Record_ID < 1) set_ValueNoCheck (COLUMNNAME_Source_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Source_Record_ID, Source_Record_ID); }
@Override public int getSource_Record_ID() { return get_ValueAsInt(COLUMNNAME_Source_Record_ID); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_Source_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_Source_Table_ID, Source_Table_ID); } @Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTriggering_User_ID (final int Triggering_User_ID) { if (Triggering_User_ID < 1) set_Value (COLUMNNAME_Triggering_User_ID, null); else set_Value (COLUMNNAME_Triggering_User_ID, Triggering_User_ID); } @Override public int getTriggering_User_ID() { return get_ValueAsInt(COLUMNNAME_Triggering_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Event.java
1
请完成以下Java代码
protected void configurePlugins(ProcessEngineConfigurationImpl configuration, ProcessEngineXml processEngineXml, ClassLoader classLoader) { for (ProcessEnginePluginXml pluginXml : processEngineXml.getPlugins()) { // create plugin instance Class<? extends ProcessEnginePlugin> pluginClass = loadClass(pluginXml.getPluginClass(), classLoader, ProcessEnginePlugin.class); ProcessEnginePlugin plugin = ReflectUtil.createInstance(pluginClass); // apply configured properties Map<String, String> properties = pluginXml.getProperties(); PropertyHelper.applyProperties(plugin, properties); // add to configuration configuration.getProcessEnginePlugins().add(plugin); } } protected JobExecutor getJobExecutorService(final PlatformServiceContainer serviceContainer) { // lookup container managed job executor String jobAcquisitionName = processEngineXml.getJobAcquisitionName(); JobExecutor jobExecutor = serviceContainer.getServiceValue(ServiceTypes.JOB_EXECUTOR, jobAcquisitionName); return jobExecutor; } @SuppressWarnings("unchecked") protected <T> Class<? extends T> loadClass(String className, ClassLoader customClassloader, Class<T> clazz) { try { return ReflectUtil.loadClass(className, customClassloader, clazz); } catch (ClassNotFoundException e) {
throw LOG.cannotLoadConfigurationClass(className, e); } catch (ClassCastException e) { throw LOG.configurationClassHasWrongType(className, clazz, e); } } /** * Add additional plugins that are not declared in the process engine xml. */ protected void addAdditionalPlugins(ProcessEngineConfigurationImpl configuration) { // do nothing } protected void additionalConfiguration(ProcessEngineConfigurationImpl configuration) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StartProcessEngineStep.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<MailServiceBinding> createServiceBinding(String instanceId, String bindingId) { return this.serviceInstanceExists(instanceId) .flatMap(exists -> { if (exists) { MailServiceBinding mailServiceBinding = new MailServiceBinding(bindingId, buildCredentials(instanceId, bindingId)); mailServiceBindings.put(instanceId, mailServiceBinding); return Mono.just(mailServiceBinding); } else { return Mono.empty(); } }); } public Mono<Boolean> serviceBindingExists(String instanceId, String bindingId) { return Mono.just(mailServiceBindings.containsKey(instanceId) && mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId)); } public Mono<MailServiceBinding> getServiceBinding(String instanceId, String bindingId) { if (mailServiceBindings.containsKey(instanceId) && mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId)) { return Mono.just(mailServiceBindings.get(instanceId));
} return Mono.empty(); } public Mono<Void> deleteServiceBinding(String instanceId) { mailServiceBindings.remove(instanceId); return Mono.empty(); } private Map<String, Object> buildCredentials(String instanceId, String bindingId) { Map<String, Object> credentials = new HashMap<>(); credentials.put(URI_KEY, mailSystemBaseURL + instanceId); credentials.put(USERNAME_KEY, bindingId); credentials.put(PASSWORD_KEY, UUID.randomUUID().toString()); return credentials; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-open-service-broker\src\main\java\com\baeldung\spring\cloud\openservicebroker\mail\MailService.java
2
请完成以下Java代码
public final PricingConditionsView getById(final ViewId viewId) { final PricingConditionsView view = getById(viewId); if (view == null) { throw new EntityNotFoundException("View not found: " + viewId.toJson()); } return view; } @Override public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { final PricingConditionsView view = views.getIfPresent(viewId); if (view == null || !view.isAllowClosingPerUserRequest()) { return; } if (closeAction.isDone()) { onViewClosedByUser(view); } views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } @Override public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final PricingConditionsView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PricingConditionsView createView(@NonNull final CreateViewRequest request) { final PricingConditionsRowData rowsData = createPricingConditionsRowData(request); return createView(rowsData); } protected abstract PricingConditionsRowData createPricingConditionsRowData(CreateViewRequest request); private PricingConditionsView createView(final PricingConditionsRowData rowsData) {
return PricingConditionsView.builder() .viewId(ViewId.random(windowId)) .rowsData(rowsData) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_CopyRowToEditable.class)) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_SaveEditableRow.class)) .filterDescriptors(filtersFactory.getFilterDescriptorsProvider()) .build(); } protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData() { return PricingConditionsRowsLoader.builder() .lookups(lookups); } @Override public PricingConditionsView filterView( @NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo_IGNORED) { return PricingConditionsView.cast(view) .filter(filtersFactory.extractFilters(filterViewRequest)); } private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable() .anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } protected final DocumentFilterList extractFilters(final CreateViewRequest request) { return filtersFactory.extractFilters(request); } @lombok.Value(staticConstructor = "of") private static final class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeviceInfo() { return deviceInfo; } public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getNonceStr() { return nonceStr; } public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getFeeType() { return feeType; } public void setFeeType(String feeType) { this.feeType = feeType; } public Integer getTotalFee() { return totalFee; } public void setTotalFee(Integer totalFee) { this.totalFee = totalFee; } public String getSpbillCreateIp() { return spbillCreateIp; } public void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; }
public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public WeiXinTradeTypeEnum getTradeType() { return tradeType; } public void setTradeType(WeiXinTradeTypeEnum tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } public void setLimitPay(String limitPay) { this.limitPay = limitPay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java
2
请完成以下Java代码
private void addBpartnerRecordDescriptor() { final AdWindowId bpartnerQuickInputAdWindowId = bpartnerQuickInputService.getNewBPartnerWindowId().orElse(null); if (bpartnerQuickInputAdWindowId != null) { addNewRecordDescriptor(NewRecordDescriptor.of( I_C_BPartner.Table_Name, WindowId.of(bpartnerQuickInputAdWindowId), this::handleNewBPartnerRequest)); } else { logger.warn("No window found for " + I_C_BPartner_QuickInput.Table_Name); } } private int handleNewBPartnerRequest(final ProcessNewRecordDocumentRequest request) { final I_C_BPartner_QuickInput template = InterfaceWrapperHelper.getPO(request.getDocument()); final BPartnerId bpartnerId = bpartnerQuickInputService.createBPartnerFromTemplate( template, NewRecordContext.builder() .loginOrgId(request.getLoginOrgId()) .loggedUserId(request.getLoggedUserId()) .loginLanguage(request.getLoginLanguage()) .build() ); return bpartnerId.getRepoId(); } public void addNewRecordDescriptor(@NonNull final NewRecordDescriptor newRecordDescriptor) { newRecordDescriptorsByTableName.put(newRecordDescriptor.getTableName(), newRecordDescriptor); logger.info("Registered {}", newRecordDescriptor); } public NewRecordDescriptor getNewRecordDescriptorOrNull(@NonNull final String tableName) { return newRecordDescriptorsByTableName.get(tableName); } /** * @param entityDescriptor the entity descriptor of the quick input window (e.g. for BPartner that is C_BPartner_QuickInput)
* @return new record descriptor */ public NewRecordDescriptor getNewRecordDescriptor(final DocumentEntityDescriptor entityDescriptor) { final WindowId newRecordWindowId = entityDescriptor.getWindowId(); return newRecordDescriptorsByTableName.values() .stream() .filter(descriptor -> WindowId.equals(newRecordWindowId, descriptor.getNewRecordWindowId())) .findFirst() .orElseThrow(() -> new AdempiereException("No new record quick input defined windowId=" + newRecordWindowId)); } @Nullable public DocumentEntityDescriptor getNewRecordEntityDescriptorIfAvailable(@NonNull final String tableName) { final NewRecordDescriptor newRecordDescriptor = getNewRecordDescriptorOrNull(tableName); if (newRecordDescriptor == null) { return null; } try { return documentDescriptors.getDocumentEntityDescriptor(newRecordDescriptor.getNewRecordWindowId()); } catch (final Exception ex) { logger.warn("Failed fetching document entity descriptor for {}. Ignored", newRecordDescriptor, ex); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\NewRecordDescriptorsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class Neo4jDao { private static final Logger logger = LoggerFactory.getLogger(Neo4jDao.class); private static final String packages = "cn.abel.neo4j.bean"; private SessionFactory sessionFactory = null; @Value("${neo4j.url}") private String boltUri; @Value("${neo4j.username}") private String username; @Value("${neo4j.password}") private String password; /** * 打开一个到neo4j的连接会话。 */ public Neo4jSession open() { SessionFactory factory = getSessionFactory(); Neo4jSession session = new Neo4jSession(factory); return session;
} private synchronized SessionFactory getSessionFactory() { if (sessionFactory == null) { ConfigurationSource props = () -> { Properties properties = new Properties(); properties.setProperty("URI", boltUri); properties.setProperty("username", username); properties.setProperty("password", password); return properties; }; Configuration configuration = new Configuration.Builder(props).build(); sessionFactory = new SessionFactory(configuration, packages); } return sessionFactory; } }
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\dao\Neo4jDao.java
2
请在Spring Boot框架中完成以下Java代码
private RefreshTokenFilterConfigurer refreshTokenSecurityConfigurerAdapter() { return new RefreshTokenFilterConfigurer(uaaAuthenticationService(), tokenStore); } @Bean public OAuth2CookieHelper cookieHelper() { return new OAuth2CookieHelper(oAuth2Properties); } @Bean public OAuth2AuthenticationService uaaAuthenticationService() { return new OAuth2AuthenticationService(tokenEndpointClient, cookieHelper()); } /** * Configure the ResourceServer security by installing a new TokenExtractor.
*/ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenExtractor(tokenExtractor()); } /** * The new TokenExtractor can extract tokens from Cookies and Authorization headers. * * @return the CookieTokenExtractor bean. */ @Bean public TokenExtractor tokenExtractor() { return new CookieTokenExtractor(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2AuthenticationConfiguration.java
2
请完成以下Java代码
private Node<T> getNode_rec(final Node<T> currentNode, final T value) { if (currentNode.value.equals(value)) { return currentNode; } else { final Iterator<Node<T>> iterator = currentNode.getChildren().iterator(); Node<T> requestedNode = null; while (requestedNode == null && iterator.hasNext()) { requestedNode = getNode_rec(iterator.next(), value); }
return requestedNode; } } private void listAllNodesBelow_rec(final Node<T> currentNode, final List<Node<T>> nodeList) { nodeList.add(currentNode); if (!currentNode.isLeaf()) { currentNode.getChildren().forEach(child -> listAllNodesBelow_rec(child, nodeList)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Node.java
1
请完成以下Java代码
public Field getField() { return fieldReference.getField(); } public boolean isSupportZoomInto() {return allowZoomInfo && widgetType.isSupportZoomInto();} } @Getter private enum DisplayMode { DISPLAYED(true, false), HIDDEN(false, false), DISPLAYED_BY_SYSCONFIG(true, true), HIDDEN_BY_SYSCONFIG(false, true), ; private final boolean displayed; private final boolean configuredBySysConfig; DisplayMode(final boolean displayed, final boolean configuredBySysConfig)
{ this.displayed = displayed; this.configuredBySysConfig = configuredBySysConfig; } } @Value @Builder private static class ClassViewColumnLayoutDescriptor { @NonNull JSONViewDataType viewType; DisplayMode displayMode; int seqNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\annotation\ViewColumnHelper.java
1
请完成以下Java代码
public final class KerberosMultiTier { public static final String KERBEROS_OID_STRING = "1.2.840.113554.1.2.2"; public static final Oid KERBEROS_OID = createOid(KERBEROS_OID_STRING); /** * Create a new ticket for the * @param authentication * @param username * @param lifetimeInSeconds * @param targetService * @return */ public static Authentication authenticateService(Authentication authentication, final String username, final int lifetimeInSeconds, final String targetService) { KerberosAuthentication kerberosAuthentication = (KerberosAuthentication) authentication; final JaasSubjectHolder jaasSubjectHolder = kerberosAuthentication.getJaasSubjectHolder(); Subject subject = jaasSubjectHolder.getJaasSubject(); Subject.doAs(subject, new PrivilegedAction<Object>() { @Override public Object run() { runAuthentication(jaasSubjectHolder, username, lifetimeInSeconds, targetService); return null; } }); return authentication; } public static byte[] getTokenForService(Authentication authentication, String principalName) { KerberosAuthentication kerberosAuthentication = (KerberosAuthentication) authentication; final JaasSubjectHolder jaasSubjectHolder = kerberosAuthentication.getJaasSubjectHolder(); return jaasSubjectHolder.getToken(principalName); } private static void runAuthentication(JaasSubjectHolder jaasContext, String username, int lifetimeInSeconds, String targetService) { try { GSSManager manager = GSSManager.getInstance(); GSSName clientName = manager.createName(username, GSSName.NT_USER_NAME); GSSCredential clientCredential = manager.createCredential(clientName, lifetimeInSeconds, KERBEROS_OID, GSSCredential.INITIATE_ONLY); GSSName serverName = manager.createName(targetService, GSSName.NT_USER_NAME); GSSContext securityContext = manager.createContext(serverName, KERBEROS_OID, clientCredential, GSSContext.DEFAULT_LIFETIME); securityContext.requestCredDeleg(true); securityContext.requestInteg(false); securityContext.requestAnonymity(false); securityContext.requestMutualAuth(false); securityContext.requestReplayDet(false); securityContext.requestSequenceDet(false);
boolean established = false; byte[] outToken = new byte[0]; while (!established) { byte[] inToken = new byte[0]; outToken = securityContext.initSecContext(inToken, 0, inToken.length); established = securityContext.isEstablished(); } jaasContext.addToken(targetService, outToken); } catch (Exception ex) { throw new BadCredentialsException("Kerberos authentication failed", ex); } } private static Oid createOid(String oid) { try { return new Oid(oid); } catch (GSSException ex) { throw new IllegalStateException("Unable to instantiate Oid: ", ex); } } private KerberosMultiTier() { } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosMultiTier.java
1
请完成以下Java代码
public java.lang.String getDataEntry_RecordType () { return (java.lang.String)get_Value(COLUMNNAME_DataEntry_RecordType); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Pflichtangabe. @param IsMandatory Data entry is required in this column */ @Override public void setIsMandatory (boolean IsMandatory) { set_Value (COLUMNNAME_IsMandatory, Boolean.valueOf(IsMandatory)); } /** Get Pflichtangabe. @return Data entry is required in this column */ @Override public boolean isMandatory () { Object oo = get_Value(COLUMNNAME_IsMandatory); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PersonalDataCategory AD_Reference_ID=540857
* Reference name: PersonalDataCategory */ public static final int PERSONALDATACATEGORY_AD_Reference_ID=540857; /** NotPersonal = NP */ public static final String PERSONALDATACATEGORY_NotPersonal = "NP"; /** Personal = P */ public static final String PERSONALDATACATEGORY_Personal = "P"; /** SensitivePersonal = SP */ public static final String PERSONALDATACATEGORY_SensitivePersonal = "SP"; /** Set Datenschutz-Kategorie. @param PersonalDataCategory Datenschutz-Kategorie */ @Override public void setPersonalDataCategory (java.lang.String PersonalDataCategory) { set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory); } /** Get Datenschutz-Kategorie. @return Datenschutz-Kategorie */ @Override public java.lang.String getPersonalDataCategory () { return (java.lang.String)get_Value(COLUMNNAME_PersonalDataCategory); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Field.java
1
请完成以下Java代码
public void destroy() { executor.shutdownNow(); } public void execute(Runnable command) { executor.execute(command); } public void showExecutorInfo() { LOG.info("NotifyExecutor Info : corePoolSize = " + corePoolSize + " | maxPoolSize = " + maxPoolSize + " | workQueueSize = " + workQueueSize + " | taskCount = " + executor.getTaskCount() + " | activeCount = " + executor.getActiveCount() + " | completedTaskCount = " + executor.getCompletedTaskCount()); } public void setNotifyRadio(int notifyRadio) { this.notifyRadio = notifyRadio; }
public void setWorkQueueSize(int workQueueSize) { this.workQueueSize = workQueueSize; } public void setKeepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } }
repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\utils\SettThreadPoolExecutor.java
1
请完成以下Java代码
public void remove(K key) { this.cache.remove(key); keys.remove(key); } @Override public void clear() { cache.clear(); keys.clear(); } @Override public boolean isEmpty() { return cache.isEmpty(); } @Override public Set<K> keySet() { return cache.keySet();
} @Override public int size() { return cache.size(); } /** * Removes all instances of the given key within the keys queue. */ protected void removeAll(K key) { while (keys.remove(key)) { } } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\cache\ConcurrentLruCache.java
1
请完成以下Java代码
public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; }
public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
repos\springbootwebapp-master\src\main\java\guru\springframework\domain\Product.java
1
请完成以下Java代码
public java.math.BigDecimal getTotalCr () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalCr); if (bd == null) return Env.ZERO; return bd; } /** Set Total Debit. @param TotalDr Total debit in document currency */ @Override public void setTotalDr (java.math.BigDecimal TotalDr) {
set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr); } /** Get Total Debit. @return Total debit in document currency */ @Override public java.math.BigDecimal getTotalDr () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalDr); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalBatch.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cbPartnerLocationID == null ? 0 : cbPartnerLocationID.hashCode()); result = prime * result + (gln == null ? 0 : gln.hashCode()); result = prime * result + (interchangeReferenceNo == null ? 0 : interchangeReferenceNo.hashCode()); result = prime * result + (isTest == null ? 0 : isTest.hashCode()); result = prime * result + (senderGln == null ? 0 : senderGln.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop000V other = (Cctop000V)obj; if (cbPartnerLocationID == null) { if (other.cbPartnerLocationID != null) { return false; } } else if (!cbPartnerLocationID.equals(other.cbPartnerLocationID)) { return false; } if (gln == null) { if (other.gln != null) { return false; } } else if (!gln.equals(other.gln)) { return false; } if (interchangeReferenceNo == null) { if (other.interchangeReferenceNo != null) { return false; } } else if (!interchangeReferenceNo.equals(other.interchangeReferenceNo)) { return false; }
if (isTest == null) { if (other.isTest != null) { return false; } } else if (!isTest.equals(other.isTest)) { return false; } if (senderGln == null) { if (other.senderGln != null) { return false; } } else if (!senderGln.equals(other.senderGln)) { return false; } return true; } @Override public String toString() { return "Cctop000V [cbPartnerLocationID=" + cbPartnerLocationID + ", gln=" + gln + ", senderGln=" + senderGln + ", interchangeReferenceNo=" + interchangeReferenceNo + ", isTest=" + isTest + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop000V.java
2
请完成以下Java代码
private Iterator<I_C_Invoice> retrieveInvoices() { final Stopwatch stopwatch = Stopwatch.createStarted(); // // Create the selection which we might need to update // note that selecting all unpaid and then skipping all whose open amount is > p_OpenAmt is acceptable performance-wise, // at least when we worked with 14.000 invoices and the client was running remote, over an internet connection final IQueryBuilder<I_C_Invoice> queryBuilder = queryBL .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_AD_Client_ID, getClientId()) .addEqualsFilter(I_C_Invoice.COLUMNNAME_IsPaid, false); // not already fully allocated if (!getProcessInfo().isInvokedByScheduler()) { // user selection..if any. if none, then process all final IQueryFilter<I_C_Invoice> userSelectionFilter = getProcessInfo().getQueryFilterOrElseTrue(); queryBuilder.filter(userSelectionFilter); } if (p_SOTrx != null) { queryBuilder.addEqualsFilter(PARAM_IsSOTrx, p_SOTrx.toBoolean()); } if (p_DateInvoicedFrom != null) { queryBuilder.addCompareFilter(PARAM_DateInvoiced, Operator.GREATER_OR_EQUAL, p_DateInvoicedFrom); } if (p_DateInvoicedTo != null) {
queryBuilder.addCompareFilter(PARAM_DateInvoiced, Operator.LESS_OR_EQUAL, p_DateInvoicedTo); } final IQuery<I_C_Invoice> query = queryBuilder .orderBy(I_C_Invoice.COLUMNNAME_C_Invoice_ID) .create(); addLog("Using query: " + query); final int count = query.count(); if (count > 0) { final Iterator<I_C_Invoice> iterator = query.iterate(I_C_Invoice.class); addLog("Found " + count + " invoices to evaluate. Took " + stopwatch); return iterator; } else { addLog("No invoices found. Took " + stopwatch); return Collections.emptyIterator(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_MassDiscountOrWriteOff.java
1
请完成以下Java代码
public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { return ServerCsrfTokenRequestHandler.super.resolveCsrfTokenValue(exchange, csrfToken) .switchIfEmpty(tokenFromMultipartData(exchange, csrfToken)); } /** * Specifies if the {@code ServerCsrfTokenRequestResolver} should try to resolve the * actual CSRF token from the body of multipart data requests. * @param tokenFromMultipartDataEnabled true if should read from multipart form body, * else false. Default is false */ public void setTokenFromMultipartDataEnabled(boolean tokenFromMultipartDataEnabled) { this.isTokenFromMultipartDataEnabled = tokenFromMultipartDataEnabled; } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 private Mono<String> tokenFromMultipartData(ServerWebExchange exchange, CsrfToken expected) { if (!this.isTokenFromMultipartDataEnabled) {
return Mono.empty(); } ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); MediaType contentType = headers.getContentType(); if (!MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) { return Mono.empty(); } return exchange.getMultipartData() .mapNotNull((d) -> d.getFirst(expected.getParameterName())) .cast(FormFieldPart.class) .map(FormFieldPart::value); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\ServerCsrfTokenRequestAttributeHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * 批量删除key * * @param pattern */ @Override public void removePattern(final String pattern) { Set<Serializable> keys = redisTemplate.keys(pattern); if (keys.size() > 0) { redisTemplate.delete(keys); } } /** * 删除对应的value * * @param key */ @Override public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判断缓存中是否有对应的value * * @param key * @return */ @Override public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 读取缓存 * * @param key * @return */ @Override public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key);
return result; } /** * 写入缓存 * * @param key * @param value * @return */ @Override public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ @Override public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Redis\src\main\java\com\gaoxi\redis\service\RedisServiceImpl.java
2
请完成以下Java代码
private static List<String> splitLineByDelimiter( final String line, final char cellQuote, final char cellDelimiter) { if (line == null || line.isEmpty()) { return ImmutableList.of(); } final List<String> result = new ArrayList<>(); StringBuilder currentValue = new StringBuilder(); boolean inQuotes = false; boolean startCollectChar = false; boolean doubleQuotesInColumn = false; final char[] chars = line.toCharArray(); for (final char ch : chars) { if (inQuotes) { startCollectChar = true; if (ch == cellQuote) { inQuotes = false; doubleQuotesInColumn = false; } else { // Fixed : allow "" in custom quote enclosed if (ch == '\"') { if (!doubleQuotesInColumn) { currentValue.append(ch); doubleQuotesInColumn = true; } } else { currentValue.append(ch); }
} } else { if (ch == cellQuote) { inQuotes = true; // double quotes in column will hit this! if (startCollectChar) { currentValue.append('"'); } } else if (ch == cellDelimiter) { result.add(currentValue.toString()); currentValue = new StringBuilder(); startCollectChar = false; } else { currentValue.append(ch); } } } result.add(currentValue.toString()); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FlexImpDataLineParser.java
1
请完成以下Java代码
public boolean isReadOnly(ELContext context, Object base, Object property) { return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if(base == null) { String key = (String) property; if (applicationContext.containsBean(key)) { throw new ProcessEngineException("Cannot set value of '" + property + "', it resolves to a bean defined in the Spring application-context."); } } }
@Override public Class< ? > getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object arg) { return null; } @Override public Class< ? > getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\ApplicationContextElResolver.java
1
请完成以下Java代码
public class TravelingSalesman { private static final int STOPS = 50; private static final double[][] ADJACENCE = matrix(STOPS); private static double[][] matrix(int stops) { final double radius = 100.0; double[][] matrix = new double[stops][stops]; for (int i = 0; i < stops; ++i) { for (int j = 0; j < stops; ++j) { matrix[i][j] = chord(stops, abs(i - j), radius); } } return matrix; } private static double chord(int stops, int i, double r) { return 2.0 * r * abs(sin(PI * i / stops)); } private static double dist(final int[] path) { return IntStream.range(0, STOPS) .mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]]) .sum(); } public static void main(String[] args) { final Engine<EnumGene<Integer>, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS)) .optimize(Optimize.MINIMUM) .maximalPhenotypeAge(11) .populationSize(500) .alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35))
.build(); final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); final Phenotype<EnumGene<Integer>, Double> best = engine.stream() .limit(bySteadyFitness(15)) .limit(250) .peek(statistics) .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\TravelingSalesman.java
1
请完成以下Java代码
public void dispose() { } // dispose private String m_columnName; private GridField m_mField; /** * Set Editable * @param value */ public void setEditable (boolean value) { super.setReadWrite(value); } // setEditable /** * IsEditable * @return true if editable */ public boolean isEditable() { return super.isReadWrite(); } // isEditable /** * Set Editor to value * @param value */ @Override public void setValue (Object value) { boolean sel = false; if (value != null) { if (value instanceof Boolean) sel = ((Boolean)value).booleanValue(); else sel = "Y".equals(value); } setSelected(sel); } // setValue /** * Property Change Listener * @param evt */ @Override public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); } // propertyChange /** * Return Editor value * @return value */ @Override public Object getValue() { return isSelected(); } // getValue /** * Return Display Value * @return value */ @Override public String getDisplay() { String value = isSelected() ? "Y" : "N"; return Msg.translate(Env.getCtx(), value); } // getDisplay /** * Set Background (nop) */ public void setBackground() { } // setBackground
/** * Action Listener - data binding * @param e */ @Override public void actionPerformed(ActionEvent e) { try { fireVetoableChange(m_columnName, null, getValue()); } catch (PropertyVetoException pve) { } } // actionPerformed /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic @Override public boolean isAutoCommit() { return true; } } // VCheckBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCheckBox.java
1
请完成以下Java代码
public class ClassStructureDefinition implements FieldBaseStructureDefinition { protected String id; protected Class<?> classStructure; public ClassStructureDefinition(Class<?> classStructure) { this(classStructure.getName(), classStructure); } public ClassStructureDefinition(String id, Class<?> classStructure) { this.id = id; this.classStructure = classStructure; } @Override public String getId() { return this.id; } @Override public int getFieldSize() { // TODO return 0; } @Override public String getFieldNameAt(int index) { // TODO return null;
} @Override public Class<?> getFieldTypeAt(int index) { // TODO return null; } @Override public Class<?> getFieldParameterTypeAt(int index) { // TODO return null; } @Override public StructureInstance createInstance() { return new FieldBaseStructureInstance(this); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\data\ClassStructureDefinition.java
1
请完成以下Java代码
public List<HistoricProcessInstance> findHistoricProcessInstancesAndVariablesByQueryCriteria( HistoricProcessInstanceQueryImpl historicProcessInstanceQuery ) { // paging doesn't work for combining process instances and variables // due to an outer join, so doing it in-memory if (historicProcessInstanceQuery.getFirstResult() < 0 || historicProcessInstanceQuery.getMaxResults() <= 0) { return emptyList(); } int firstResult = historicProcessInstanceQuery.getFirstResult(); int maxResults = historicProcessInstanceQuery.getMaxResults(); // setting max results, limit to 20000 results for performance reasons if (historicProcessInstanceQuery.getProcessInstanceVariablesLimit() != null) { historicProcessInstanceQuery.setMaxResults(historicProcessInstanceQuery.getProcessInstanceVariablesLimit()); } else { historicProcessInstanceQuery.setMaxResults( getProcessEngineConfiguration().getHistoricProcessInstancesQueryLimit() ); } historicProcessInstanceQuery.setFirstResult(0); List<HistoricProcessInstance> instanceList = getDbSqlSession().selectListWithRawParameterWithoutFilter( "selectHistoricProcessInstancesWithVariablesByQueryCriteria", historicProcessInstanceQuery, historicProcessInstanceQuery.getFirstResult(), historicProcessInstanceQuery.getMaxResults() ); if (instanceList != null && !instanceList.isEmpty()) { if (firstResult > 0) { if (firstResult <= instanceList.size()) { int toIndex = firstResult + Math.min(maxResults, instanceList.size() - firstResult); return instanceList.subList(firstResult, toIndex); } else { return emptyList(); }
} else { int toIndex = Math.min(maxResults, instanceList.size()); return instanceList.subList(0, toIndex); } } return instanceList; } @Override @SuppressWarnings("unchecked") public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return getDbSqlSession().selectListWithRawParameter( "selectHistoricProcessInstanceByNativeQuery", parameterMap, firstResult, maxResults ); } @Override public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricProcessInstanceCountByNativeQuery", parameterMap); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricProcessInstanceDataManager.java
1
请完成以下Java代码
public OptionalBoolean hasReferences(@NonNull final String tableName, @NonNull final String referencedTableName) { if (TABLENAMES_TO_AVOID_CACHING.contains(tableName)) { return OptionalBoolean.UNKNOWN; } return OptionalBoolean.ofBoolean(retrieveTableInfo(tableName).containsReferencedTableName(referencedTableName)); } private TableInfo retrieveTableInfo(@NonNull final String tableName) { final ImmutableSet<String> referencedTableNames = tableRecordIdDAO.getTableRecordIdReferences(tableName) .stream() .map(TableRecordIdDescriptor::getTargetTableName) .collect(ImmutableSet.toImmutableSet()); return TableInfo.builder()
.tableName(tableName) .referencedTableNames(referencedTableNames) .build(); } @Value @Builder private static class TableInfo { @NonNull String tableName; @NonNull ImmutableSet<String> referencedTableNames; public boolean containsReferencedTableName(@NonNull final String referencedTableName) {return referencedTableNames.contains(referencedTableName);} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\generic\DynamicReferencesCache.java
1
请完成以下Java代码
public static DocumentBuilderFactory defaultDocumentBuilderFactory() { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); LOG.documentBuilderFactoryConfiguration("namespaceAware", "true"); documentBuilderFactory.setValidating(false); LOG.documentBuilderFactoryConfiguration("validating", "false"); documentBuilderFactory.setIgnoringComments(true); LOG.documentBuilderFactoryConfiguration("ignoringComments", "true"); documentBuilderFactory.setIgnoringElementContentWhitespace(false); LOG.documentBuilderFactoryConfiguration("ignoringElementContentWhitespace", "false"); return documentBuilderFactory; } public static Class<?> loadClass(String classname, DataFormat dataFormat) { // first try context classoader
ClassLoader cl = Thread.currentThread().getContextClassLoader(); if(cl != null) { try { return cl.loadClass(classname); } catch(Exception e) { // ignore } } // else try the classloader which loaded the dataformat cl = dataFormat.getClass().getClassLoader(); try { return cl.loadClass(classname); } catch (ClassNotFoundException e) { throw LOG.classNotFound(classname, e); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlDataFormat.java
1
请完成以下Java代码
public String getType() { String structureRef = itemSubjectRef.getStructureRef(); return structureRef.substring(structureRef.indexOf(':') + 1); } @Override public int hashCode() { int result = 0; result = 31 * result + (itemSubjectRef.getStructureRef() != null ? itemSubjectRef.getStructureRef().hashCode() : 0); result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} ValuedDataObject otherObject = (ValuedDataObject) o; if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) { return false; } if (!otherObject.getId().equals(this.id)) { return false; } if (!otherObject.getName().equals(this.name)) { return false; } return otherObject.getValue().equals(this.value.toString()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ValuedDataObject.java
1
请完成以下Java代码
public static App createVulnerable(int port) { return new App(port, new XStream()); } private final int port; private final Set<Person> persons; private final XStream xstream; private HttpServer server; private App(int port, XStream xstream) { this.port = port; persons = new HashSet<>(); // this app is vulnerable because XStream security is not configured this.xstream = xstream; this.xstream.alias("person", Person.class); } void start() throws IOException { server = HttpServer.create(new InetSocketAddress("localhost", port), 0); server.createContext("/persons", exchange -> { switch (exchange.getRequestMethod()) { case "POST": final Person person = (Person) xstream.fromXML(exchange.getRequestBody()); persons.add(person); exchange.sendResponseHeaders(201, 0); exchange.close();
break; case "GET": exchange.sendResponseHeaders(200, 0); xstream.toXML(persons, exchange.getResponseBody()); exchange.close(); break; default: exchange.sendResponseHeaders(405, 0); exchange.close(); } }); server.start(); } void stop() { if (server != null) { server.stop(0); } } int port() { if (server == null) throw new IllegalStateException("Server not started"); return server.getAddress() .getPort(); } }
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\rce\App.java
1
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("PlainVendorReceipt ["); sb.append("product=").append(product == null ? "-" : product.getValue()); sb.append(", qtyReceived=").append(qtyReceived).append(qtyReceivedUOM == null ? "" : qtyReceivedUOM.getUOMSymbol()); sb.append(", handlingUnitsInfo=").append(handlingUnitsInfo); sb.append("]"); return sb.toString(); } @Override public I_M_Product getM_Product() { Check.assumeNotNull(product, "product not null"); return product; } public void setM_Product(final I_M_Product product) { this.product = product; } @Override public BigDecimal getQtyReceived() { Check.assumeNotNull(qtyReceived, "qtyReceived not null"); return qtyReceived; } public void setQtyReceived(final BigDecimal qtyReceived) { this.qtyReceived = qtyReceived; } @Override public I_C_UOM getQtyReceivedUOM() { Check.assumeNotNull(qtyReceivedUOM, "qtyReceivedUOM not null"); return qtyReceivedUOM; } public void setQtyReceivedUOM(final I_C_UOM qtyReceivedUOM) { this.qtyReceivedUOM = qtyReceivedUOM; }
@Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } /** * This method does nothing! */ @Override public void add(final Object IGNORED) { } /** * This method returns the empty list. */ @Override public List<Object> getModels() { return Collections.emptyList(); } @Override public I_M_PriceList_Version getPLV() { return plv; } public void setPlv(I_M_PriceList_Version plv) { this.plv = plv; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainVendorReceipt.java
1
请完成以下Java代码
public MessageCorrelationAsyncBuilder processInstanceQuery(ProcessInstanceQuery processInstanceQuery) { ensureNotNull("processInstanceQuery", processInstanceQuery); this.processInstanceQuery = processInstanceQuery; return this; } @Override public MessageCorrelationAsyncBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) { ensureNotNull("historicProcessInstanceQuery", historicProcessInstanceQuery); this.historicProcessInstanceQuery = historicProcessInstanceQuery; return this; } public MessageCorrelationAsyncBuilder setVariable(String variableName, Object variableValue) { ensureNotNull("variableName", variableName); ensurePayloadProcessInstanceVariablesInitialized(); payloadProcessInstanceVariables.put(variableName, variableValue); return this; } public MessageCorrelationAsyncBuilder setVariables(Map<String, Object> variables) { if (variables != null) { ensurePayloadProcessInstanceVariablesInitialized(); payloadProcessInstanceVariables.putAll(variables); } return this; } protected void ensurePayloadProcessInstanceVariablesInitialized() { if (payloadProcessInstanceVariables == null) { payloadProcessInstanceVariables = new VariableMapImpl(); } } @Override public Batch correlateAllAsync() { return commandExecutor.execute(new CorrelateAllMessageBatchCmd(this)); }
// getters ////////////////////////////////// public CommandExecutor getCommandExecutor() { return commandExecutor; } public String getMessageName() { return messageName; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public Map<String, Object> getPayloadProcessInstanceVariables() { return payloadProcessInstanceVariables; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationAsyncBuilderImpl.java
1
请完成以下Java代码
public class GetCaseVariableInstanceCmd implements Command<VariableInstance>, Serializable { private static final long serialVersionUID = 1L; protected String caseInstanceId; protected String variableName; public GetCaseVariableInstanceCmd(String caseInstanceId, String variableName) { this.caseInstanceId = caseInstanceId; this.variableName = variableName; } @Override public VariableInstance execute(CommandContext commandContext) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null");
} if (variableName == null) { throw new FlowableIllegalArgumentException("variableName is null"); } CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); CaseInstanceEntity caseInstance = cmmnEngineConfiguration.getCaseInstanceEntityManager().findById(caseInstanceId); if (caseInstance == null) { throw new FlowableObjectNotFoundException("case instance " + caseInstanceId + " doesn't exist", CaseInstance.class); } return caseInstance.getVariableInstance(variableName, false); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetCaseVariableInstanceCmd.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public String toString() { StringBuilder sb = new StringBuilder ("X_M_QualityInsp_LagerKonf[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Lagerkonferenz. @param M_QualityInsp_LagerKonf_ID Lagerkonferenz */ @Override public void setM_QualityInsp_LagerKonf_ID (int M_QualityInsp_LagerKonf_ID) { if (M_QualityInsp_LagerKonf_ID < 1) set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, null); else set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, Integer.valueOf(M_QualityInsp_LagerKonf_ID)); } /** Get Lagerkonferenz. @return Lagerkonferenz */ @Override public int getM_QualityInsp_LagerKonf_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf.java
1
请在Spring Boot框架中完成以下Java代码
private GitRepository getRepository(String key) { GitRepository repository = repositories.get(key); if (repository != null) { if (!GitRepository.exists(repository.getDirectory())) { // reinitializing the repository because folder was deleted initRepository(key, repository.getSettings()); } } repository = repositories.get(key); if (repository == null) { throw new IllegalStateException(key + " repository is not initialized"); } return repository; } private void initRepository(String key, RepositorySettings settings) { try { repositories.remove(key); Path directory = getRepoDirectory(settings); GitRepository repository = GitRepository.openOrClone(directory, settings, true); repositories.put(key, repository); log.info("[{}] Initialized repository", key); onUpdate(key); } catch (Throwable e) { log.error("[{}] Failed to initialize repository with settings {}", key, settings, e); } } private void onUpdate(String key) { Runnable listener = updateListeners.get(key); if (listener != null) { log.debug("[{}] Handling repository update", key); try { listener.run(); } catch (Throwable e) { log.error("[{}] Failed to handle repository update", key, e);
} } } private Path getRepoDirectory(RepositorySettings settings) { // using uri to define folder name in case repo url is changed String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", ""); return Path.of(repositoriesFolder, name); } private String getBranchRef(GitRepository repository) { return "refs/remotes/origin/" + repository.getSettings().getDefaultBranch(); } @PreDestroy private void preDestroy() { executor.shutdownNow(); } }
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\DefaultGitSyncService.java
2
请完成以下Java代码
protected void initializeDecisionTableResultMapper(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask decisionTask = getDefinition(element); DmnDecisionTaskActivityBehavior behavior = getActivityBehavior(activity); String mapper = decisionTask.getCamundaMapDecisionResult(); DecisionResultMapper decisionResultMapper = getDecisionResultMapperForName(mapper); behavior.setDecisionTableResultMapper(decisionResultMapper); } protected BaseCallableElement createCallableElement() { return new BaseCallableElement(); } protected CmmnActivityBehavior getActivityBehavior() { return new DmnDecisionTaskActivityBehavior(); } protected DmnDecisionTaskActivityBehavior getActivityBehavior(CmmnActivity activity) { return (DmnDecisionTaskActivityBehavior) activity.getActivityBehavior(); } protected String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); String decision = definition.getDecision(); if (decision == null) { DecisionRefExpression decisionExpression = definition.getDecisionExpression(); if (decisionExpression != null) { decision = decisionExpression.getText(); } } return decision; } protected String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionBinding();
} protected String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionVersion(); } protected String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionTenantId(); } protected DecisionTask getDefinition(CmmnElement element) { return (DecisionTask) super.getDefinition(element); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\DecisionTaskItemHandler.java
1
请完成以下Java代码
public class ArchiveEventManager implements IArchiveEventManager { private static final Logger logger = LogManager.getLogger(ArchiveEventManager.class); private final CopyOnWriteArrayList<IArchiveEventListener> listeners = new CopyOnWriteArrayList<>(); @Override public void registerArchiveEventListener(@NonNull final IArchiveEventListener listener) { final boolean registered = listeners.addIfAbsent(listener); if (registered) { logger.info("Registered {}", listener); } else { logger.warn("Skip registering {} because it was already registered", listener); } } @Override public void firePdfUpdate( @NonNull final I_AD_Archive archive, @Nullable final UserId userId) { for (final IArchiveEventListener listener : listeners) { listener.onPdfUpdate(archive, userId); } } @Override public void firePdfUpdate( @NonNull final I_AD_Archive archive, @Nullable final UserId userId, String action) { for (final IArchiveEventListener listener : listeners) { listener.onPdfUpdate(archive, userId, action); } } @Override public void fireEmailSent( final I_AD_Archive archive, final UserEMailConfig user, final EMailAddress emailFrom, final EMailAddress emailTo, final EMailAddress emailCc, final EMailAddress emailBcc, final ArchiveEmailSentStatus status) { for (final IArchiveEventListener listener : listeners) { listener.onEmailSent(archive, user, emailFrom, emailTo, emailCc, emailBcc, status); } } @Override public void firePrintOut( final I_AD_Archive archive, @Nullable final UserId userId, final String printerName, final int copies, @NonNull final ArchivePrintOutStatus status) {
for (final IArchiveEventListener listener : listeners) { listener.onPrintOut(archive, userId, printerName, copies, status); } } @Override public void firePrintOut( final I_AD_Archive archive, @Nullable final UserId userId, @NonNull final Set<String> printerNames, final int copies, @NonNull final ArchivePrintOutStatus status) { for (final String printerName : printerNames) { for (final IArchiveEventListener listener : listeners) { listener.onPrintOut(archive, userId, printerName, copies, status); } } } @Override public void fireVoidDocument(final I_AD_Archive archive) { for (final IArchiveEventListener listener : listeners) { listener.onVoidDocument(archive); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveEventManager.java
1
请在Spring Boot框架中完成以下Java代码
public void log(TransportProtos.ToCoreNotificationMsg msg) { totalCounter.increment(); if (msg.hasToLocalSubscriptionServiceMsg()) { toCoreNfSubscriptionServiceCounter.increment(); } else if (msg.hasFromDeviceRpcResponse()) { toCoreNfDeviceRpcResponseCounter.increment(); } else if (msg.hasComponentLifecycle()) { toCoreNfComponentLifecycleCounter.increment(); } else if (msg.getQueueUpdateMsgsCount() > 0) { toCoreNfQueueUpdateCounter.increment(); } else if (msg.getQueueDeleteMsgsCount() > 0) { toCoreNfQueueDeleteCounter.increment(); } else if (msg.hasVcResponseMsg()) { toCoreNfVersionControlResponseCounter.increment(); } else if (msg.hasToSubscriptionMgrMsg()) { toCoreNfSubscriptionManagerCounter.increment(); } else if (msg.hasNotificationRuleProcessorMsg()) { toCoreNfNotificationRuleProcessorCounter.increment(); } else { toCoreNfOtherCounter.increment();
} } public void printStats() { int total = totalCounter.get(); if (total > 0) { StringBuilder stats = new StringBuilder(); counters.forEach(counter -> stats.append(counter.getName()).append(" = [").append(counter.get()).append("] ")); log.info("Core Stats: {}", stats); } } public void reset() { counters.forEach(StatsCounter::clear); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbCoreConsumerStats.java
2
请完成以下Java代码
public Optional<BPartnerId> getBPartnerId(@NonNull final OrderLineId orderLineId) { final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); return BPartnerId.optionalOfRepoId(orderLine.getC_BPartner_ID()); } @Override public Optional<BPartnerId> getBPartnerId(@NonNull final OrderAndLineId orderLineId) { final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); return BPartnerId.optionalOfRepoId(orderLine.getC_BPartner_ID()); } @Override public void setTax(@NonNull final org.compiere.model.I_C_OrderLine orderLine) { final I_C_Order orderRecord = orderBL().getById(OrderId.ofRepoId(orderLine.getC_Order_ID())); final TaxCategoryId taxCategoryId = getTaxCategoryId(orderLine); final WarehouseId warehouseId = warehouseAdvisor.evaluateWarehouse(orderLine); final CountryId countryFromId = warehouseBL.getCountryId(warehouseId); final BPartnerLocationAndCaptureId bpLocationId = OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).getBPartnerLocationAndCaptureId(); final boolean isSOTrx = orderRecord.isSOTrx(); final Timestamp taxDate = orderLine.getDatePromised(); final BPartnerId effectiveBillPartnerId = orderBL().getEffectiveBillPartnerId(orderRecord); // if we set the tax for a sales order, consider whether the customer is exempt from taxes final Boolean isTaxExempt; if (isSOTrx && effectiveBillPartnerId != null) { final I_C_BPartner billBPartnerRecord = bpartnerDAO.getById(effectiveBillPartnerId); // Only set if TRUE - otherwise leave null (don't filter) isTaxExempt = billBPartnerRecord.isTaxExempt() ? Boolean.TRUE : null;
} else { isTaxExempt = null; } final Tax tax = taxDAO.getBy(TaxQuery.builder() .fromCountryId(countryFromId) .orgId(OrgId.ofRepoId(orderLine.getAD_Org_ID())) .bPartnerLocationId(bpLocationId) .warehouseId(warehouseId) .dateOfInterest(taxDate) .taxCategoryId(taxCategoryId) .soTrx(SOTrx.ofBoolean(isSOTrx)) .isTaxExempt(isTaxExempt) .build()); if (tax == null) { TaxNotFoundException.builder() .taxCategoryId(taxCategoryId) .isSOTrx(isSOTrx) .isTaxExempt(isTaxExempt) .billDate(taxDate) .billFromCountryId(countryFromId) .billToC_Location_ID(bpLocationId.getLocationCaptureId()) .build() .throwOrLogWarning(true, logger); } orderLine.setC_Tax_ID(tax.getTaxId().getRepoId()); orderLine.setC_TaxCategory_ID(tax.getTaxCategoryId().getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLineBL.java
1
请完成以下Java代码
public void setCreated_OrderLine_ID (final int Created_OrderLine_ID) { if (Created_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, Created_OrderLine_ID); } @Override public int getCreated_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_Created_OrderLine_ID); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class);
} @Override public void setM_CostElement(final I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost.java
1
请完成以下Java代码
public String toString() { return sb.toString(); } /** * @return underlying {@link StringBuilder}. */ public StringBuilder asStringBuilder() { return sb; } public boolean isAutoAppendSeparator() { return autoAppendSeparator; } public TokenizedStringBuilder setAutoAppendSeparator(boolean autoAppendSeparator) { this.autoAppendSeparator = autoAppendSeparator; return this; } public boolean isLastAppendedIsSeparator() { return lastAppendedIsSeparator; } public String getSeparator() { return separator;
} public TokenizedStringBuilder append(final Object obj) { if (autoAppendSeparator) { appendSeparatorIfNeeded(); } sb.append(obj); lastAppendedIsSeparator = false; return this; } public TokenizedStringBuilder appendSeparatorIfNeeded() { if (lastAppendedIsSeparator) { return this; } if (sb.length() <= 0) { return this; } sb.append(separator); lastAppendedIsSeparator = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\TokenizedStringBuilder.java
1
请完成以下Java代码
protected void doHealthCheck(Health.Builder builder) { if (getGemFireCache().filter(CacheUtils::isPeer).isPresent()) { Set<GatewaySender> gatewaySenders = getGemFireCache() .map(Cache.class::cast) .map(Cache::getGatewaySenders) .orElseGet(Collections::emptySet); builder.withDetail("geode.gateway-sender.count", gatewaySenders.size()); gatewaySenders.stream() .filter(Objects::nonNull) .forEach(gatewaySender -> { String gatewaySenderId = gatewaySender.getId(); builder.withDetail(gatewaySendersKey(gatewaySenderId, "alert-threshold"), gatewaySender.getAlertThreshold()) .withDetail(gatewaySendersKey(gatewaySenderId, "batch-conflation-enabled"), toYesNoString(gatewaySender.isBatchConflationEnabled())) .withDetail(gatewaySendersKey(gatewaySenderId, "batch-size"), gatewaySender.getBatchSize()) .withDetail(gatewaySendersKey(gatewaySenderId, "batch-time-interval"), gatewaySender.getBatchTimeInterval()) .withDetail(gatewaySendersKey(gatewaySenderId, "disk-store-name"), emptyIfUnset(gatewaySender.getDiskStoreName())) .withDetail(gatewaySendersKey(gatewaySenderId, "disk-synchronous"), toYesNoString(gatewaySender.isDiskSynchronous())) .withDetail(gatewaySendersKey(gatewaySenderId, "dispatcher-threads"), gatewaySender.getDispatcherThreads()) .withDetail(gatewaySendersKey(gatewaySenderId, "max-queue-memory"), gatewaySender.getMaximumQueueMemory()) .withDetail(gatewaySendersKey(gatewaySenderId, "max-parallelism-for-replicated-region"), gatewaySender.getMaxParallelismForReplicatedRegion()) .withDetail(gatewaySendersKey(gatewaySenderId, "order-policy"), gatewaySender.getOrderPolicy()) .withDetail(gatewaySendersKey(gatewaySenderId, "parallel"), toYesNoString(gatewaySender.isParallel())) .withDetail(gatewaySendersKey(gatewaySenderId, "paused"), toYesNoString(gatewaySender.isPaused()))
.withDetail(gatewaySendersKey(gatewaySenderId, "persistent"), toYesNoString(gatewaySender.isPersistenceEnabled())) .withDetail(gatewaySendersKey(gatewaySenderId, "remote-distributed-system-id"), gatewaySender.getRemoteDSId()) .withDetail(gatewaySendersKey(gatewaySenderId, "running"), toYesNoString(gatewaySender.isRunning())) .withDetail(gatewaySendersKey(gatewaySenderId, "socket-buffer-size"), gatewaySender.getSocketBufferSize()) .withDetail(gatewaySendersKey(gatewaySenderId, "socket-read-timeout"), gatewaySender.getSocketReadTimeout()); }); builder.up(); return; } builder.unknown(); } private String emptyIfUnset(String value) { return StringUtils.hasText(value) ? value : ""; } private String gatewaySendersKey(String id, String suffix) { return String.format("geode.gateway-sender.%1$s.%2$s", id, suffix); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeGatewaySendersHealthIndicator.java
1
请完成以下Spring Boot application配置
spring.main.banner-mode=off logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-
auto=update spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect spring.jpa.generate-ddl=true spring.jpa.show-sql=true
repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\resources\application.properties
2
请完成以下Java代码
public Priority2Code getInstrPrty() { return instrPrty; } /** * Sets the value of the instrPrty property. * * @param value * allowed object is * {@link Priority2Code } * */ public void setInstrPrty(Priority2Code value) { this.instrPrty = value; } /** * Gets the value of the svcLvl property. * * @return * possible object is * {@link ServiceLevel8Choice } * */ public ServiceLevel8Choice getSvcLvl() { return svcLvl; } /** * Sets the value of the svcLvl property. * * @param value * allowed object is * {@link ServiceLevel8Choice } * */ public void setSvcLvl(ServiceLevel8Choice value) { this.svcLvl = value; } /** * Gets the value of the lclInstrm property. * * @return * possible object is * {@link LocalInstrument2Choice } * */ public LocalInstrument2Choice getLclInstrm() { return lclInstrm; } /**
* Sets the value of the lclInstrm property. * * @param value * allowed object is * {@link LocalInstrument2Choice } * */ public void setLclInstrm(LocalInstrument2Choice value) { this.lclInstrm = value; } /** * Gets the value of the ctgyPurp property. * * @return * possible object is * {@link CategoryPurpose1CHCode } * */ public CategoryPurpose1CHCode getCtgyPurp() { return ctgyPurp; } /** * Sets the value of the ctgyPurp property. * * @param value * allowed object is * {@link CategoryPurpose1CHCode } * */ public void setCtgyPurp(CategoryPurpose1CHCode value) { this.ctgyPurp = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentTypeInformation19CH.java
1