instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static boolean contentTypeMatch(ServerRequest request, List<MediaType> contentTypes) { if (CorsUtils.isPreFlightRequest(request.exchange().getRequest())) { return true; } ServerRequest.Headers headers = request.headers(); MediaType actual; try { actual = headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM); } catch (InvalidMediaTypeException ex) { throw new UnsupportedMediaTypeStatusException("Could not parse " + "Content-Type [" + headers.firstHeader(HttpHeaders.CONTENT_TYPE) + "]: " + ex.getMessage()); } boolean contentTypeMatch = false; for (MediaType contentType : contentTypes) { contentTypeMatch = contentType.includes(actual); traceMatch("Content-Type", contentTypes, actual, contentTypeMatch); if (contentTypeMatch) { break; } } return contentTypeMatch; } private static boolean acceptMatch(ServerRequest request, List<MediaType> expected) { if (CorsUtils.isPreFlightRequest(request.exchange().getRequest())) { return true; } ServerRequest.Headers headers = request.headers(); List<MediaType> acceptedMediaTypes; try { acceptedMediaTypes = acceptedMediaTypes(headers); } catch (InvalidMediaTypeException ex) { throw new NotAcceptableStatusException("Could not parse " + "Accept header [" + headers.firstHeader(HttpHeaders.ACCEPT) + "]: " + ex.getMessage()); } boolean match = false; outer: for (MediaType acceptedMediaType : acceptedMediaTypes) {
for (MediaType mediaType : expected) { if (acceptedMediaType.isCompatibleWith(mediaType)) { match = true; break outer; } } } traceMatch("Accept", expected, acceptedMediaTypes, match); return match; } private static List<MediaType> acceptedMediaTypes(ServerRequest.Headers headers) { List<MediaType> acceptedMediaTypes = headers.accept(); if (acceptedMediaTypes.isEmpty()) { acceptedMediaTypes = Collections.singletonList(MediaType.ALL); } else { MimeTypeUtils.sortBySpecificity(acceptedMediaTypes); } return acceptedMediaTypes; } private static boolean pathMatch(ServerRequest request, PathPattern pattern) { PathContainer pathContainer = request.requestPath().pathWithinApplication(); boolean pathMatch = pattern.matches(pathContainer); traceMatch("Pattern", pattern.getPatternString(), request.path(), pathMatch); if (pathMatch) { request.attributes().put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern); } return pathMatch; } private static void traceMatch(String prefix, Object desired, @Nullable Object actual, boolean match) { if (logger.isTraceEnabled()) { logger.trace(String.format("%s \"%s\" %s against value \"%s\"", prefix, desired, match ? "matches" : "does not match", actual)); } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\GraphQlRequestPredicates.java
1
请完成以下Java代码
public boolean isVisited() { return isVisited; } public void setVisited(boolean visited) { isVisited = visited; } public Pair<Vertex, Edge> nextMinimum(){ Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getKey().isVisited()){ if (!pair.getValue().isIncluded()) { if (pair.getValue().getWeight() < nextMinimum.getWeight()) { nextMinimum = pair.getValue(); nextVertex = pair.getKey(); } } } } return new Pair<>(nextVertex, nextMinimum); } public String originalToString(){ StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } return sb.toString(); } public String includedToString(){ StringBuilder sb = new StringBuilder();
if (isVisited()) { Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (pair.getValue().isIncluded()) { if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } } } return sb.toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\prim\Vertex.java
1
请完成以下Java代码
public class HUMaterialTrackingBL implements IHUMaterialTrackingBL { /** * @param ctx * @return {@link I_M_Attribute} for {@link #ATTRIBUTENAME_IsQualityInspection} */ I_M_Attribute getIsQualityInspectionAttribute() { final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class); final I_M_Attribute attribute = attributeDAO.retrieveAttributeByValue(ATTRIBUTENAME_IsQualityInspection); Check.assumeNotNull(attribute, "attribute shall exist for {}", ATTRIBUTENAME_IsQualityInspection); return attribute; } @Override public Optional<IQualityInspectionSchedulable> asQualityInspectionSchedulable(final IContextAware context, final IAttributeStorage attributeStorage) { return AttributeStorageQualityInspectionSchedulable.of(this, context, attributeStorage); } @Override public void updateHUAttributeRecursive(final I_M_HU hu,
final I_M_Material_Tracking materialTracking, final String onlyHUStatus) { final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); final IHUAttributesBL huAttributesBL = Services.get(IHUAttributesBL.class); final I_M_Attribute materialTrackingAttribute = materialTrackingAttributeBL.getMaterialTrackingAttribute(); final Object attributeValue = materialTracking == null ? null : materialTracking.getM_Material_Tracking_ID(); huAttributesBL.updateHUAttributeRecursive(hu, materialTrackingAttribute, attributeValue, onlyHUStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\impl\HUMaterialTrackingBL.java
1
请完成以下Java代码
public static class Builder { private int C_Invoice_Candidate_ID; private String BPartnerName; private Date documentDate; // task 09643 private Date dateAcct; private Date dateToInvoice; private Date dateInvoiced; private BigDecimal netAmtToInvoice; private BigDecimal netAmtInvoiced; private BigDecimal discount; private String currencyISOCode; private String invoiceRuleName; private String headerAggregationKey; private Builder() { super(); } public InvoiceCandidateRow build() { return new InvoiceCandidateRow(this); } public Builder setC_Invoice_Candidate_ID(int C_Invoice_Candidate_ID) { this.C_Invoice_Candidate_ID = C_Invoice_Candidate_ID; return this; } public Builder setBPartnerName(String BPartnerName) { this.BPartnerName = BPartnerName; return this; } public Builder setDocumentDate(Date documentDate) { this.documentDate = documentDate; return this; } /** * task 09643: separate accounting date from the transaction date * * @param dateAcct * @return */ public Builder setDateAcct(Date dateAcct) {
this.dateAcct = dateAcct; return this; } public Builder setDateToInvoice(Date dateToInvoice) { this.dateToInvoice = dateToInvoice; return this; } public Builder setDateInvoiced(Date dateInvoiced) { this.dateInvoiced = dateInvoiced; return this; } public Builder setNetAmtToInvoice(BigDecimal netAmtToInvoice) { this.netAmtToInvoice = netAmtToInvoice; return this; } public Builder setNetAmtInvoiced(BigDecimal netAmtInvoiced) { this.netAmtInvoiced = netAmtInvoiced; return this; } public Builder setDiscount(BigDecimal discount) { this.discount = discount; return this; } public Builder setCurrencyISOCode(String currencyISOCode) { this.currencyISOCode = currencyISOCode; return this; } public Builder setInvoiceRuleName(String invoiceRuleName) { this.invoiceRuleName = invoiceRuleName; return this; } public Builder setHeaderAggregationKey(String headerAggregationKey) { this.headerAggregationKey = headerAggregationKey; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidateRow.java
1
请完成以下Java代码
public String getClientInfo() { final String javaVersion = System.getProperty("java.version"); return new StringBuilder("Swing, java.version=").append(javaVersion).toString(); } @Override public void showWindow(final Object model) { Check.assumeNotNull(model, "model not null"); final int adTableId = InterfaceWrapperHelper.getModelTableId(model); final int recordId = InterfaceWrapperHelper.getId(model); AEnv.zoom(adTableId, recordId); } @Override public IClientUIInvoker invoke() { return new SwingClientUIInvoker(this); } @Override
public IClientUIAsyncInvoker invokeAsync() { return new SwingClientUIAsyncInvoker(); } @Override public void showURL(final String url) { try { final URI uri = new URI(url); Desktop.getDesktop().browse(uri); } catch (Exception e) { logger.warn("Failed opening " + url, e.getLocalizedMessage()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIInstance.java
1
请完成以下Java代码
public ExistingLockInfo getLockInfo(@NonNull final TableRecordReference tableRecordReference, @Nullable final LockOwner lockOwner) { try (final CloseableReentrantLock ignored = mainLock.open()) { final LockKey lockKey = LockKey.ofTableRecordReference(tableRecordReference); final RecordLocks recordLocks = locks.get(lockKey); if (recordLocks == null) { return null; } final LockOwner lockOwnerToUse = lockOwner == null ? LockOwner.NONE : lockOwner; final LockInfo lockInfo = recordLocks.getLockByOwner(lockOwnerToUse); if (lockInfo == null) { return null; } return toExistingLockInfo(lockInfo, tableRecordReference); } } private static ExistingLockInfo toExistingLockInfo(@NonNull final LockInfo lockInfo, @NonNull final TableRecordReference tableRecordReference) { return ExistingLockInfo.builder() .ownerName(lockInfo.getLockOwner().getOwnerName()) .lockedRecord(tableRecordReference) .allowMultipleOwners(lockInfo.isAllowMultipleOwners()) .autoCleanup(lockInfo.isAutoCleanup()) .created(lockInfo.getAcquiredAt()) .build(); } @Override public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(@NonNull final TableRecordReferenceSet recordRefs) { if (recordRefs.isEmpty()) { return ImmutableSetMultimap.of(); } final ImmutableSetMultimap.Builder<TableRecordReference, ExistingLockInfo> result = ImmutableSetMultimap.builder(); try (final CloseableReentrantLock ignored = mainLock.open()) { for (final TableRecordReference recordRef : recordRefs) {
final LockKey lockKey = LockKey.ofTableRecordReference(recordRef); final RecordLocks recordLocks = locks.get(lockKey); if (recordLocks == null) { continue; } for (final LockInfo lockInfo : recordLocks.getLocks()) { result.put(recordRef, toExistingLockInfo(lockInfo, recordRef)); } } return result.build(); } } @Value(staticConstructor = "of") public static class LockKey { int adTableId; int recordId; public static LockKey ofTableRecordReference(@NonNull final TableRecordReference recordRef) {return of(recordRef.getAD_Table_ID(), recordRef.getRecord_ID());} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\spi\impl\PlainLockDatabase.java
1
请在Spring Boot框架中完成以下Java代码
public void customize(ClientBuilder builder) { builder.withJsonConverter(this.converter); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter(this.converter); } } private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition { PreferGsonOrJacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson") static class GsonPreferred { } @Conditional(JacksonAndJsonbUnavailableCondition.class) static class JacksonJsonbUnavailable { } } private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { JacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); }
@ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonAvailable { } @SuppressWarnings("removal") @ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class) static class Jackson2Available { } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol) { set_Value (COLUMNNAME_UOMSymbol, UOMSymbol); } @Override public java.lang.String getUOMSymbol() { return get_ValueAsString(COLUMNNAME_UOMSymbol); } @Override public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID) { if (WEBUI_KPI_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID); } @Override public int getWEBUI_KPI_Field_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class); } @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); }
@Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java
1
请在Spring Boot框架中完成以下Java代码
public NursingHome timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NursingHome nursingHome = (NursingHome) o; return Objects.equals(this._id, nursingHome._id) && Objects.equals(this.name, nursingHome.name) && Objects.equals(this.address, nursingHome.address) && Objects.equals(this.postalCode, nursingHome.postalCode) && Objects.equals(this.city, nursingHome.city) && Objects.equals(this.phone, nursingHome.phone) && Objects.equals(this.fax, nursingHome.fax) && Objects.equals(this.email, nursingHome.email) && Objects.equals(this.timestamp, nursingHome.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, timestamp); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class NursingHome {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\NursingHome.java
2
请完成以下Java代码
public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null)
{ if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** 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_PrintColor.java
1
请在Spring Boot框架中完成以下Java代码
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException { return new EntityScanner(this.applicationContext).scan(Table.class); } @Override @Bean @ConditionalOnMissingBean public RelationalManagedTypes jdbcManagedTypes() throws ClassNotFoundException { return super.jdbcManagedTypes(); } @Override @Bean @ConditionalOnMissingBean public JdbcMappingContext jdbcMappingContext(Optional<NamingStrategy> namingStrategy, JdbcCustomConversions customConversions, RelationalManagedTypes jdbcManagedTypes) { return super.jdbcMappingContext(namingStrategy, customConversions, jdbcManagedTypes); } @Override @Bean @ConditionalOnMissingBean public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations, @Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, JdbcDialect dialect) { return super.jdbcConverter(mappingContext, operations, relationResolver, conversions, dialect); } @Override @Bean @ConditionalOnMissingBean public JdbcCustomConversions jdbcCustomConversions() { return super.jdbcCustomConversions(); } @Override @Bean @ConditionalOnMissingBean public JdbcAggregateTemplate jdbcAggregateTemplate(ApplicationContext applicationContext, JdbcMappingContext mappingContext, JdbcConverter converter, DataAccessStrategy dataAccessStrategy) { return super.jdbcAggregateTemplate(applicationContext, mappingContext, converter, dataAccessStrategy);
} @Override @Bean @ConditionalOnMissingBean public DataAccessStrategy dataAccessStrategyBean(NamedParameterJdbcOperations operations, JdbcConverter jdbcConverter, JdbcMappingContext context, JdbcDialect dialect) { return super.dataAccessStrategyBean(operations, jdbcConverter, context, dialect); } @Override @Bean @ConditionalOnMissingBean public JdbcDialect jdbcDialect(NamedParameterJdbcOperations operations) { DataJdbcDatabaseDialect dialect = this.properties.getDialect(); return (dialect != null) ? dialect.getJdbcDialect(operations.getJdbcOperations()) : super.jdbcDialect(operations); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-jdbc\src\main\java\org\springframework\boot\data\jdbc\autoconfigure\DataJdbcRepositoriesAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class FooController { @Autowired FooRepository repository; @GetMapping public ResponseEntity<List<Foo>> getAllFoos() { List<Foo> fooList = (List<Foo>) repository.findAll(); if (fooList.isEmpty()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(fooList, HttpStatus.OK); } @GetMapping(value = "{id}") public ResponseEntity<Foo> getFooById(@PathVariable("id") Long id) { Optional<Foo> foo = repository.findById(id); return foo.map(value -> new ResponseEntity<>(value, HttpStatus.OK)) .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PostMapping public ResponseEntity<Foo> addFoo(@RequestBody @Valid Foo foo) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(linkTo(FooController.class).slash(foo.getId()) .toUri()); Foo savedFoo; try { savedFoo = repository.save(foo); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
} @DeleteMapping("/{id}") public ResponseEntity<Void> deleteFoo(@PathVariable("id") long id) { try { repository.deleteById(id); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @PutMapping("/{id}") public ResponseEntity<Foo> updateFoo(@PathVariable("id") long id, @RequestBody Foo foo) { boolean isFooPresent = repository.existsById(id); if (!isFooPresent) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } Foo updatedFoo = repository.save(foo); return new ResponseEntity<>(updatedFoo, HttpStatus.OK); } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\restdocopenapi\FooController.java
2
请完成以下Java代码
public String getSql() { buildSql(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx) { buildSql(); return sqlParams; } private final void buildSql() { if (sqlBuilt) { return; } final StringBuilder sqlWhereClause = new StringBuilder(); final ImmutableList.Builder<Object> sqlParams = ImmutableList.builder(); // (ValidFrom IS NULL OR ValidFrom <= Date) if (validFromColumnName != null) { sqlWhereClause.append("("); sqlWhereClause.append(validFromColumnName).append(" IS NULL"); sqlWhereClause.append(" OR ").append(validFromColumnName).append(" <= ?"); sqlWhereClause.append(")"); sqlParams.add(dateValue); } // (ValidTo IS NULL OR ValidTo >= Date) if (validToColumnName != null) { if (sqlWhereClause.length() > 0) { sqlWhereClause.append(" AND "); } sqlWhereClause.append("("); sqlWhereClause.append(validToColumnName).append(" IS NULL"); sqlWhereClause.append(" OR ").append(validToColumnName).append(" >= ?"); sqlWhereClause.append(")"); sqlParams.add(dateValue); } this.sqlWhereClause = sqlWhereClause.toString(); this.sqlParams = sqlParams.build(); this.sqlBuilt = true; }
@Override public boolean accept(final T model) { final Date validFrom = getDate(model, validFromColumnName); if (validFrom != null && validFrom.compareTo(dateValue) > 0) { return false; } final Date validTo = getDate(model, validToColumnName); if (validTo != null && validTo.compareTo(dateValue) < 0) { return false; } return true; } private final Date getDate(final T model, final String dateColumnName) { if (dateColumnName == null) { return null; } if (!InterfaceWrapperHelper.hasModelColumnName(model, dateColumnName)) { return null; } final Optional<Date> date = InterfaceWrapperHelper.getValue(model, dateColumnName); return date.orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ValidFromToMatchesQueryFilter.java
1
请完成以下Java代码
public VariableInstanceEntity create() { VariableInstanceEntityImpl variableInstanceEntity = new VariableInstanceEntityImpl(); variableInstanceEntity.setRevision(0); // For backwards compatibility, variables / HistoricVariableUpdate assumes revision 0 for the first time return variableInstanceEntity; } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByTaskId(String taskId) { return getDbSqlSession().selectList("selectVariablesByTaskId", taskId); } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByTaskIds(Set<String> taskIds) { return getDbSqlSession().selectList("selectVariablesByTaskIds", taskIds); } @Override public List<VariableInstanceEntity> findVariableInstancesByExecutionId(final String executionId) { return getList("selectVariablesByExecutionId", executionId, variableInstanceEntity, true); } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByExecutionIds(Set<String> executionIds) { return getDbSqlSession().selectList("selectVariablesByExecutionIds", executionIds); } @Override public VariableInstanceEntity findVariableInstanceByExecutionAndName(String executionId, String variableName) { Map<String, String> params = new HashMap<String, String>(2); params.put("executionId", executionId); params.put("name", variableName); return (VariableInstanceEntity) getDbSqlSession().selectOne("selectVariableInstanceByExecutionAndName", params);
} @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByExecutionAndNames( String executionId, Collection<String> names ) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("executionId", executionId); params.put("names", names); return getDbSqlSession().selectList("selectVariableInstancesByExecutionAndNames", params); } @Override public VariableInstanceEntity findVariableInstanceByTaskAndName(String taskId, String variableName) { Map<String, String> params = new HashMap<String, String>(2); params.put("taskId", taskId); params.put("name", variableName); return (VariableInstanceEntity) getDbSqlSession().selectOne("selectVariableInstanceByTaskAndName", params); } @Override @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByTaskAndNames(String taskId, Collection<String> names) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("taskId", taskId); params.put("names", names); return getDbSqlSession().selectList("selectVariableInstancesByTaskAndNames", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisVariableInstanceDataManager.java
1
请在Spring Boot框架中完成以下Java代码
public Result<IPage<SysDataLog>> queryPageList(SysDataLog dataLog,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) { Result<IPage<SysDataLog>> result = new Result<IPage<SysDataLog>>(); dataLog.setType(CommonConstant.DATA_LOG_TYPE_JSON); QueryWrapper<SysDataLog> queryWrapper = QueryGenerator.initQueryWrapper(dataLog, req.getParameterMap()); Page<SysDataLog> page = new Page<SysDataLog>(pageNo, pageSize); IPage<SysDataLog> pageList = service.page(page, queryWrapper); log.info("查询当前页:"+pageList.getCurrent()); log.info("查询当前页数量:"+pageList.getSize()); log.info("查询结果数量:"+pageList.getRecords().size()); log.info("数据总数:"+pageList.getTotal()); result.setSuccess(true); result.setResult(pageList); return result; } /** * 查询对比数据 * @param req * @return */ @RequestMapping(value = "/queryCompareList", method = RequestMethod.GET) public Result<List<SysDataLog>> queryCompareList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataId1 = req.getParameter("dataId1"); String dataId2 = req.getParameter("dataId2"); List<String> idList = new ArrayList<String>(); idList.add(dataId1); idList.add(dataId2); try { List<SysDataLog> list = (List<SysDataLog>) service.listByIds(idList); result.setResult(list); result.setSuccess(true); } catch (Exception e) { log.error(e.getMessage(),e); }
return result; } /** * 查询版本信息 * @param req * @return */ @RequestMapping(value = "/queryDataVerList", method = RequestMethod.GET) public Result<List<SysDataLog>> queryDataVerList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataTable = req.getParameter("dataTable"); String dataId = req.getParameter("dataId"); QueryWrapper<SysDataLog> queryWrapper = new QueryWrapper<SysDataLog>(); queryWrapper.eq("data_table", dataTable); queryWrapper.eq("data_id", dataId); // 代码逻辑说明: 新增查询条件-type String type = req.getParameter("type"); if (oConvertUtils.isNotEmpty(type)) { queryWrapper.eq("type", type); } // 按时间倒序排 queryWrapper.orderByDesc("create_time"); List<SysDataLog> list = service.list(queryWrapper); if(list==null||list.size()<=0) { result.error500("未找到版本信息"); }else { result.setResult(list); result.setSuccess(true); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDataLogController.java
2
请完成以下Java代码
public static void concatByStreamBy100(Blackhole blackhole) { concatByStream(DATA_100, blackhole); } @Benchmark public static void concatByStreamBy1000(Blackhole blackhole) { concatByStream(DATA_1000, blackhole); } @Benchmark public static void concatByStreamBy10000(Blackhole blackhole) { concatByStream(DATA_10000, blackhole); } public static void concatByStream(String[] data, Blackhole blackhole) {
String concatString = ""; List<String> strList = List.of(data); concatString = strList.stream().collect(Collectors.joining("")); blackhole.consume(concatString); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(BatchConcatBenchmark.class.getSimpleName()).threads(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\performance\BatchConcatBenchmark.java
1
请在Spring Boot框架中完成以下Java代码
public class LedgerEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "timeStamp") private Long timeStamp; @Column(name = "parentId") private Long parentId; @Column(name = "checksum") private String checksum; @Column(name = "event") private String event; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTimeStamp() { return timeStamp; } public void setTimeStamp(Long timeStamp) { this.timeStamp = timeStamp; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; }
public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getChecksum() { return checksum; } public void setChecksum(String checksum) { this.checksum = checksum; } }
repos\spring-examples-java-17\spring-bank\bank-server\src\main\java\itx\examples\springbank\server\repository\model\LedgerEntity.java
2
请完成以下Java代码
public void setIncludeJobDefinitionsWithoutTenantId(Boolean includeJobDefinitionsWithoutTenantId) { this.includeJobDefinitionsWithoutTenantId = includeJobDefinitionsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected JobDefinitionQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createJobDefinitionQuery(); } @Override protected void applyFilters(JobDefinitionQuery query) { if (jobDefinitionId != null) { query.jobDefinitionId(jobDefinitionId); } if (activityIdIn != null && activityIdIn.length > 0) { query.activityIdIn(activityIdIn); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (jobType != null) { query.jobType(jobType); } if (jobConfiguration != null) { query.jobConfiguration(jobConfiguration); } if (TRUE.equals(active)) {
query.active(); } if (TRUE.equals(suspended)) { query.suspended(); } if (TRUE.equals(withOverridingJobPriority)) { query.withOverridingJobPriority(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeJobDefinitionsWithoutTenantId)) { query.includeJobDefinitionsWithoutTenantId(); } } @Override protected void applySortBy(JobDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) { query.orderByJobDefinitionId(); } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { query.orderByActivityId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_JOB_TYPE)) { query.orderByJobType(); } else if (sortBy.equals(SORT_BY_JOB_CONFIGURATION)) { query.orderByJobConfiguration(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentResource { private static final String ID = "/{id}"; private final StudentRepository studentRepository; public StudentResource(StudentRepository studentRepository) { this.studentRepository = studentRepository; } @GetMapping public List<Student> retrieveAllStudents() { return studentRepository.findAll(); } @GetMapping(ID) public Student retrieveStudent(@PathVariable long id) { Optional<Student> student = studentRepository.findById(id); if (student.isEmpty()) throw new StudentNotFoundException("id-" + id); return student.get(); } @DeleteMapping(ID) public void deleteStudent(@PathVariable long id) { studentRepository.deleteById(id); } @PostMapping public ResponseEntity<Object> createStudent(@RequestBody Student student) { Student savedStudent = studentRepository.save(student); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedStudent.getId())
.toUri(); return ResponseEntity.created(location).build(); } @PutMapping(ID) public ResponseEntity<Object> updateStudent(@RequestBody Student student, @PathVariable long id) { Optional<Student> studentOptional = studentRepository.findById(id); if (studentOptional.isEmpty()) return ResponseEntity.notFound().build(); student.setId(id); studentRepository.save(student); return ResponseEntity.noContent().build(); } }
repos\spring-boot-examples-master\spring-boot-2-rest-service-content-negotiation\src\main\java\com\in28minutes\springboot\rest\example\student\StudentResource.java
2
请完成以下Java代码
public void setClassname (String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Classname. @return Java Classname */ public String getClassname () { return (String)get_Value(COLUMNNAME_Classname); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Manual. @param IsManual This is a manual process */ public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manual. @return This is a manual process */ public boolean isManual ()
{ Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set SLA Criteria. @param PA_SLA_Criteria_ID Service Level Agreement Criteria */ public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID) { if (PA_SLA_Criteria_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID)); } /** Get SLA Criteria. @return Service Level Agreement Criteria */ public int getPA_SLA_Criteria_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Criteria.java
1
请完成以下Java代码
public TopicSubscription open() { if (topicName == null) { throw LOG.topicNameNullException(); } if (lockDuration != null && lockDuration <= 0L) { throw LOG.lockDurationIsNotGreaterThanZeroException(lockDuration); } if (externalTaskHandler == null) { throw LOG.externalTaskHandlerNullException(); } TopicSubscriptionImpl subscription = new TopicSubscriptionImpl(topicName, lockDuration, externalTaskHandler, topicSubscriptionManager, variableNames, businessKey); if (processDefinitionId != null) { subscription.setProcessDefinitionId(processDefinitionId); } if (processDefinitionIds != null) { subscription.setProcessDefinitionIdIn(processDefinitionIds); } if (processDefinitionKey != null) { subscription.setProcessDefinitionKey(processDefinitionKey); } if (processDefinitionKeys != null) { subscription.setProcessDefinitionKeyIn(processDefinitionKeys); } if (withoutTenantId) { subscription.setWithoutTenantId(withoutTenantId); } if (tenantIds != null) { subscription.setTenantIdIn(tenantIds); } if(processDefinitionVersionTag != null) { subscription.setProcessDefinitionVersionTag(processDefinitionVersionTag); }
if (processVariables != null) { subscription.setProcessVariables(processVariables); } if (localVariables) { subscription.setLocalVariables(localVariables); } if(includeExtensionProperties) { subscription.setIncludeExtensionProperties(includeExtensionProperties); } topicSubscriptionManager.subscribe(subscription); return subscription; } protected void ensureNotNull(Object tenantIds, String parameterName) { if (tenantIds == null) { throw LOG.passNullValueParameter(parameterName); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionBuilderImpl.java
1
请完成以下Java代码
public String acquireSuffix(@Nullable String txIdPrefix) { Assert.notNull(txIdPrefix, "'txIdPrefix' must not be null"); BlockingQueue<String> cache = getSuffixCache(txIdPrefix); if (cache == null) { return String.valueOf(this.transactionIdSuffix.getAndIncrement()); } String suffix = cache.poll(); if (suffix == null) { throw new NoProducerAvailableException("No available transaction producer", txIdPrefix); } return suffix; } @Override public void releaseSuffix(@Nullable String txIdPrefix, @Nullable String suffix) { Assert.notNull(txIdPrefix, "'txIdPrefix' must not be null"); Assert.notNull(suffix, "'suffix' must not be null"); if (this.maxCache <= 0) { return; } BlockingQueue<String> queue = getSuffixCache(txIdPrefix);
if (queue != null && !queue.contains(suffix)) { queue.add(suffix); } } @Nullable private BlockingQueue<String> getSuffixCache(String txIdPrefix) { if (this.maxCache <= 0) { return null; } return this.suffixCache.computeIfAbsent(txIdPrefix, txId -> { BlockingQueue<String> queue = new LinkedBlockingQueue<>(); for (int suffix = 0; suffix < this.maxCache; suffix++) { queue.add(String.valueOf(this.transactionIdSuffix.getAndIncrement())); } return queue; }); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\DefaultTransactionIdSuffixStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isExcludeSubtasks() { return excludeSubtasks; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } @Override public List<Task> list() { cachedCandidateGroups = null; return super.list(); } @Override public List<Task> listPage(int firstResult, int maxResults) { cachedCandidateGroups = null; return super.listPage(firstResult, maxResults); } @Override public long count() { cachedCandidateGroups = null; return super.count(); } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; }
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java
2
请完成以下Java代码
public List<Object[]> fetchColumnWithNativeQuery() { return session.createNativeQuery("SELECT * FROM Student student") .list(); } public List<Object[]> fetchColumnWithScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("studentId", StandardBasicTypes.LONG) .addScalar("name", StandardBasicTypes.STRING) .addScalar("age", StandardBasicTypes.INTEGER) .list(); } public List<String> fetchLimitedColumnWithScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("name", StandardBasicTypes.STRING)
.list(); } public List<Object[]> fetchColumnWithOverloadedScalar() { return session.createNativeQuery("SELECT * FROM Student student") .addScalar("name", StandardBasicTypes.STRING) .addScalar("age") .list(); } public Double fetchAvgAgeWithScalar() { return (Double) session.createNativeQuery("SELECT AVG(age) as avgAge FROM Student student") .addScalar("avgAge") .uniqueResult(); } }
repos\tutorials-master\persistence-modules\hibernate-queries-2\src\main\java\com\baeldung\hibernate\scalarmethod\HibernateScalarExample.java
1
请完成以下Java代码
private MimeMessage createMimeMsg(String email, String text, String attachmentClassPath) throws MessagingException, UnsupportedEncodingException { MimeMessage msg = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg, true); mimeMessageHelper.setFrom(mailProperties.getFrom(), mailProperties.getPersonal()); mimeMessageHelper.setTo(email); mimeMessageHelper.setBcc(mailProperties.getBcc()); mimeMessageHelper.setSubject(mailProperties.getSubject()); mimeMessageHelper.setText(text); mimeMessageHelper.addAttachment("附件", new ClassPathResource(attachmentClassPath)); return msg; } /** * 创建简单邮件
* @param email * @param text * @return */ private SimpleMailMessage createSimpleMsg(String email, String text) { SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom(mailProperties.getFrom()); msg.setTo(email); msg.setBcc(mailProperties.getBcc()); msg.setSubject(mailProperties.getSubject()); msg.setText(text); return msg; } }
repos\spring-boot-best-practice-master\spring-boot-mail\src\main\java\cn\javastack\springboot\mail\EmailController.java
1
请完成以下Java代码
public String toString() { return "Catalog [id=" + id + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.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; Publisher other = (Publisher) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Publisher.java
1
请完成以下Java代码
public String getInterfaceDesc() { return interfaceDesc; } public void setInterfaceDesc(String interfaceDesc) { this.interfaceDesc = interfaceDesc; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getBillDay() { return billDay; } public void setBillDay(int billDay) { this.billDay = billDay; } public static List<ReconciliationInterface> getInterface() { List<ReconciliationInterface> list = new ArrayList<ReconciliationInterface>(); // 微信支付 ReconciliationInterface weixin = new ReconciliationInterface();
weixin.setInterfaceCode(PayWayEnum.WEIXIN.name()); weixin.setInterfaceName(PayWayEnum.WEIXIN.getDesc()); weixin.setStatus(PublicStatusEnum.ACTIVE.name()); weixin.setBillDay(1); list.add(weixin); // 支付宝 ReconciliationInterface alipay = new ReconciliationInterface(); alipay.setInterfaceCode(PayWayEnum.ALIPAY.name()); alipay.setInterfaceName(PayWayEnum.ALIPAY.getDesc()); alipay.setStatus(PublicStatusEnum.ACTIVE.name()); alipay.setBillDay(1); list.add(alipay); return list; } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\ReconciliationInterface.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultCacheCleanupService implements CacheCleanupService { private final CacheManager cacheManager; private final Optional<RedisTemplate<String, Object>> redisTemplate; /** * Cleanup caches that can not deserialize anymore due to schema upgrade or data update using sql scripts. * Refer to SqlDatabaseUpgradeService and /data/upgrage/*.sql * to discover which tables were changed * */ @Override public void clearCache() throws Exception { log.info("Clearing cache to upgrade."); clearAll(); } void clearAllCaches() { cacheManager.getCacheNames().forEach(this::clearCacheByName); } void clearCacheByName(final String cacheName) { log.info("Clearing cache [{}]", cacheName);
Cache cache = cacheManager.getCache(cacheName); Objects.requireNonNull(cache, "Cache does not exist for name " + cacheName); cache.clear(); } void clearAll() { if (redisTemplate.isPresent()) { log.info("Flushing all caches"); redisTemplate.get().execute((RedisCallback<Object>) connection -> { connection.serverCommands().flushAll(); return null; }); return; } cacheManager.getCacheNames().forEach(this::clearCacheByName); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\update\DefaultCacheCleanupService.java
2
请完成以下Java代码
public int size() { return this.session.getAttributeNames().size(); } @Override public boolean isEmpty() { return this.session.getAttributeNames().isEmpty(); } @Override public boolean containsKey(Object key) { return key instanceof String && this.session.getAttributeNames().contains(key); } @Override public boolean containsValue(Object value) { return this.session.getAttributeNames() .stream() .anyMatch((attrName) -> this.session.getAttribute(attrName) != null); } @Override @Nullable public Object get(Object key) { if (key instanceof String) { return this.session.getAttribute((String) key); } return null; } @Override public Object put(String key, Object value) { Object original = this.session.getAttribute(key); this.session.setAttribute(key, value); return original; } @Override @Nullable public Object remove(Object key) { if (key instanceof String) { String attrName = (String) key; Object original = this.session.getAttribute(attrName); this.session.removeAttribute(attrName); return original; } return null; } @Override public void putAll(Map<? extends String, ?> m) { for (Entry<? extends String, ?> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { for (String attrName : this.session.getAttributeNames()) { remove(attrName); } } @Override public Set<String> keySet() { return this.session.getAttributeNames(); } @Override
public Collection<Object> values() { return this.values; } @Override public Set<Entry<String, Object>> entrySet() { Set<String> attrNames = keySet(); Set<Entry<String, Object>> entries = new HashSet<>(attrNames.size()); for (String attrName : attrNames) { Object value = this.session.getAttribute(attrName); entries.add(new AbstractMap.SimpleEntry<>(attrName, value)); } return Collections.unmodifiableSet(entries); } private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator(); @Override public boolean hasNext() { return this.i.hasNext(); } @Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove(); } }; } @Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请完成以下Java代码
public void setM_Picking_Job_Step(final de.metas.handlingunits.model.I_M_Picking_Job_Step M_Picking_Job_Step) { set_ValueFromPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class, M_Picking_Job_Step); } @Override public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID) { if (M_Picking_Job_Step_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_Step_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID); } @Override public int getM_Picking_Job_Step_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID); } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; }
@Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java
1
请完成以下Java代码
public class ManufacturingOrderExportAudit { @Getter private final APITransactionId transactionId; private final HashMap<PPOrderId, ManufacturingOrderExportAuditItem> items; @Builder private ManufacturingOrderExportAudit( @NonNull final APITransactionId transactionId, @NonNull @Singular List<ManufacturingOrderExportAuditItem> items) { this.transactionId = transactionId; this.items = items.stream() .collect(GuavaCollectors.toHashMapByKeyFailOnDuplicates(ManufacturingOrderExportAuditItem::getOrderId)); } public ImmutableList<ManufacturingOrderExportAuditItem> getItems() { return ImmutableList.copyOf(items.values()); } public ImmutableMap<PPOrderId, APIExportStatus> getExportStatusesByOrderId() { return items.values() .stream() .collect(ImmutableMap.toImmutableMap( item -> item.getOrderId(),
item -> item.getExportStatus())); } public ManufacturingOrderExportAuditItem computeItemIfAbsent( @NonNull final PPOrderId orderId, @NonNull final Function<PPOrderId, ManufacturingOrderExportAuditItem> mappingFunction) { return items.computeIfAbsent(orderId, mappingFunction); } @Nullable public ManufacturingOrderExportAuditItem getByOrderId(@NonNull final PPOrderId orderId) { return items.get(orderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\exportaudit\ManufacturingOrderExportAudit.java
1
请完成以下Java代码
protected void updateAuthorizationBasedOnCacheEntries(AuthorizationEntity authorization, String userId, String groupId, Resource resource, String resourceId) { DbEntityManager dbManager = Context.getCommandContext().getDbEntityManager(); List<AuthorizationEntity> list = dbManager.getCachedEntitiesByType(AuthorizationEntity.class); for (AuthorizationEntity authEntity : list) { boolean hasSameAuthRights = hasEntitySameAuthorizationRights(authEntity, userId, groupId, resource, resourceId); if (hasSameAuthRights) { int previousPermissions = authEntity.getPermissions(); authorization.setPermissions(previousPermissions); dbManager.getDbEntityCache().remove(authEntity); return; } } } protected boolean hasEntitySameAuthorizationRights(AuthorizationEntity authEntity, String userId, String groupId, Resource resource, String resourceId) { boolean sameUserId = areIdsEqual(authEntity.getUserId(), userId);
boolean sameGroupId = areIdsEqual(authEntity.getGroupId(), groupId); boolean sameResourceId = areIdsEqual(authEntity.getResourceId(), (resourceId)); boolean sameResourceType = authEntity.getResourceType() == resource.resourceType(); boolean sameAuthorizationType = authEntity.getAuthorizationType() == AUTH_TYPE_GRANT; return sameUserId && sameGroupId && sameResourceType && sameResourceId && sameAuthorizationType; } protected boolean areIdsEqual(String firstId, String secondId) { if (firstId == null || secondId == null) { return firstId == secondId; }else { return firstId.equals(secondId); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\auth\DefaultAuthorizationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, String> getInit() { return this.init; } public void setInit(Map<String, String> init) { this.init = init; } public @Nullable String getApplicationPath() { return this.applicationPath; } public void setApplicationPath(@Nullable String applicationPath) { this.applicationPath = applicationPath; } public enum Type { SERVLET, FILTER } public static class Filter { /** * Jersey filter chain order. */ private int order; public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } }
public static class Servlet { /** * Load on startup priority of the Jersey servlet. */ private int loadOnStartup = -1; public int getLoadOnStartup() { return this.loadOnStartup; } public void setLoadOnStartup(int loadOnStartup) { this.loadOnStartup = loadOnStartup; } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\JerseyProperties.java
2
请完成以下Java代码
public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Buchführungs-Schema. @return Stammdaten für Buchhaltung */ @Override public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Buchungsdatum. @param DateAcct Accounting Date */ @Override public void setDateAcct (java.sql.Timestamp DateAcct) { set_ValueNoCheck (COLUMNNAME_DateAcct, DateAcct); } /** Get Buchungsdatum. @return Accounting Date */ @Override public java.sql.Timestamp getDateAcct () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Accounting Fact. @param Fact_Acct_ID Accounting Fact */ @Override public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ @Override public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue();
} /** * PostingType AD_Reference_ID=125 * Reference name: _Posting Type */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Actual Year End = Y */ public static final String POSTINGTYPE_ActualYearEnd = "Y"; /** Set Buchungsart. @param PostingType Die Art des gebuchten Betrages dieser Transaktion */ @Override public void setPostingType (java.lang.String PostingType) { set_ValueNoCheck (COLUMNNAME_PostingType, PostingType); } /** Get Buchungsart. @return Die Art des gebuchten Betrages dieser Transaktion */ @Override public java.lang.String getPostingType () { return (java.lang.String)get_Value(COLUMNNAME_PostingType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_EndingBalance.java
1
请在Spring Boot框架中完成以下Java代码
private BPUpsertCamelRequest getBPUpsertCamelRequest(@NonNull final JsonVendor jsonVendor) { final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials(); final JsonRequestBPartner jsonRequestBPartner = new JsonRequestBPartner(); jsonRequestBPartner.setName(jsonVendor.getName()); jsonRequestBPartner.setCompanyName(jsonVendor.getName()); jsonRequestBPartner.setActive(jsonVendor.isActive()); jsonRequestBPartner.setVendor(true); jsonRequestBPartner.setCode(jsonVendor.getBpartnerValue()); final JsonRequestComposite jsonRequestComposite = JsonRequestComposite.builder() .orgCode(credentials.getOrgCode()) .bpartner(jsonRequestBPartner) .build(); final JsonRequestBPartnerUpsertItem jsonRequestBPartnerUpsertItem = JsonRequestBPartnerUpsertItem.builder() .bpartnerIdentifier(computeBPartnerIdentifier(jsonVendor)) .bpartnerComposite(jsonRequestComposite) .build(); final JsonRequestBPartnerUpsert jsonRequestBPartnerUpsert = JsonRequestBPartnerUpsert.builder() .requestItem(jsonRequestBPartnerUpsertItem) .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .build(); return BPUpsertCamelRequest.builder() .jsonRequestBPartnerUpsert(jsonRequestBPartnerUpsert)
.orgCode(credentials.getOrgCode()) .build(); } @NonNull private static String computeBPartnerIdentifier(@NonNull final JsonVendor jsonVendor) { if (jsonVendor.getMetasfreshId() != null && Check.isNotBlank(jsonVendor.getMetasfreshId())) { return jsonVendor.getMetasfreshId(); } throw new RuntimeException("Missing mandatory METASFRESHID! JsonVendor.MKREDID: " + jsonVendor.getBpartnerValue()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\vendor\processor\PushBPartnersProcessor.java
2
请完成以下Java代码
private void invalidateCache() { _adLanguageEffective = null; _text2parsedText.clear(); } public MailTextBuilder record(final Object record) { _record = record; invalidateCache(); return this; } public MailTextBuilder recordAndUpdateBPartnerAndContact(final Object record) { record(record); if (record != null) { updateBPartnerAndContactFromRecord(record); } return this; } private void updateBPartnerAndContactFromRecord(@NonNull final Object record) { final BPartnerId bpartnerId = extractBPartnerId(record); if (bpartnerId != null) { bpartner(bpartnerId); } final UserId bpartnerContactId = extractBPartnerContactId(record); if (bpartnerContactId != null) { bpartnerContact(bpartnerContactId); } } private BPartnerId extractBPartnerId(final Object record) {
final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID"); if (!(bpartnerIdObj instanceof Integer)) { return null; } final int bpartnerRepoId = (Integer)bpartnerIdObj; return BPartnerId.ofRepoIdOrNull(bpartnerRepoId); } private UserId extractBPartnerContactId(final Object record) { final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID"); if (!(userIdObj instanceof Integer)) { return null; } final int userRepoId = userIdObj.intValue(); return UserId.ofRepoIdOrNull(userRepoId); } private Object getRecord() { return _record; } public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value) { return customVariable(name, TranslatableStrings.anyLanguage(value)); } public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value) { _customVariables.put(name, value); invalidateCache(); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isVerificationCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.VERIFICATION); } /** * Indicate whether this credential can be used for encryption * @return true if the credential has a {@link Saml2X509CredentialType#ENCRYPTION} * type */ public boolean isEncryptionCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.ENCRYPTION); } /** * List all this credential's intended usages * @return the set of this credential's intended usages */ public Set<Saml2X509CredentialType> getCredentialTypes() { return this.credentialTypes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Saml2X509Credential that = (Saml2X509Credential) o; return Objects.equals(this.privateKey, that.privateKey) && this.certificate.equals(that.certificate) && this.credentialTypes.equals(that.credentialTypes); } @Override public int hashCode() { return Objects.hash(this.privateKey, this.certificate, this.credentialTypes);
} private void validateUsages(Saml2X509CredentialType[] usages, Saml2X509CredentialType... validUsages) { for (Saml2X509CredentialType usage : usages) { boolean valid = false; for (Saml2X509CredentialType validUsage : validUsages) { if (usage == validUsage) { valid = true; break; } } Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } public enum Saml2X509CredentialType { VERIFICATION, ENCRYPTION, SIGNING, DECRYPTION, } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2X509Credential.java
2
请完成以下Java代码
public class CalloutRMA extends CalloutEngine { /** * docType - set document properties based on document type. * @param ctx * @param WindowNo * @param mTab * @param mField * @param value * @return error message or "" */ public String docType (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) { Integer C_DocType_ID = (Integer)value;
if (C_DocType_ID == null || C_DocType_ID.intValue() == 0) return ""; String sql = "SELECT d.IsSoTrx " + "FROM C_DocType d WHERE C_DocType_ID=?"; String docSOTrx = DB.getSQLValueString(null, sql, C_DocType_ID); boolean isSOTrx = "Y".equals(docSOTrx); mTab.setValue("IsSOTrx", isSOTrx); return ""; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\CalloutRMA.java
1
请完成以下Java代码
public class ConnectionPoolMetrics implements MeterBinder { private static final String CONNECTIONS = "connections"; private final ConnectionPool pool; private final Iterable<Tag> tags; public ConnectionPoolMetrics(ConnectionPool pool, String name, Iterable<Tag> tags) { this.pool = pool; this.tags = Tags.concat(tags, "name", name); } @Override public void bindTo(MeterRegistry registry) { this.pool.getMetrics().ifPresent((poolMetrics) -> { bindConnectionPoolMetric(registry, Gauge.builder(metricKey("acquired"), poolMetrics, PoolMetrics::acquiredSize) .description("Size of successfully acquired connections which are in active use.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("allocated"), poolMetrics, PoolMetrics::allocatedSize) .description("Size of allocated connections in the pool which are in active use or idle.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("idle"), poolMetrics, PoolMetrics::idleSize) .description("Size of idle connections in the pool.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("pending"), poolMetrics, PoolMetrics::pendingAcquireSize)
.description("Size of pending to acquire connections from the underlying connection factory.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.allocated"), poolMetrics, PoolMetrics::getMaxAllocatedSize) .description("Maximum size of allocated connections that this pool allows.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.pending"), poolMetrics, PoolMetrics::getMaxPendingAcquireSize) .description("Maximum size of pending state to acquire connections that this pool allows.")); }); } private void bindConnectionPoolMetric(MeterRegistry registry, Builder<?> builder) { builder.tags(this.tags).baseUnit(CONNECTIONS).register(registry); } private static String metricKey(String name) { return "r2dbc.pool." + name; } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\metrics\ConnectionPoolMetrics.java
1
请完成以下Java代码
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { RepetitionRule repetitionRule = ExpressionUtil.getRepetitionRule(planItemInstanceEntity); if (repetitionRule != null && ExpressionUtil.evaluateRepetitionRule(commandContext, planItemInstanceEntity, planItemInstanceEntity.getStagePlanItemInstanceEntity())) { PlanItemInstanceEntity eventPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, false, false); CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext); agenda.planCreatePlanItemInstanceWithoutEvaluationOperation(eventPlanItemInstanceEntity); agenda.planOccurPlanItemInstanceOperation(eventPlanItemInstanceEntity); CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper().executeLifecycleListeners( commandContext, planItemInstanceEntity, PlanItemInstanceState.ACTIVE, PlanItemInstanceState.AVAILABLE); } else { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); EventSubscriptionService eventSubscriptionService = cmmnEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService(); String signalName = null; if (StringUtils.isNotEmpty(signalRef)) { Expression signalExpression = CommandContextUtil.getCmmnEngineConfiguration(commandContext) .getExpressionManager().createExpression(signalRef);
signalName = signalExpression.getValue(planItemInstanceEntity).toString(); } List<EventSubscriptionEntity> eventSubscriptions = eventSubscriptionService.findEventSubscriptionsBySubScopeId(planItemInstanceEntity.getId()); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if (eventSubscription instanceof SignalEventSubscriptionEntity && eventSubscription.getEventName().equals(signalName)) { eventSubscriptionService.deleteEventSubscription(eventSubscription); } } CommandContextUtil.getAgenda(commandContext).planOccurPlanItemInstanceOperation(planItemInstanceEntity); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\SignalEventListenerActivityBehaviour.java
1
请完成以下Java代码
public String get_ValueAsString(final String variableName) { if (excludeVariableName.equals(variableName)) { return null; } return parent.get_ValueAsString(variableName); } @Override public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType) { if (excludeVariableName.equals(variableName)) { return Optional.empty(); } return parent.get_ValueIfExists(variableName, targetType); } } @ToString private static class RangeAwareParamsAsEvaluatee implements Evaluatee2 { private final IRangeAwareParams params; private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params) { this.params = params; } @Override public boolean has_Variable(final String variableName) { return params.hasParameter(variableName); } @SuppressWarnings("unchecked") @Override public <T> T get_ValueAsObject(final String variableName) { return (T)params.getParameterAsObject(variableName); } @Override public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue) { final BigDecimal value = params.getParameterAsBigDecimal(variableName); return value != null ? value : defaultValue; } @Override public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED) { return params.getParameterAsBool(variableName); } @Override
public Date get_ValueAsDate(final String variableName, final Date defaultValue) { final Timestamp value = params.getParameterAsTimestamp(variableName); return value != null ? value : defaultValue; } @Override public Integer get_ValueAsInt(final String variableName, final Integer defaultValue) { final int defaultValueInt = defaultValue != null ? defaultValue : 0; return params.getParameterAsInt(variableName, defaultValueInt); } @Override public String get_ValueAsString(final String variableName) { return params.getParameterAsString(variableName); } @Override public String get_ValueOldAsString(final String variableName) { return get_ValueAsString(variableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java
1
请完成以下Java代码
public SimpleAsyncTaskExecutor build() { return configure(new SimpleAsyncTaskExecutor()); } /** * Build a new {@link SimpleAsyncTaskExecutor} instance of the specified type and * configure it using this builder. * @param <T> the type of task executor * @param taskExecutorClass the template type to create * @return a configured {@link SimpleAsyncTaskExecutor} instance. * @see #build() * @see #configure(SimpleAsyncTaskExecutor) */ public <T extends SimpleAsyncTaskExecutor> T build(Class<T> taskExecutorClass) { return configure(BeanUtils.instantiateClass(taskExecutorClass)); } /** * Configure the provided {@link SimpleAsyncTaskExecutor} instance using this builder. * @param <T> the type of task executor * @param taskExecutor the {@link SimpleAsyncTaskExecutor} to configure * @return the task executor instance * @see #build() * @see #build(Class)
*/ public <T extends SimpleAsyncTaskExecutor> T configure(T taskExecutor) { PropertyMapper map = PropertyMapper.get(); map.from(this.virtualThreads).to(taskExecutor::setVirtualThreads); map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix); map.from(this.cancelRemainingTasksOnClose).to(taskExecutor::setCancelRemainingTasksOnClose); map.from(this.rejectTasksWhenLimitReached).to(taskExecutor::setRejectTasksWhenLimitReached); map.from(this.concurrencyLimit).to(taskExecutor::setConcurrencyLimit); map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator); map.from(this.taskTerminationTimeout).as(Duration::toMillis).to(taskExecutor::setTaskTerminationTimeout); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskExecutor)); } return taskExecutor; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\SimpleAsyncTaskExecutorBuilder.java
1
请完成以下Java代码
public Iterator<Object> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } /** @return empty result */ @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { return InvoiceCandidateGenerateResult.of(this); } /** Does nothing */ @Override public void invalidateCandidatesFor(final Object model) { // nothing to do } /** * @return {@link #MANUAL} (i.e. not a real table name). */ @Override public String getSourceTable() { return ManualCandidateHandler.MANUAL; } /** @return {@code true}. */ @Override public boolean isUserInChargeUserEditable() { return true; } /** * Does nothing. */ @Override
public void setOrderedData(final I_C_Invoice_Candidate ic) { // nothing to do } /** * Does nothing. */ @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { // nothing to do } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { // nothing to do } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\ManualCandidateHandler.java
1
请完成以下Java代码
public static boolean executesNonScopeCompensationHandler(PvmExecutionImpl execution) { ActivityImpl activity = execution.getActivity(); return execution.isScope() && activity != null && activity.isCompensationHandler() && !activity.isScope(); } public static boolean isCompensationThrowing(PvmExecutionImpl execution) { ActivityImpl currentActivity = execution.getActivity(); if (currentActivity != null) { Boolean isCompensationThrowing = (Boolean) currentActivity.getProperty(BpmnParse.PROPERTYNAME_THROWS_COMPENSATION); if (isCompensationThrowing != null && isCompensationThrowing) { return true; } } return false; } /** * Determines whether an execution is responsible for default compensation handling. * * This is the case if * <ul> * <li>the execution has an activity * <li>the execution is a scope * <li>the activity is a scope * <li>the execution has children * <li>the execution does not throw compensation * </ul>
*/ public static boolean executesDefaultCompensationHandler(PvmExecutionImpl scopeExecution) { ActivityImpl currentActivity = scopeExecution.getActivity(); if (currentActivity != null) { return scopeExecution.isScope() && currentActivity.isScope() && !scopeExecution.getNonEventScopeExecutions().isEmpty() && !isCompensationThrowing(scopeExecution); } else { return false; } } public static String getParentActivityInstanceId(PvmExecutionImpl execution) { Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping = execution.createActivityExecutionMapping(); PvmExecutionImpl parentScopeExecution = activityExecutionMapping.get(execution.getActivity().getFlowScope()); return parentScopeExecution.getParentActivityInstanceId(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\CompensationBehavior.java
1
请完成以下Java代码
static void validate (int AD_Table_ID) { MTable table = new MTable(Env.getCtx(), AD_Table_ID, null); if (table.isView()) { log.warn("Ignored - View " + table.getTableName()); } else { validate (table.getAD_Table_ID(), table.getTableName()); } } // validate /** * Validate Table for Table/Record * @param AD_Table_ID table * @param TableName Name */ static private void validate (int AD_Table_ID, String TableName) {
for (int i = 0; i < s_cascades.length; i++) { final StringBuilder sql = new StringBuilder("DELETE FROM ") .append(s_cascadeNames[i]) .append(" WHERE AD_Table_ID=").append(AD_Table_ID) .append(" AND Record_ID NOT IN (SELECT ") .append(TableName).append("_ID FROM ").append(TableName).append(")"); int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), null); if (no > 0) { log.info(s_cascadeNames[i] + " (" + AD_Table_ID + "/" + TableName + ") Invalid #" + no); } } } // validate } // PO_Record
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO_Record.java
1
请完成以下Java代码
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) { if (isInFuture(yearOfBirth)) { return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); } return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); } private int calculateAge(int yearOfBirth) { return currentYear() - yearOfBirth; } private boolean isInFuture(int year) { return currentYear() < year; } private int currentYear() { return Year.now().getValue(); }
@GetMapping("/customHeader") public ResponseEntity<String> customHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "foo"); return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); } @GetMapping("/manual") public void manual(HttpServletResponse response) throws IOException { response.setHeader("Custom-Header", "foo"); response.setStatus(200); response.getWriter() .println("Hello World!"); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\responseentity\CustomResponseController.java
1
请在Spring Boot框架中完成以下Java代码
public PooledConnectionFactory pooledConnectionFactory(@Qualifier("targetConnectionFactory") ActiveMQConnectionFactory activeMQConnectionFactory) { PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(); pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory); pooledConnectionFactory.setMaxConnections(maxConnections); return pooledConnectionFactory; } /** * 商户通知队列模板 * * @param singleConnectionFactory 连接工厂 * @return 商户通知队列模板 */ @Bean(name = "notifyJmsTemplate") public JmsTemplate notifyJmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory);
notifyJmsTemplate.setDefaultDestinationName(tradeQueueDestinationName); return notifyJmsTemplate; } /** * 队列模板 * * @param singleConnectionFactory 连接工厂 * @return 队列模板 */ @Bean(name = "jmsTemplate") public JmsTemplate jmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory); notifyJmsTemplate.setDefaultDestinationName(orderQueryDestinationName); return notifyJmsTemplate; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\config\ActiveMqConfig.java
2
请完成以下Java代码
public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProductNo (final @Nullable java.lang.String ProductNo) { set_Value (COLUMNNAME_ProductNo, ProductNo);
} @Override public java.lang.String getProductNo() { return get_ValueAsString(COLUMNNAME_ProductNo); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Product_v.java
1
请完成以下Java代码
public List<? extends ServletContextInitializer> getInitializers() { return this.initializers; } public void setJsp(Jsp jsp) { this.jsp = jsp; } public Jsp getJsp() { return this.jsp; } public Map<Locale, Charset> getLocaleCharsetMappings() { return this.localeCharsetMappings; } public Map<String, String> getInitParameters() { return this.initParameters; } public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() { return this.cookieSameSiteSuppliers; } public void setMimeMappings(MimeMappings mimeMappings) { Assert.notNull(mimeMappings, "'mimeMappings' must not be null"); this.mimeMappings = new MimeMappings(mimeMappings); } public void addMimeMappings(MimeMappings mimeMappings) { mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType())); } public void setInitializers(List<? extends ServletContextInitializer> initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers = new ArrayList<>(initializers); } public void addInitializers(ServletContextInitializer... initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers.addAll(Arrays.asList(initializers)); } public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null");
this.localeCharsetMappings = localeCharsetMappings; } public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers); } public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers)); } public void addWebListenerClassNames(String... webListenerClassNames) { this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames)); } public Set<String> getWebListenerClassNames() { return this.webListenerClassNames; } public List<URL> getStaticResourceUrls() { return this.staticResourceJars.getUrls(); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
1
请完成以下Java代码
public int getDATEV_ExportFormatColumn_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DATEV_ExportFormatColumn_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Format Pattern. @param FormatPattern The pattern used to format a number or date. */ @Override public void setFormatPattern (java.lang.String FormatPattern) { set_Value (COLUMNNAME_FormatPattern, FormatPattern); } /** Get Format Pattern. @return The pattern used to format a number or date. */ @Override public java.lang.String getFormatPattern () { return (java.lang.String)get_Value(COLUMNNAME_FormatPattern); } /** 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); } /** 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.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormatColumn.java
1
请在Spring Boot框架中完成以下Java代码
public void customize(FluentConfiguration configuration) { Extension<PostgreSQLConfigurationExtension> extension = new Extension<>(configuration, PostgreSQLConfigurationExtension.class, "PostgreSQL"); Postgresql properties = this.properties.getPostgresql(); PropertyMapper map = PropertyMapper.get(); map.from(properties::getTransactionalLock) .to(extension.via((ext, transactionalLock) -> ext.setTransactionalLock(transactionalLock))); } } @Order(Ordered.HIGHEST_PRECEDENCE) static final class SqlServerFlywayConfigurationCustomizer implements FlywayConfigurationCustomizer { private final FlywayProperties properties; SqlServerFlywayConfigurationCustomizer(FlywayProperties properties) { this.properties = properties; } @Override public void customize(FluentConfiguration configuration) { Extension<SQLServerConfigurationExtension> extension = new Extension<>(configuration, SQLServerConfigurationExtension.class, "SQL Server"); Sqlserver properties = this.properties.getSqlserver(); PropertyMapper map = PropertyMapper.get(); map.from(properties::getKerberosLoginFile).to(extension.via(this::setKerberosLoginFile)); } private void setKerberosLoginFile(SQLServerConfigurationExtension configuration, String file) { configuration.getKerberos().getLogin().setFile(file); } }
/** * Helper class used to map properties to a {@link ConfigurationExtension}. * * @param <E> the extension type */ static class Extension<E extends ConfigurationExtension> { private final Supplier<E> extension; Extension(FluentConfiguration configuration, Class<E> type, String name) { this.extension = SingletonSupplier.of(() -> { E extension = configuration.getPluginRegister().getExact(type); Assert.state(extension != null, () -> "Flyway %s extension missing".formatted(name)); return extension; }); } <T> Consumer<T> via(BiConsumer<E, T> action) { return (value) -> action.accept(this.extension.get(), value); } } }
repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\FlywayAutoConfiguration.java
2
请完成以下Java代码
public Iterator<ExitCodeGenerator> iterator() { return this.generators.iterator(); } /** * Get the final exit code that should be returned. The final exit code is the first * non-zero exit code that is {@link ExitCodeGenerator#getExitCode generated}. * @return the final exit code. */ int getExitCode() { int exitCode = 0; for (ExitCodeGenerator generator : this.generators) { try { int value = generator.getExitCode(); if (value != 0) { exitCode = value; break; } } catch (Exception ex) { exitCode = 1; ex.printStackTrace(); } } return exitCode; } /** * Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}. */ private static class MappedExitCodeGenerator implements ExitCodeGenerator { private final Throwable exception;
private final ExitCodeExceptionMapper mapper; MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) { this.exception = exception; this.mapper = mapper; } @Override public int getExitCode() { return this.mapper.getExitCode(this.exception); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ExitCodeGenerators.java
1
请在Spring Boot框架中完成以下Java代码
private MetadataResolver initialize(ResourceBackedMetadataResolver metadataResolver) { metadataResolver.setParserPool(XMLObjectProviderRegistrySupport.getParserPool()); return BaseOpenSamlAssertingPartyMetadataRepository.initialize(metadataResolver); } private static final class SpringResource implements net.shibboleth.shared.resource.Resource { private final Resource resource; SpringResource(Resource resource) { this.resource = resource; } @Override public boolean exists() { return this.resource.exists(); } @Override public boolean isReadable() { return this.resource.isReadable(); } @Override public boolean isOpen() { return this.resource.isOpen(); } @Override public URL getURL() throws IOException { return this.resource.getURL(); } @Override public URI getURI() throws IOException { return this.resource.getURI(); } @Override public File getFile() throws IOException { return this.resource.getFile(); } @NonNull @Override public InputStream getInputStream() throws IOException { return this.resource.getInputStream(); } @Override public long contentLength() throws IOException { return this.resource.contentLength(); } @Override public long lastModified() throws IOException { return this.resource.lastModified(); } @Override public net.shibboleth.shared.resource.Resource createRelativeResource(String relativePath) throws IOException { return new SpringResource(this.resource.createRelative(relativePath)); } @Override public String getFilename() {
return this.resource.getFilename(); } @Override public String getDescription() { return this.resource.getDescription(); } } } private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { CriteriaSetResolverWrapper(MetadataResolver metadataResolver) { super(metadataResolver); } @Override EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); } @Override Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception { return super.metadataResolver.resolve(new CriteriaSet(role)); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
2
请在Spring Boot框架中完成以下Java代码
public static class DirectExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo07Queue() { return QueueBuilder.durable(Demo07Message.QUEUE) // durable: 是否持久化 .exclusive() // exclusive: 是否排它 .autoDelete() // autoDelete: 是否自动删除 .deadLetterExchange(Demo07Message.EXCHANGE) .deadLetterRoutingKey(Demo07Message.DEAD_ROUTING_KEY) .build(); } // 创建 Dead Queue @Bean public Queue demo07DeadQueue() { return new Queue(Demo07Message.DEAD_QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Direct Exchange @Bean public DirectExchange demo07Exchange() { return new DirectExchange(Demo07Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding
// Exchange:Demo07Message.EXCHANGE // Routing key:Demo07Message.ROUTING_KEY // Queue:Demo07Message.QUEUE @Bean public Binding demo07Binding() { return BindingBuilder.bind(demo07Queue()).to(demo07Exchange()).with(Demo07Message.ROUTING_KEY); } // 创建 Dead Binding // Exchange:Demo07Message.EXCHANGE // Routing key:Demo07Message.DEAD_ROUTING_KEY // Queue:Demo07Message.DEAD_QUEUE @Bean public Binding demo07DeadBinding() { return BindingBuilder.bind(demo07DeadQueue()).to(demo07Exchange()).with(Demo07Message.DEAD_ROUTING_KEY); } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-consume-retry\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public boolean supportsParameter(MethodParameter parameter) { Class<?> type = getTargetType(parameter); return (type.isInterface() && AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null); } private static Class<?> getTargetType(MethodParameter parameter) { Class<?> type = parameter.getParameterType(); return (type.equals(Optional.class) || type.equals(ArgumentValue.class)) ? parameter.nested().getNestedParameterType() : parameter.getParameterType(); } @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { String name = (parameter.hasParameterAnnotation(Argument.class) ? ArgumentMethodArgumentResolver.getArgumentName(parameter) : null); Class<?> targetType = parameter.getParameterType(); boolean isOptional = (targetType == Optional.class); boolean isArgumentValue = (targetType == ArgumentValue.class); if (isOptional || isArgumentValue) { targetType = parameter.nested().getNestedParameterType(); } Map<String, Object> arguments = environment.getArguments(); Object rawValue = (name != null) ? arguments.get(name) : arguments; Object value = (rawValue != null) ? createProjection(targetType, rawValue) : null; if (isOptional) { return Optional.ofNullable(value); } else if (isArgumentValue) { return (name != null && arguments.containsKey(name)) ?
ArgumentValue.ofNullable(value) : ArgumentValue.omitted(); } else { return value; } } /** * Protected method to create the projection. The default implementation * delegates to the underlying {@link #getProjectionFactory() projectionFactory}. * @param targetType the type to create * @param rawValue a specific argument (if named via {@link Argument} * or the map of arguments * @return the created project instance */ protected Object createProjection(Class<?> targetType, Object rawValue) { return this.projectionFactory.createProjection(targetType, rawValue); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\ProjectedPayloadMethodArgumentResolver.java
1
请完成以下Java代码
public String getNamespaceURI(String arg0) { if ("bdn".equals(arg0)) { return "http://www.baeldung.com/full_archive"; } return null; } }); String expression = "/bdn:tutorials/bdn:tutorial"; nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); } catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) { e.printStackTrace(); } return nodeList; } private void clean(Node node) { NodeList childNodes = node.getChildNodes(); for (int n = childNodes.getLength() - 1; n >= 0; n--) { Node child = childNodes.item(n); short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE)
clean(child); else if (nodeType == Node.TEXT_NODE) { String trimmedNodeVal = child.getNodeValue().trim(); if (trimmedNodeVal.length() == 0) node.removeChild(child); else child.setNodeValue(trimmedNodeVal); } else if (nodeType == Node.COMMENT_NODE) node.removeChild(child); } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\DefaultParser.java
1
请完成以下Spring Boot application配置
server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/oauth?allowPublicKeyRetrieval=true username: root password: 123456 hikari: data-source-properties: useSSL: false serverTimezone: GMT+8 useUnicode: true characterEncoding
: utf8 jpa: hibernate: ddl-auto: update show-sql: true logging: level: org.springframework.security: debug
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\resources\application.yml
2
请完成以下Java代码
public AcquireJobsCommandFactory getAcquireJobsCmdFactory() { return acquireJobsCmdFactory; } public void setAcquireJobsCmdFactory(AcquireJobsCommandFactory acquireJobsCmdFactory) { this.acquireJobsCmdFactory = acquireJobsCmdFactory; } public boolean isActive() { return isActive; } public RejectedJobsHandler getRejectedJobsHandler() { return rejectedJobsHandler; } public void setRejectedJobsHandler(RejectedJobsHandler rejectedJobsHandler) { this.rejectedJobsHandler = rejectedJobsHandler; } protected void startJobAcquisitionThread() { if (jobAcquisitionThread == null) { jobAcquisitionThread = new Thread(acquireJobsRunnable, getName()); jobAcquisitionThread.start(); } } protected void stopJobAcquisitionThread() { try { jobAcquisitionThread.join(); }
catch (InterruptedException e) { LOG.interruptedWhileShuttingDownjobExecutor(e); } jobAcquisitionThread = null; } public AcquireJobsRunnable getAcquireJobsRunnable() { return acquireJobsRunnable; } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutor.java
1
请完成以下Java代码
public int hashCode() { return new HashcodeBuilder() .append(product) .append(qty) .append(uom) .toHashcode(); }; @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final InvoicingItem other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(product, other.product) .append(qty, other.qty) .append(uom, other.uom) .isEqual(); } @Override
public I_M_Product getM_Product() { return product; } @Override public BigDecimal getQty() { return qty; } @Override public I_C_UOM getC_UOM() { return uom; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicingItem.java
1
请完成以下Java代码
int processLines(String[] lines) { int statusCode = 0; parser: for (String line : lines) { System.out.println("Processing line: " + line); if (line.equals("stop")) { System.out.println("Stopping parsing..."); statusCode = -1; break parser; // Stop parsing and exit the loop } System.out.println("Line processed."); } return statusCode; } void download(String fileUrl, String destinationPath) throws MalformedURLException, URISyntaxException { if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) { return; } // execute downloading
URL url = new URI(fileUrl).toURL(); try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\stopexecution\StopExecutionFurtherCode.java
1
请完成以下Java代码
public JobDto cleanupAsync(boolean immediatelyDue) { Job job = processEngine.getHistoryService().cleanUpHistoryAsync(immediatelyDue); return JobDto.fromJob(job); } public JobDto findCleanupJob() { Job job = processEngine.getHistoryService().findHistoryCleanupJob(); if (job == null) { throw new RestException(Status.NOT_FOUND, "History cleanup job does not exist"); } return JobDto.fromJob(job); } public List<JobDto> findCleanupJobs() { List<Job> jobs = processEngine.getHistoryService().findHistoryCleanupJobs(); if (jobs == null || jobs.isEmpty()) { throw new RestException(Status.NOT_FOUND, "History cleanup jobs are empty"); } List<JobDto> dtos = new ArrayList<JobDto>(); for (Job job : jobs) { JobDto dto = JobDto.fromJob(job); dtos.add(dto); } return dtos; } public HistoryCleanupConfigurationDto getHistoryCleanupConfiguration() { ProcessEngineConfigurationImpl engineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
HistoryCleanupConfigurationDto configurationDto = new HistoryCleanupConfigurationDto(); configurationDto.setEnabled(engineConfiguration.isHistoryCleanupEnabled()); BatchWindow batchWindow = engineConfiguration.getBatchWindowManager() .getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), engineConfiguration); if (batchWindow != null) { configurationDto.setBatchWindowStartTime(batchWindow.getStart()); configurationDto.setBatchWindowEndTime(batchWindow.getEnd()); } return configurationDto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryCleanupRestServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private static final Logger logger = Logger.getLogger(BookstoreService.class.getName()); private final AuthorRepository authorRepository; private final BookRepository bookRepository; private final EntityManager em; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository, EntityManager em) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; this.em = em; } @Transactional public void registerAuthor() { Author a1 = new Author(); a1.setName("Quartis Young"); a1.setGenre("Anthology"); a1.setAge(34); Author a2 = new Author(); a2.setName("Mark Janel"); a2.setGenre("Anthology"); a2.setAge(23); Book b1 = new Book(); b1.setIsbn("001"); b1.setTitle("The Beatles Anthology"); Book b2 = new Book(); b2.setIsbn("002"); b2.setTitle("A People's Anthology"); Book b3 = new Book(); b3.setIsbn("003"); b3.setTitle("Anthology Myths"); a1.addBook(b1); a1.addBook(b2);
a2.addBook(b3); authorRepository.save(a1); authorRepository.save(a2); } @Transactional public void updateAuthor() { Author author = authorRepository.findByName("Mark Janel"); author.setAge(45); } @Transactional public void updateBooks() { Author author = authorRepository.findByName("Quartis Young"); List<Book> books = author.getBooks(); for (Book book : books) { book.setIsbn("not available"); } } @Transactional(readOnly = true) public void queryEntityHistory() { AuditReader reader = AuditReaderFactory.get(em); AuditQuery queryAtRev = reader.createQuery().forEntitiesAtRevision(Book.class, 3); System.out.println("Get all Book instances modified at revision #3:"); System.out.println(queryAtRev.getResultList()); AuditQuery queryOfRevs = reader.createQuery().forRevisionsOfEntity(Book.class, true, true); System.out.println("\nGet all Book instances in all their states that were audited:"); System.out.println(queryOfRevs.getResultList()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootEnvers\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
default String getPrefix() { String result = getPath(); int index = result.indexOf('*'); if (index != -1) { result = result.substring(0, index); } if (result.endsWith("/")) { result = result.substring(0, result.length() - 1); } return result; } /** * Return a URL mapping pattern that can be used with a * {@link ServletRegistrationBean} to map the dispatcher servlet. * @return the path as a servlet URL mapping
*/ default String getServletUrlMapping() { if (getPath().isEmpty() || getPath().equals("/")) { return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\DispatcherServletPath.java
2
请完成以下Java代码
public EventSubscriptionQueryImpl eventName(String eventName) { if (eventName == null) { throw new ActivitiIllegalArgumentException("Provided event name is null"); } this.eventName = eventName; return this; } public EventSubscriptionQueryImpl executionId(String executionId) { if (executionId == null) { throw new ActivitiIllegalArgumentException("Provided execution id is null"); } this.executionId = executionId; return this; } public EventSubscriptionQueryImpl processInstanceId(String processInstanceId) { if (processInstanceId == null) { throw new ActivitiIllegalArgumentException("Provided process instance id is null"); } this.processInstanceId = processInstanceId; return this; } public EventSubscriptionQueryImpl activityId(String activityId) { if (activityId == null) { throw new ActivitiIllegalArgumentException("Provided activity id is null"); } this.activityId = activityId; return this; } public EventSubscriptionQueryImpl eventType(String eventType) { if (eventType == null) { throw new ActivitiIllegalArgumentException("Provided event type is null"); } this.eventType = eventType; return this; } public String getTenantId() { return tenantId; } public EventSubscriptionQueryImpl tenantId(String tenantId) { this.tenantId = tenantId; return this; } public EventSubscriptionQueryImpl configuration(String configuration) { this.configuration = configuration; return this; } public EventSubscriptionQueryImpl orderByCreated() { return orderBy(EventSubscriptionQueryProperty.CREATED); } // results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionCountByQueryCriteria(this); } @Override
public List<EventSubscriptionEntity> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getEventSubscriptionId() { return eventSubscriptionId; } public String getEventName() { return eventName; } public String getEventType() { return eventType; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getActivityId() { return activityId; } public String getConfiguration() { return configuration; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\EventSubscriptionQueryImpl.java
1
请完成以下Java代码
private void setWeight(final AttributeCode weightAttribute, final BigDecimal weight) { final IAttributeStorage attributeStorage = getAttributeStorage(); logger.debug("Setting {} attribute Value={} on {}", weightAttribute, weight, attributeStorage); attributeStorage.setValue(weightAttribute, weight); } /** * Set the given weight directly, avoiding attribute propagation. */ private void setWeightNoPropagate(final AttributeCode weightAttribute, final BigDecimal weight) { final IAttributeStorage attributeStorage = getAttributeStorage(); logger.debug("Setting {} INTERNAL attribute Value={} on {}", weightAttribute, weight, attributeStorage); attributeStorage.setValueNoPropagate(weightAttribute, weight); // directly set the correct value we're expecting } private I_C_UOM getWeightUOM(final AttributeCode weightAttribute) { final IAttributeStorage attributeStorage = getAttributeStorage(); final IAttributeValue attributeValue = attributeStorage.getAttributeValue(weightAttribute); if (attributeValue == null) { return null; } return attributeValue.getC_UOM(); } /** * @return true if has WeightGross attribute */ @Override public boolean hasWeightGross() { final AttributeCode attr_WeightGross = getWeightGrossAttribute(); return hasWeightAttribute(attr_WeightGross); } /** * @return true if has WeightNet attribute */ @Override
public boolean hasWeightNet() { final AttributeCode attr_WeightNet = getWeightNetAttribute(); return hasWeightAttribute(attr_WeightNet); } /** * @return true if has WeightTare attribute */ @Override public boolean hasWeightTare() { final AttributeCode attr_WeightTare = getWeightTareAttribute(); return hasWeightAttribute(attr_WeightTare); } /** * @return true if has WeightTare(adjust) attribute */ @Override public boolean hasWeightTareAdjust() { final AttributeCode attr_WeightTareAdjust = getWeightTareAdjustAttribute(); return hasWeightAttribute(attr_WeightTareAdjust); } /** * @return true if given attribute exists */ private boolean hasWeightAttribute(final AttributeCode weightAttribute) { if (weightAttribute == null) { return false; } final IAttributeStorage attributeStorage = getAttributeStorage(); return attributeStorage.hasAttribute(weightAttribute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\AttributeStorageWeightableWrapper.java
1
请完成以下Java代码
public String getProcessDefinitionKey() { return processDefinitionKey; } public TopicSubscription setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; return this; } public List<String> getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public TopicSubscription setProcessDefinitionKeyIn(List<String> processDefinitionKeys) { this.processDefinitionKeyIn = processDefinitionKeys; return this; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) { this.processDefinitionVersionTag = processDefinitionVersionTag; } public HashMap<String, Object> getProcessVariables() { return (HashMap<String, Object>) processVariables; } public void setProcessVariables(Map<String, Object> processVariables) { if (this.processVariables == null) { this.processVariables = new HashMap<>(); } for (Map.Entry<String, Object> processVariable : processVariables.entrySet()) { this.processVariables.put(processVariable.getKey(), processVariable.getValue()); } } public boolean isWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public List<String> getTenantIdIn() { return tenantIdIn; } public TopicSubscription setTenantIdIn(List<String> tenantIds) { this.tenantIdIn = tenantIds; return this; }
public boolean isIncludeExtensionProperties() { return includeExtensionProperties; } public void setIncludeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((topicName == null) ? 0 : topicName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TopicSubscriptionImpl other = (TopicSubscriptionImpl) obj; if (topicName == null) { if (other.topicName != null) return false; } else if (!topicName.equals(other.topicName)) { return false; } return true; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionImpl.java
1
请完成以下Java代码
public int getC_Task_ID() { return get_ValueAsInt(COLUMNNAME_C_Task_ID); } @Override public void setCommittedAmt (final BigDecimal CommittedAmt) { set_Value (COLUMNNAME_CommittedAmt, CommittedAmt); } @Override public BigDecimal getCommittedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CommittedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void 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 setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; }
/** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectTask.java
1
请在Spring Boot框架中完成以下Java代码
UserDetailsService customUserService(){ //注册UserDetailsService 的bean return new CustomUserService(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){ @Override public String encode(CharSequence rawPassword) { return MD5Util.encode((String)rawPassword); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return encodedPassword.equals(MD5Util.encode((String)rawPassword)); }}); //user Details Service验证 }
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() //任何请求,登录后可以访问 .and() .formLogin() .loginPage("/login") .failureUrl("/login?error") .permitAll() //登录页面用户任意访问 .and() .logout().permitAll(); //注销行为任意访问 } }
repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\config\WebSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.htm"); } /** * Add {@link CommonFilter} to the server, this is the simplest way to use Sentinel * for Web application. */ @Bean public FilterRegistrationBean sentinelFilterRegistration() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(new CommonFilter()); registration.addUrlPatterns("/*"); registration.setName("sentinelFilter"); registration.setOrder(1); // If this is enabled, the entrance of all Web URL resources will be unified as a single context name. // In most scenarios that's enough, and it could reduce the memory footprint. registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "true"); logger.info("Sentinel servlet CommonFilter registered"); return registration; } @PostConstruct public void doInit() { Set<String> suffixSet = new HashSet<>(Arrays.asList(".js", ".css", ".html", ".ico", ".txt", ".woff", ".woff2")); // Example: register a UrlCleaner to exclude URLs of common static resources. WebCallbackManager.setUrlCleaner(url -> { if (StringUtil.isEmpty(url)) { return url; } if (suffixSet.stream().anyMatch(url::endsWith)) {
return null; } return url; }); } @Bean public FilterRegistrationBean authenticationFilterRegistration() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(loginAuthenticationFilter); registration.addUrlPatterns("/*"); registration.setName("authenticationFilter"); registration.setOrder(0); return registration; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\config\WebConfig.java
2
请完成以下Java代码
public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_Value (COLUMNNAME_C_TaxCategory_ID, null); else set_Value (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setM_Product_TaxCategory_ID (final int M_Product_TaxCategory_ID) { if (M_Product_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, M_Product_TaxCategory_ID); } @Override public int getM_Product_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_TaxCategory_ID); } @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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_TaxCategory.java
1
请完成以下Java代码
public void addAggregator(IDunningAggregator aggregator) { dunningAggregators.add(aggregator); } public boolean isNewDunningDoc(I_C_Dunning_Candidate candidate) { Result finalResult = null; for (IDunningAggregator agg : dunningAggregators) { final Result result = agg.isNewDunningDoc(candidate); if (result == Result.I_FUCKING_DONT_CARE) { continue; } if (result == null) { finalResult = result; } if (!Util.same(result, finalResult)) { throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators); } } if (finalResult == null) { finalResult = defaultDunningAggregator.isNewDunningDoc(candidate); } return toBoolean(finalResult); } public boolean isNewDunningDocLine(I_C_Dunning_Candidate candidate) { if (dunningAggregators.isEmpty()) { throw new DunningException("No child " + IDunningAggregator.class + " registered"); } Result finalResult = null;
for (IDunningAggregator agg : dunningAggregators) { final Result result = agg.isNewDunningDocLine(candidate); if (result == Result.I_FUCKING_DONT_CARE) { continue; } if (result == null) { finalResult = result; } if (!Util.same(result, finalResult)) { throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators); } } if (finalResult == null) { finalResult = defaultDunningAggregator.isNewDunningDocLine(candidate); } return toBoolean(finalResult); } private static final boolean toBoolean(final Result result) { if (result == Result.YES) { return true; } else if (result == Result.NO) { return false; } else { throw new IllegalArgumentException("Result shall be YES or NO: " + result); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\CompositeDunningAggregator.java
1
请完成以下Java代码
public class BlobTriggerJava { /** * This function will be invoked when a new or updated blob is detected at the specified path. The blob contents are provided as input to this function. */ @FunctionName("BlobTriggerJava") @StorageAccount("AZURE_STORAGE") public void run( @BlobTrigger(name = "content", path = "feeds/{name}.csv", dataType = "binary") byte[] content, @BindingName("name") String fileName, @CosmosDBOutput(name = "output", databaseName = "organization", connection = "COSMOS_DB", containerName = "employee") OutputBinding<List<Employee>> employeeOutputBinding, final ExecutionContext context ) { context.getLogger().info("Java Blob trigger function processed a blob. Name: " + fileName + "\n Size: " + content.length + " Bytes"); employeeOutputBinding.setValue(getEmployeeList(content)); context.getLogger().info("Processing finished");
} private static List<Employee> getEmployeeList(byte[] content) { List<Employee> employees = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content)))) { String line; while ((line = reader.readLine()) != null) { String[] record = line.split(","); employees.add(new Employee(record[0], record[1], record[2], record[3])); } } catch (Exception e) { throw new RuntimeException(e); } return employees; } }
repos\tutorials-master\azure-functions\src\main\java\com\baeldung\azure\functions\BlobTriggerJava.java
1
请完成以下Java代码
public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } public List<FieldExtension> getFieldExtensions() { return fieldExtensions; } public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } @Override public ScriptInfo getScriptInfo() { return scriptInfo; } @Override public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo;
} @Override public abstract AbstractFlowableHttpHandler clone(); public void setValues(AbstractFlowableHttpHandler otherHandler) { super.setValues(otherHandler); setImplementation(otherHandler.getImplementation()); setImplementationType(otherHandler.getImplementationType()); if (otherHandler.getScriptInfo() != null) { setScriptInfo(otherHandler.getScriptInfo().clone()); } fieldExtensions = new ArrayList<>(); if (otherHandler.getFieldExtensions() != null && !otherHandler.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherHandler.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\AbstractFlowableHttpHandler.java
1
请完成以下Java代码
public Object getProperty(String name) { return getSource().getProperty(name); } @NonNull protected Predicate<String> getVcapServicePredicate() { return this.vcapServicePredicate != null ? this.vcapServicePredicate : propertyName -> true; } @Override public Iterator<String> iterator() { return Collections.unmodifiableList(Arrays.asList(getSource().getPropertyNames())).iterator(); } @NonNull public VcapPropertySource withVcapServiceName(@NonNull String serviceName) {
Assert.hasText(serviceName, "Service name is required"); String resolvedServiceName = StringUtils.trimAllWhitespace(serviceName); Predicate<String> vcapServiceNamePredicate = propertyName -> propertyName.startsWith(String.format("%1$s%2$s.", VCAP_SERVICES_PROPERTY, resolvedServiceName)); return withVcapServicePredicate(vcapServiceNamePredicate); } @NonNull public VcapPropertySource withVcapServicePredicate(@Nullable Predicate<String> vcapServicePredicate) { this.vcapServicePredicate = vcapServicePredicate; return this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\VcapPropertySource.java
1
请完成以下Java代码
public class AfterInvocationProviderManager implements AfterInvocationManager, InitializingBean { protected static final Log logger = LogFactory.getLog(AfterInvocationProviderManager.class); @SuppressWarnings("NullAway.Init") private @Nullable List<AfterInvocationProvider> providers; @Override public void afterPropertiesSet() { checkIfValidList(this.providers); } @Override public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { Object result = returnedObject; for (AfterInvocationProvider provider : this.providers) { result = provider.decide(authentication, object, config, result); } return result; } public List<AfterInvocationProvider> getProviders() { return this.providers; } public void setProviders(List<?> newList) { checkIfValidList(newList); this.providers = new ArrayList<>(newList.size()); for (Object currentObject : newList) { Assert.isInstanceOf(AfterInvocationProvider.class, currentObject, () -> "AfterInvocationProvider " + currentObject.getClass().getName() + " must implement AfterInvocationProvider"); this.providers.add((AfterInvocationProvider) currentObject); } } private void checkIfValidList(List<?> listToCheck) { Assert.isTrue(!CollectionUtils.isEmpty(listToCheck), "A list of AfterInvocationProviders is required"); } @Override
public boolean supports(ConfigAttribute attribute) { for (AfterInvocationProvider provider : this.providers) { logger.debug(LogMessage.format("Evaluating %s against %s", attribute, provider)); if (provider.supports(attribute)) { return true; } } return false; } /** * Iterates through all <code>AfterInvocationProvider</code>s and ensures each can * support the presented class. * <p> * If one or more providers cannot support the presented class, <code>false</code> is * returned. * @param clazz the secure object class being queries * @return if the <code>AfterInvocationProviderManager</code> can support the secure * object class, which requires every one of its <code>AfterInvocationProvider</code>s * to support the secure object class */ @Override public boolean supports(Class<?> clazz) { for (AfterInvocationProvider provider : this.providers) { if (!provider.supports(clazz)) { return false; } } return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AfterInvocationProviderManager.java
1
请完成以下Java代码
static Builder builder() { return new Builder(); } static class Builder { private int messageId; private Promise<Void> future; private ByteBuf payload; private MqttPublishMessage message; private MqttQoS qos; private String ownerId; private MqttClientConfig.RetransmissionConfig retransmissionConfig; private PendingOperation pendingOperation; Builder messageId(int messageId) { this.messageId = messageId; return this; } Builder future(Promise<Void> future) { this.future = future; return this; } Builder payload(ByteBuf payload) { this.payload = payload; return this; } Builder message(MqttPublishMessage message) { this.message = message; return this; } Builder qos(MqttQoS qos) { this.qos = qos; return this; }
Builder ownerId(String ownerId) { this.ownerId = ownerId; return this; } Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingPublish build() { return new MqttPendingPublish(messageId, future, payload, message, qos, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingPublish.java
1
请完成以下Java代码
public Float getProbability() { return probability; } public void setProbability(Float probability) { this.probability = probability; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((country_id == null) ? 0 : country_id.hashCode()); result = prime * result + ((probability == null) ? 0 : probability.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; NameCountryEntity other = (NameCountryEntity) obj; if (country_id == null) { if (other.country_id != null) return false; } else if (!country_id.equals(other.country_id)) return false; if (probability == null) { if (other.probability != null) return false; } else if (!probability.equals(other.probability)) return false; return true; } @Override public String toString() { return "NameCountryModel [country_id=" + country_id + ", probability=" + probability + "]"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameCountryEntity.java
1
请完成以下Java代码
public class ContextIdApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered { private int order = Ordered.LOWEST_PRECEDENCE - 10; public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void initialize(ConfigurableApplicationContext applicationContext) { ContextId contextId = getContextId(applicationContext); applicationContext.setId(contextId.getId()); applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), contextId); } private ContextId getContextId(ConfigurableApplicationContext applicationContext) { ApplicationContext parent = applicationContext.getParent(); if (parent != null && parent.containsBean(ContextId.class.getName())) { return parent.getBean(ContextId.class).createChildId(); } return new ContextId(getApplicationId(applicationContext.getEnvironment())); } private String getApplicationId(ConfigurableEnvironment environment) { String name = environment.getProperty("spring.application.name"); return StringUtils.hasText(name) ? name : "application"; } /** * The ID of a context. */ static class ContextId { private final AtomicLong children = new AtomicLong();
private final String id; ContextId(String id) { this.id = id; } ContextId createChildId() { return new ContextId(this.id + "-" + this.children.incrementAndGet()); } String getId() { return this.id; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\ContextIdApplicationContextInitializer.java
1
请完成以下Java代码
public void setAccessTokenResponseClient( ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds. * * <p> * An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew */ public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\ClientCredentialsReactiveOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public class ParameterMappingImpl extends CmmnElementImpl implements ParameterMapping { protected static AttributeReference<Parameter> sourceRefAttribute; protected static AttributeReference<Parameter> targetRefAttribute; protected static ChildElement<TransformationExpression> transformationChild; public ParameterMappingImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Parameter getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(Parameter parameter) { sourceRefAttribute.setReferenceTargetElement(this, parameter); } public Parameter getTarget() { return targetRefAttribute.getReferenceTargetElement(this); } public void setTarget(Parameter parameter) { targetRefAttribute.setReferenceTargetElement(this, parameter); } public TransformationExpression getTransformation() { return transformationChild.getChild(this); } public void setTransformation(TransformationExpression transformationExpression) { transformationChild.setChild(this, transformationExpression); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParameterMapping.class, CMMN_ELEMENT_PARAMETER_MAPPING) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<ParameterMapping>() { public ParameterMapping newInstance(ModelTypeInstanceContext instanceContext) { return new ParameterMappingImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(Parameter.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF) .idAttributeReference(Parameter.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); transformationChild = sequenceBuilder.element(TransformationExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ParameterMappingImpl.java
1
请完成以下Java代码
public class GraphTraversal { static Set<String> depthFirstTraversal(Graph graph, String root) { Set<String> visited = new LinkedHashSet<String>(); Stack<String> stack = new Stack<String>(); stack.push(root); while (!stack.isEmpty()) { String vertex = stack.pop(); if (!visited.contains(vertex)) { visited.add(vertex); for (Vertex v : graph.getAdjVertices(vertex)) { stack.push(v.label); } } } return visited; } static Set<String> breadthFirstTraversal(Graph graph, String root) { Set<String> visited = new LinkedHashSet<String>();
Queue<String> queue = new LinkedList<String>(); queue.add(root); visited.add(root); while (!queue.isEmpty()) { String vertex = queue.poll(); for (Vertex v : graph.getAdjVertices(vertex)) { if (!visited.contains(v.label)) { visited.add(v.label); queue.add(v.label); } } } return visited; } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\graph\GraphTraversal.java
1
请完成以下Java代码
public String foo(String deviceType) { log.info("foo({})", deviceType); Counter.builder("foo.count") .tag("device.type", deviceType) .register(meterRegistry) .increment(); String response = Timer.builder("foo.time") .tag("device.type", deviceType) .register(meterRegistry) .record(this::invokeSomeLogic); return response; } public String bar(String device) { log.info("bar({})", device); counterProvider.withTag("device.type", device) .increment(); String response = timerProvider.withTag("device.type", device) .record(this::invokeSomeLogic); return response; }
@Timed("buzz.time") @Counted("buzz.count") public String buzz(@MeterTag("device.type") String device) { log.info("buzz({})", device); return invokeSomeLogic(); } private String invokeSomeLogic() { long sleepMs = ThreadLocalRandom.current() .nextInt(0, 100); try { Thread.sleep(sleepMs); } catch (InterruptedException e) { throw new RuntimeException(e); } return "dummy response"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\micrometer\tags\dummy\DummyService.java
1
请完成以下Java代码
public java.lang.String getSenderName1 () { return (java.lang.String)get_Value(COLUMNNAME_SenderName1); } /** Set Name 2 Absender. @param SenderName2 Name 2 Absender */ @Override public void setSenderName2 (java.lang.String SenderName2) { set_Value (COLUMNNAME_SenderName2, SenderName2); } /** Get Name 2 Absender. @return Name 2 Absender */ @Override public java.lang.String getSenderName2 () { return (java.lang.String)get_Value(COLUMNNAME_SenderName2); } /** Set Straße Absender. @param SenderStreet Straße Absender */ @Override public void setSenderStreet (java.lang.String SenderStreet) { set_Value (COLUMNNAME_SenderStreet, SenderStreet); } /** Get Straße Absender. @return Straße Absender */ @Override public java.lang.String getSenderStreet () { return (java.lang.String)get_Value(COLUMNNAME_SenderStreet); } /** Set PLZ Absender. @param SenderZipCode PLZ Absender */ @Override public void setSenderZipCode (java.lang.String SenderZipCode) { set_Value (COLUMNNAME_SenderZipCode, SenderZipCode); } /** Get PLZ Absender. @return PLZ Absender */ @Override public java.lang.String getSenderZipCode () { return (java.lang.String)get_Value(COLUMNNAME_SenderZipCode); } /** Set Versandlager. @param SendingDepot Versandlager */ @Override public void setSendingDepot (java.lang.String SendingDepot)
{ set_Value (COLUMNNAME_SendingDepot, SendingDepot); } /** Get Versandlager. @return Versandlager */ @Override public java.lang.String getSendingDepot () { return (java.lang.String)get_Value(COLUMNNAME_SendingDepot); } /** Set Nachverfolgungs-URL. @param TrackingURL URL des Spediteurs um Sendungen zu verfolgen */ @Override public void setTrackingURL (java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } /** Get Nachverfolgungs-URL. @return URL des Spediteurs um Sendungen zu verfolgen */ @Override public java.lang.String getTrackingURL () { return (java.lang.String)get_Value(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder.java
1
请完成以下Java代码
public BigDecimal getDurationAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DurationAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setExternalId (final String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt) { set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt); } @Override public java.sql.Timestamp getExternallyUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt); } @Override public void setIsPrivateSale (final boolean IsPrivateSale) { set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale); } @Override public boolean isPrivateSale() { return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale); } @Override public void setIsRentalEquipment (final boolean IsRentalEquipment) { set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment); } @Override public boolean isRentalEquipment() { return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment); } @Override public void setSalesLineId (final @Nullable String SalesLineId) { set_Value (COLUMNNAME_SalesLineId, SalesLineId); } @Override public String getSalesLineId()
{ return get_ValueAsString(COLUMNNAME_SalesLineId); } @Override public void setTimePeriod (final @Nullable BigDecimal TimePeriod) { set_Value (COLUMNNAME_TimePeriod, TimePeriod); } @Override public BigDecimal getTimePeriod() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUnit (final @Nullable String Unit) { set_Value (COLUMNNAME_Unit, Unit); } @Override public String getUnit() { return get_ValueAsString(COLUMNNAME_Unit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java
1
请完成以下Java代码
public int getM_HU_PackagingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI getM_HU_PI() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class); } @Override public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI) { set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Version.java
1
请完成以下Java代码
public static boolean isNull(JsonObject jsonObject, String memberName) { if (jsonObject != null && memberName != null && jsonObject.has(memberName)) { return jsonObject.get(memberName).isJsonNull(); } else { return false; } } public static long getLong(JsonObject json, String memberName) { if (json != null && memberName != null && json.has(memberName)) { try { return json.get(memberName).getAsLong(); } catch (ClassCastException | IllegalStateException e) { LOG.logJsonException(e); return 0L; } } else { return 0L; } } public static JsonArray getArray(JsonObject json, String memberName) { if (json != null && memberName != null && json.has(memberName)) { return getArray(json.get(memberName)); } else { return createArray(); } } public static JsonArray getArray(JsonElement json) { if (json != null && json.isJsonArray()) { return json.getAsJsonArray(); } else { return createArray(); } } public static JsonObject getObject(JsonObject json, String memberName) { if (json != null && memberName != null && json.has(memberName)) { return getObject(json.get(memberName)); } else { return createObject(); } } public static JsonObject getObject(JsonElement json) { if (json != null && json.isJsonObject()) { return json.getAsJsonObject();
} else { return createObject(); } } public static JsonObject createObject() { return new JsonObject(); } public static JsonArray createArray() { return new JsonArray(); } public static Gson getGsonMapper() { return gsonMapper; } public static Gson createGsonMapper() { return new GsonBuilder() .serializeNulls() .registerTypeAdapter(Map.class, new JsonDeserializer<Map<String,Object>>() { public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, JsonElement> entry : getObject(json).entrySet()) { if (entry != null) { String key = entry.getKey(); JsonElement jsonElement = entry.getValue(); if (jsonElement != null && jsonElement.isJsonNull()) { map.put(key, null); } else if (jsonElement != null && jsonElement.isJsonPrimitive()) { Object rawValue = asPrimitiveObject((JsonPrimitive) jsonElement); if (rawValue != null) { map.put(key, rawValue); } } } } return map; } }) .create(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\JsonUtil.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } 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 java.lang.String getPickFrom_HUQRCode() { return get_ValueAsString(COLUMNNAME_PickFrom_HUQRCode); } /** * PickingJobAggregationType AD_Reference_ID=541931 * Reference name: PickingJobAggregationType */ public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931; /** sales_order = sales_order */ public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order"; /** product = product */ public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product"; /** delivery_location = delivery_location */ public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location"; @Override public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } @Override public void setPicking_User_ID (final int Picking_User_ID) { if (Picking_User_ID < 1) set_Value (COLUMNNAME_Picking_User_ID, null); else set_Value (COLUMNNAME_Picking_User_ID, Picking_User_ID); } @Override public int getPicking_User_ID() { return get_ValueAsInt(COLUMNNAME_Picking_User_ID); }
@Override public void setPreparationDate (final @Nullable java.sql.Timestamp PreparationDate) { set_Value (COLUMNNAME_PreparationDate, PreparationDate); } @Override public java.sql.Timestamp getPreparationDate() { return get_ValueAsTimestamp(COLUMNNAME_PreparationDate); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job.java
1
请完成以下Java代码
public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * Gets the value of the encoding property. * * @return * possible object is * {@link String } *
*/ public String getEncoding() { return encoding; } /** * Sets the value of the encoding property. * * @param value * allowed object is * {@link String } * */ public void setEncoding(String value) { this.encoding = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptedType.java
1
请在Spring Boot框架中完成以下Java代码
private @Nullable SslBundle getPemSslBundle(RunningService service) { PemSslStoreDetails keyStoreDetails = getPemSslStoreDetails(service, "keystore"); PemSslStoreDetails trustStoreDetails = getPemSslStoreDetails(service, "truststore"); if (keyStoreDetails == null && trustStoreDetails == null) { return null; } SslBundleKey key = SslBundleKey.of(service.labels().get("org.springframework.boot.sslbundle.pem.key.alias"), service.labels().get("org.springframework.boot.sslbundle.pem.key.password")); SslOptions options = createSslOptions( service.labels().get("org.springframework.boot.sslbundle.pem.options.ciphers"), service.labels().get("org.springframework.boot.sslbundle.pem.options.enabled-protocols")); String protocol = service.labels().get("org.springframework.boot.sslbundle.pem.protocol"); Path workingDirectory = getWorkingDirectory(service); ResourceLoader resourceLoader = getResourceLoader(workingDirectory); return SslBundle.of(new PemSslStoreBundle(PemSslStore.load(keyStoreDetails, resourceLoader), PemSslStore.load(trustStoreDetails, resourceLoader)), key, options, protocol); }
private @Nullable PemSslStoreDetails getPemSslStoreDetails(RunningService service, String storeType) { String type = service.labels().get("org.springframework.boot.sslbundle.pem.%s.type".formatted(storeType)); String certificate = service.labels() .get("org.springframework.boot.sslbundle.pem.%s.certificate".formatted(storeType)); String privateKey = service.labels() .get("org.springframework.boot.sslbundle.pem.%s.private-key".formatted(storeType)); String privateKeyPassword = service.labels() .get("org.springframework.boot.sslbundle.pem.%s.private-key-password".formatted(storeType)); if (certificate == null && privateKey == null) { return null; } return new PemSslStoreDetails(type, certificate, privateKey, privateKeyPassword); } } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\service\connection\DockerComposeConnectionDetailsFactory.java
2
请完成以下Java代码
public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setId(Long id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\errors\User.java
1
请完成以下Java代码
public boolean isCacheScriptingEngines() { return cacheScriptingEngines; } protected Object evaluate(String script, String language, Bindings bindings) { ScriptEngine scriptEngine = getEngineByName(language); try { return scriptEngine.eval(script, bindings); } catch (ScriptException e) { throw new ActivitiException("problem evaluating script: " + e.getMessage(), e); } } protected ScriptEngine getEngineByName(String language) { ScriptEngine scriptEngine = null; if (cacheScriptingEngines) { scriptEngine = cachedEngines.get(language); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName(language); if (scriptEngine != null) { // ACT-1858: Special handling for groovy engine regarding GC if (GROOVY_SCRIPTING_LANGUAGE.equals(language)) { try { scriptEngine .getContext() .setAttribute("#jsr223.groovy.engine.keep.globals", "weak", ScriptContext.ENGINE_SCOPE); } catch (Exception ignore) { // ignore this, in case engine doesn't support the // passed attribute } } // Check if script-engine allows caching, using "THREADING" // parameter as defined in spec Object threadingParameter = scriptEngine.getFactory().getParameter("THREADING"); if (threadingParameter != null) { // Add engine to cache as any non-null result from the // threading-parameter indicates at least MT-access cachedEngines.put(language, scriptEngine); } } } } else { scriptEngine = scriptEngineManager.getEngineByName(language); }
if (scriptEngine == null) { throw new ActivitiException("Can't find scripting engine for '" + language + "'"); } return scriptEngine; } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope) { return scriptBindingsFactory.createBindings(variableScope); } /** override to build a spring aware ScriptingEngines */ protected Bindings createBindings(VariableScope variableScope, boolean storeScriptVariables) { return scriptBindingsFactory.createBindings(variableScope, storeScriptVariables); } public ScriptBindingsFactory getScriptBindingsFactory() { return scriptBindingsFactory; } public void setScriptBindingsFactory(ScriptBindingsFactory scriptBindingsFactory) { this.scriptBindingsFactory = scriptBindingsFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptingEngines.java
1
请在Spring Boot框架中完成以下Java代码
public String getCategory() { return job.getCategory(); } @Override public String getJobType() { return job.getJobType(); } @Override public String getElementId() { return job.getElementId(); } @Override public String getElementName() { return job.getElementName(); } @Override public String getScopeId() { return job.getScopeId(); } @Override public String getSubScopeId() { return job.getSubScopeId(); } @Override public String getScopeType() { return job.getScopeType(); } @Override public String getScopeDefinitionId() { return job.getScopeDefinitionId(); } @Override public String getCorrelationId() { return job.getCorrelationId(); } @Override public boolean isExclusive() { return job.isExclusive(); } @Override public Date getCreateTime() { return job.getCreateTime(); } @Override public String getId() { return job.getId(); } @Override public int getRetries() { return job.getRetries(); } @Override public String getExceptionMessage() { return job.getExceptionMessage(); } @Override public String getTenantId() { return job.getTenantId(); }
@Override public String getJobHandlerType() { return job.getJobHandlerType(); } @Override public String getJobHandlerConfiguration() { return job.getJobHandlerConfiguration(); } @Override public String getCustomValues() { return job.getCustomValues(); } @Override public String getLockOwner() { return job.getLockOwner(); } @Override public Date getLockExpirationTime() { return job.getLockExpirationTime(); } @Override public String toString() { return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]") .add("job=" + job) .toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setQualifierDelimiter(String qualifierDelimiter) { this.qualifierDelimiter = qualifierDelimiter; } public int getDefaultPageSize() { return this.defaultPageSize; } public void setDefaultPageSize(int defaultPageSize) { this.defaultPageSize = defaultPageSize; } public int getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode; } public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort {
/** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请完成以下Java代码
public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType) { final String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 + " invoiceOpen(C_Invoice_ID, ?)," // 3 #1 + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, c_Invoice_ID); pstmt.setTimestamp(2, payment.getDateTrx()); pstmt.setInt(3, c_Invoice_ID); pstmt.setInt(4, c_Invoice_ID); rs = pstmt.executeQuery(); if (rs.next()) { final int bpartnerId = rs.getInt(1); payment.setC_BPartner_ID(bpartnerId); // Set Invoice Currency final int C_Currency_ID = rs.getInt(2); payment.setC_Currency_ID(C_Currency_ID); // BigDecimal InvoiceOpen = rs.getBigDecimal(3); // Set Invoice // OPen Amount if (InvoiceOpen == null) { InvoiceOpen = BigDecimal.ZERO;
} BigDecimal DiscountAmt = rs.getBigDecimal(4); // Set Discount // Amt if (DiscountAmt == null) { DiscountAmt = BigDecimal.ZERO; } BigDecimal payAmt = InvoiceOpen.subtract(DiscountAmt); if (X_C_DocType.DOCBASETYPE_APCreditMemo.equals(c_DocType.getDocBaseType()) || X_C_DocType.DOCBASETYPE_ARCreditMemo.equals(c_DocType.getDocBaseType())) { if (payAmt.signum() < 0) { payAmt = payAmt.abs(); } } payment.setPayAmt(payAmt); payment.setDiscountAmt(DiscountAmt); } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentDAO.java
1
请完成以下Java代码
public static class DomErrorHandler implements ErrorHandler { private static final Logger LOGGER = Logger.getLogger(DomErrorHandler.class.getName()); private String getParseExceptionInfo(SAXParseException spe) { return "URI=" + spe.getSystemId() + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); } public void warning(SAXParseException spe) { LOGGER.warning(getParseExceptionInfo(spe)); } public void error(SAXParseException spe) throws SAXException { String message = "Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } public void fatalError(SAXParseException spe) throws SAXException { String message = "Fatal Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } } /** * Get an empty DOM document * * @param documentBuilderFactory the factory to build to DOM document * @return the new empty document * @throws ModelParseException if unable to create a new document */ public static DomDocument getEmptyDocument(DocumentBuilderFactory documentBuilderFactory) { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return new DomDocumentImpl(documentBuilder.newDocument()); } catch (ParserConfigurationException e) { throw new ModelParseException("Unable to create a new document", e); } } /**
* Create a new DOM document from the input stream * * @param documentBuilderFactory the factory to build to DOM document * @param inputStream the input stream to parse * @return the new DOM document * @throws ModelParseException if a parsing or IO error is triggered */ public static DomDocument parseInputStream(DocumentBuilderFactory documentBuilderFactory, InputStream inputStream) { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(new DomErrorHandler()); return new DomDocumentImpl(documentBuilder.parse(inputStream)); } catch (ParserConfigurationException e) { throw new ModelParseException("ParserConfigurationException while parsing input stream", e); } catch (SAXException e) { throw new ModelParseException("SAXException while parsing input stream", e); } catch (IOException e) { throw new ModelParseException("IOException while parsing input stream", e); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\DomUtil.java
1
请完成以下Java代码
public void setLineNo (final int LineNo) { set_Value (COLUMNNAME_LineNo, LineNo); } @Override public int getLineNo() { return get_ValueAsInt(COLUMNNAME_LineNo); } @Override public void setMatchErrorMsg (final @Nullable java.lang.String MatchErrorMsg) { set_Value (COLUMNNAME_MatchErrorMsg, MatchErrorMsg); } @Override public java.lang.String getMatchErrorMsg() { return get_ValueAsString(COLUMNNAME_MatchErrorMsg); } @Override public void setOrg_ID (final int Org_ID) { if (Org_ID < 1) set_Value (COLUMNNAME_Org_ID, null); else set_Value (COLUMNNAME_Org_ID, Org_ID); } @Override public int getOrg_ID() { return get_ValueAsInt(COLUMNNAME_Org_ID); } @Override public void setPaymentDate (final @Nullable java.sql.Timestamp PaymentDate) { set_Value (COLUMNNAME_PaymentDate, PaymentDate); } @Override public java.sql.Timestamp getPaymentDate() { return get_ValueAsTimestamp(COLUMNNAME_PaymentDate); }
@Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setSektionNo (final @Nullable java.lang.String SektionNo) { set_Value (COLUMNNAME_SektionNo, SektionNo); } @Override public java.lang.String getSektionNo() { return get_ValueAsString(COLUMNNAME_SektionNo); } /** * Type AD_Reference_ID=541287 * Reference name: ESR_Type */ public static final int TYPE_AD_Reference_ID=541287; /** QRR = QRR */ public static final String TYPE_QRR = "QRR"; /** ESR = ISR Reference */ public static final String TYPE_ESR = "ISR Reference"; /** SCOR = SCOR Reference */ public static final String TYPE_SCOR = "SCOR"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportLine.java
1
请完成以下Java代码
public static String usingCodePointsMethod(String text, int length) { if (length < 0) { throw new IllegalArgumentException("length cannot be negative"); } if (text == null) { return EMPTY; } return text.codePoints() .limit(length) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } public static String usingLeftMethod(String text, int length) { return StringUtils.left(text, length); } public static String usingTruncateMethod(String text, int length) { return StringUtils.truncate(text, length);
} public static String usingSplitter(String text, int length) { if (length < 0) { throw new IllegalArgumentException("length cannot be negative"); } if (text == null) { return EMPTY; } Iterable<String> parts = Splitter.fixedLength(length) .split(text); return parts.iterator() .next(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\truncate\TruncateString.java
1
请在Spring Boot框架中完成以下Java代码
public class MailRestService { private final AttachmentEntryService attachmentEntryService; private final DocumentDescriptorFactory documentDescriptorFactory; private final UserSession userSession; private final WebuiDocumentPrintService documentPrintService; public MailRestService( @NonNull final AttachmentEntryService attachmentEntryService, @NonNull final DocumentDescriptorFactory documentDescriptorFactory, @NonNull final UserSession userSession, @NonNull final WebuiDocumentPrintService documentPrintService) { this.attachmentEntryService = attachmentEntryService; this.documentDescriptorFactory = documentDescriptorFactory; this.userSession = userSession; this.documentPrintService = documentPrintService; } @NonNull public List<EmailAttachment> getEmailAttachments( @NonNull final DocumentPath documentPath, @NonNull final String tagName) { final TableRecordReference recordRef = documentDescriptorFactory.getTableRecordReference(documentPath); final WebuiDocumentPrintRequest printRequest = WebuiDocumentPrintRequest.builder() .flavor(DocumentReportFlavor.EMAIL) .documentPath(documentPath) .userId(userSession.getLoggedUserId()) .roleId(userSession.getLoggedRoleId()) .build(); final Stream<EmailAttachment> emailAttachments = documentPrintService.createDocumentPrint(printRequest) .map(MailRestService::toEmailAttachment)
.map(Stream::of).orElseGet(Stream::empty); return Stream.concat(emailAttachments, attachmentEntryService.streamEmailAttachments(recordRef, tagName)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } private static EmailAttachment toEmailAttachment(final ReportResultData contextDocumentPrint) { return EmailAttachment.builder() .filename(contextDocumentPrint.getReportFilename()) .attachmentDataSupplier(contextDocumentPrint::getReportDataByteArray) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\MailRestService.java
2
请完成以下Java代码
InputStream getInputStream() throws IOException { synchronized (this) { if (this.inputStream == null) { throw new IOException("Nested location not found " + this.location); } return this.inputStream; } } long getContentLength() { return this.size; } @Override public void run() { releaseAll(); } private void releaseAll() { synchronized (this) { if (this.zipContent != null) { IOException exceptionChain = null; try { this.inputStream.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } try { this.zipContent.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex);
} this.size = -1; if (exceptionChain != null) { throw new UncheckedIOException(exceptionChain); } } } } private IOException addToExceptionChain(IOException exceptionChain, IOException ex) { if (exceptionChain != null) { exceptionChain.addSuppressed(ex); return exceptionChain; } return ex; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnectionResources.java
1