instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class Event implements Serializable { @Id @GeneratedValue private Long id; private String description; public Event() { } public Event(String description) { this.description = description; } 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; } }
repos\tutorials-master\persistence-modules\spring-hibernate-3\src\main\java\com\baeldung\persistence\model\Event.java
2
请完成以下Java代码
protected void ensureSourceCaseExecutionInitialized() { if ((sourceCaseExecution == null) && (sourceCaseExecutionId != null)) { sourceCaseExecution = findCaseExecutionById(sourceCaseExecutionId); } } public void setSourceCaseExecution(CmmnExecution sourceCaseExecution) { this.sourceCaseExecution = (CaseExecutionEntity) sourceCaseExecution; if (sourceCaseExecution != null) { sourceCaseExecutionId = sourceCaseExecution.getId(); } else { sourceCaseExecutionId = null; } } // persistence ///////////////////////////////////////////////////////// public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public int getRevisionNext() { return revision + 1; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void forceUpdate() { this.forcedUpdate = true; } public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("satisfied", isSatisfied()); if (forcedUpdate) { persistentState.put("forcedUpdate", Boolean.TRUE); } return persistentState; } // helper ////////////////////////////////////////////////////////////////////
protected CaseExecutionEntity findCaseExecutionById(String caseExecutionId) { return Context .getCommandContext() .getCaseExecutionManager() .findCaseExecutionById(caseExecutionId); } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); if (caseExecutionId != null) { referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } if (caseInstanceId != null) { referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class); } return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartEntity.java
1
请完成以下Java代码
public class VariableContainerWrapper implements VariableContainer { protected Map<String, Object> variables = new HashMap<>(); protected String instanceId; protected String scopeType; protected String tenantId; public VariableContainerWrapper(Map<String, Object> variables) { if (variables != null) { this.variables.putAll(variables); } } @Override public boolean hasVariable(String variableName) { return variables.containsKey(variableName); } @Override public Object getVariable(String variableName) { return variables.get(variableName); } @Override public void setVariable(String variableName, Object variableValue) { variables.put(variableName, variableValue); } @Override public void setTransientVariable(String variableName, Object variableValue) { throw new UnsupportedOperationException(); } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; }
@Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("instanceId='" + instanceId + "'") .add("scopeType='" + scopeType + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\VariableContainerWrapper.java
1
请完成以下Java代码
public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Sql WHERE. @param WhereClause
Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_HouseKeeping.java
1
请完成以下Java代码
public static void concatByStreamBy100(Blackhole blackhole) { concatByStream(ITERATION_100, blackhole); } @Benchmark public static void concatByStreamBy1000(Blackhole blackhole) { concatByStream(ITERATION_1000, blackhole); } @Benchmark public static void concatByStreamBy10000(Blackhole blackhole) { concatByStream(ITERATION_10000, blackhole); } public static void concatByStream(int iterations, Blackhole blackhole) { String concatString = ""; List<String> strList = new ArrayList<>(); strList.add(concatString); strList.add(TOKEN); for (int n=0; n<iterations; n++) {
concatString = strList.stream().collect(Collectors.joining("")); strList.set(0, concatString); } blackhole.consume(concatString); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(LoopConcatBenchmark.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\LoopConcatBenchmark.java
1
请完成以下Java代码
public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_InOutLine_To_C_Customs_Invoice_Line. @param M_InOutLine_To_C_Customs_Invoice_Line_ID M_InOutLine_To_C_Customs_Invoice_Line */ @Override public void setM_InOutLine_To_C_Customs_Invoice_Line_ID (int M_InOutLine_To_C_Customs_Invoice_Line_ID) { if (M_InOutLine_To_C_Customs_Invoice_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID, Integer.valueOf(M_InOutLine_To_C_Customs_Invoice_Line_ID)); } /** Get M_InOutLine_To_C_Customs_Invoice_Line. @return M_InOutLine_To_C_Customs_Invoice_Line */ @Override public int getM_InOutLine_To_C_Customs_Invoice_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bewegungs-Menge. @param MovementQty Menge eines bewegten Produktes. */ @Override public void setMovementQty (java.math.BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Bewegungs-Menge. @return Menge eines bewegten Produktes. */ @Override public java.math.BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Einzelpreis. @param PriceActual Effektiver Preis */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLine_To_C_Customs_Invoice_Line.java
1
请完成以下Java代码
public boolean isDirectory() { return this.delegate.isDirectory(); } @Override public boolean isReadable() { return this.delegate.isReadable(); } @Override public Instant lastModified() { return this.delegate.lastModified(); } @Override public long length() { return this.delegate.length(); } @Override public URI getURI() { return this.delegate.getURI(); } @Override public String getName() { return this.delegate.getName(); } @Override public String getFileName() { return this.delegate.getFileName(); } @Override public InputStream newInputStream() throws IOException { return this.delegate.newInputStream(); } @Override @SuppressWarnings({ "deprecation", "removal" }) public ReadableByteChannel newReadableByteChannel() throws IOException { return this.delegate.newReadableByteChannel(); } @Override public List<Resource> list() { return asLoaderHidingResources(this.delegate.list()); } private boolean nonLoaderResource(Resource resource) { return !resource.getPath().startsWith(this.loaderBasePath); } private List<Resource> asLoaderHidingResources(Collection<Resource> resources) { return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList(); } private Resource asLoaderHidingResource(Resource resource) { return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource); } @Override
public @Nullable Resource resolve(String subUriPath) { if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) { return null; } Resource resolved = this.delegate.resolve(subUriPath); return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null; } @Override public boolean isAlias() { return this.delegate.isAlias(); } @Override public URI getRealURI() { return this.delegate.getRealURI(); } @Override public void copyTo(Path destination) throws IOException { this.delegate.copyTo(destination); } @Override public Collection<Resource> getAllResources() { return asLoaderHidingResources(this.delegate.getAllResources()); } @Override public String toString() { return this.delegate.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
1
请完成以下Java代码
public void setLabelReport_Process_ID (final int LabelReport_Process_ID) { if (LabelReport_Process_ID < 1) set_Value (COLUMNNAME_LabelReport_Process_ID, null); else set_Value (COLUMNNAME_LabelReport_Process_ID, LabelReport_Process_ID); } @Override public int getLabelReport_Process_ID() { return get_ValueAsInt(COLUMNNAME_LabelReport_Process_ID); } @Override public void setM_HU_Label_Config_ID (final int M_HU_Label_Config_ID) { if (M_HU_Label_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Label_Config_ID, M_HU_Label_Config_ID); } @Override
public int getM_HU_Label_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Label_Config_ID); } @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Label_Config.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @Generated private @Nullable ObjectId id; @NotBlank private String title; @NotNull private Author author; private int year; public Book() { } public Book(@Nullable ObjectId id, String title, Author author, int year) { this.id = id; this.title = title; this.author = author; this.year = year; } public Book(String title, Author author, int year) { this.title = title; this.author = author; this.year = year; } public @Nullable ObjectId getId() { return id; } public void setId(@Nullable ObjectId id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } }
repos\tutorials-master\microservices-modules\micronaut-reactive\src\main\java\com\baeldung\micronautreactive\entity\Book.java
2
请在Spring Boot框架中完成以下Java代码
private static final class IncotermsMap { private final ImmutableMap<IncotermsId, Incoterms> byId; private final ImmutableMap<OrgId, Incoterms> defaultByOrgId; private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId; IncotermsMap(final List<Incoterms> list) { this.byId = Maps.uniqueIndex(list, Incoterms::getId); this.defaultByOrgId = list.stream().filter(Incoterms::isDefault) .collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms)); this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build()); } @NonNull public Incoterms getById(@NonNull final IncotermsId id) { final Incoterms incoterms = byId.get(id); if (incoterms == null) { throw new AdempiereException("Incoterms not found by ID: " + id); } return incoterms; } @Nullable public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId) { return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY)); } @NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId)
{ final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()), byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build())); if (incoterms == null) { throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY); } return incoterms; } @Builder @Value private static class ValueAndOrgId { @NonNull String value; @NonNull OrgId orgId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
2
请在Spring Boot框架中完成以下Java代码
public String getMerchantShortname() { return merchantShortname; } public void setMerchantShortname(String merchantShortname) { this.merchantShortname = merchantShortname; } public String getServicePhone() { return servicePhone; } public void setServicePhone(String servicePhone) { this.servicePhone = servicePhone; } public String getProductDesc() { return productDesc; } public void setProductDesc(String productDesc) { this.productDesc = productDesc; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } @Override
public String toString() { return "RpMicroSubmitRecord{" + "businessCode='" + businessCode + '\'' + ", subMchId='" + subMchId + '\'' + ", idCardCopy='" + idCardCopy + '\'' + ", idCardNational='" + idCardNational + '\'' + ", idCardName='" + idCardName + '\'' + ", idCardNumber='" + idCardNumber + '\'' + ", idCardValidTime='" + idCardValidTime + '\'' + ", accountBank='" + accountBank + '\'' + ", bankAddressCode='" + bankAddressCode + '\'' + ", accountNumber='" + accountNumber + '\'' + ", storeName='" + storeName + '\'' + ", storeAddressCode='" + storeAddressCode + '\'' + ", storeStreet='" + storeStreet + '\'' + ", storeEntrancePic='" + storeEntrancePic + '\'' + ", indoorPic='" + indoorPic + '\'' + ", merchantShortname='" + merchantShortname + '\'' + ", servicePhone='" + servicePhone + '\'' + ", productDesc='" + productDesc + '\'' + ", rate='" + rate + '\'' + ", contactPhone='" + contactPhone + '\'' + ", idCardValidTimeBegin='" + idCardValidTimeBegin + '\'' + ", idCardValidTimeEnd='" + idCardValidTimeEnd + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpMicroSubmitRecord.java
2
请在Spring Boot框架中完成以下Java代码
public static class HUQRCodeGenerateRequestBuilder { public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable String valueString) { return _attribute(Attribute.builder().attributeId(attributeId).valueString(valueString).build()); } public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable BigDecimal valueNumber) { return _attribute(Attribute.builder().attributeId(attributeId).valueNumber(valueNumber).build()); } public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable LocalDate valueDate) { return _attribute(Attribute.builder().attributeId(attributeId).valueDate(valueDate).build()); } public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable AttributeValueId valueListId) { return _attribute(Attribute.builder().attributeId(attributeId).valueListId(valueListId).build()); } public HUQRCodeGenerateRequestBuilder lotNo(@Nullable final String lotNo, @NonNull final Function<AttributeCode, AttributeId> getAttributeIdByCode) { final AttributeId attributeId = getAttributeIdByCode.apply(AttributeConstants.ATTR_LotNumber); return attribute(attributeId, StringUtils.trimBlankToNull(lotNo)); } } //
// // @Value @Builder public static class Attribute { @Nullable AttributeId attributeId; @Nullable AttributeCode code; @Nullable String valueString; @Nullable BigDecimal valueNumber; @Nullable LocalDate valueDate; @Nullable AttributeValueId valueListId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateRequest.java
2
请完成以下Java代码
public FlowElementsContainer getParentContainer() { return parentContainer; } @JsonIgnore public SubProcess getSubProcess() { SubProcess subProcess = null; if (parentContainer instanceof SubProcess) { subProcess = (SubProcess) parentContainer; } return subProcess; } public void setParentContainer(FlowElementsContainer parentContainer) { this.parentContainer = parentContainer; } @Override
public abstract FlowElement clone(); public void setValues(FlowElement otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setDocumentation(otherElement.getDocumentation()); executionListeners = new ArrayList<>(); if (otherElement.getExecutionListeners() != null && !otherElement.getExecutionListeners().isEmpty()) { for (FlowableListener listener : otherElement.getExecutionListeners()) { executionListeners.add(listener.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowElement.java
1
请完成以下Java代码
public String getId() { return name + reporter + timestamp.toString(); } @Override public void setId(String id) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Object getPersistentState() { return MetricIntervalEntity.class; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + (this.timestamp != null ? this.timestamp.hashCode() : 0); hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 67 * hash + (this.reporter != null ? this.reporter.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } final MetricIntervalEntity other = (MetricIntervalEntity) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.reporter == null) ? (other.reporter != null) : !this.reporter.equals(other.reporter)) { return false; } if (this.timestamp != other.timestamp && (this.timestamp == null || !this.timestamp.equals(other.timestamp))) { return false; } return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MetricIntervalEntity.java
1
请在Spring Boot框架中完成以下Java代码
class ProductService { private final String PRODUCT_ADDED_TO_CART_TOPIC = "product-added-to-cart"; private final ProductRepository repository; private final DiscountService discountService; private final KafkaTemplate<String, ProductAddedToCartEvent> kafkaTemplate; public ProductService(ProductRepository repository, DiscountService discountService) { this.repository = repository; this.discountService = discountService; this.kafkaTemplate = new KafkaTemplate<>(); } public void addProductToCart(String productId, String cartId) { Thread.startVirtualThread(() -> computePriceAndPublishMessage(productId, cartId)); } private void computePriceAndPublishMessage(String productId, String cartId) { Product product = repository.findById(productId) .orElseThrow(() -> new IllegalArgumentException("not found!"));
Price price = computePrice(productId, product); var event = new ProductAddedToCartEvent(productId, price.value(), price.currency(), cartId); kafkaTemplate.send(PRODUCT_ADDED_TO_CART_TOPIC, cartId, event); } private Price computePrice(String productId, Product product) { if (product.category().isEligibleForDiscount()) { BigDecimal discount = discountService.discountForProduct(productId); return product.basePrice().applyDiscount(discount); } return product.basePrice(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-performance\src\main\java\com\baeldung\spring\reactive\performance\virtualthreads\ProductService.java
2
请在Spring Boot框架中完成以下Java代码
class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { private final JmxEndpointProperties properties; private final JmxProperties jmxProperties; private final @Nullable MBeanServer mBeanServer; private final @Nullable String contextId; DefaultEndpointObjectNameFactory(JmxEndpointProperties properties, JmxProperties jmxProperties, @Nullable MBeanServer mBeanServer, @Nullable String contextId) { this.properties = properties; this.jmxProperties = jmxProperties; this.mBeanServer = mBeanServer; this.contextId = contextId; } @Override public ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(determineDomain()); builder.append(":type=Endpoint"); builder.append(",name=").append(StringUtils.capitalize(endpoint.getEndpointId().toString())); String baseName = builder.toString(); if (this.mBeanServer != null && hasMBean(baseName)) { builder.append(",context=").append(this.contextId); } if (this.jmxProperties.isUniqueNames()) { String identity = ObjectUtils.getIdentityHexString(endpoint); builder.append(",identity=").append(identity); } builder.append(getStaticNames()); return ObjectNameManager.getInstance(builder.toString()); } private String determineDomain() { if (StringUtils.hasText(this.properties.getDomain())) { return this.properties.getDomain(); } if (StringUtils.hasText(this.jmxProperties.getDefaultDomain())) { return this.jmxProperties.getDefaultDomain();
} return "org.springframework.boot"; } private boolean hasMBean(String baseObjectName) throws MalformedObjectNameException { ObjectName query = new ObjectName(baseObjectName + ",*"); Assert.state(this.mBeanServer != null, "'mBeanServer' must not be null"); return !this.mBeanServer.queryNames(query, null).isEmpty(); } private String getStaticNames() { if (this.properties.getStaticNames().isEmpty()) { return ""; } StringBuilder builder = new StringBuilder(); this.properties.getStaticNames() .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); return builder.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\DefaultEndpointObjectNameFactory.java
2
请完成以下Java代码
public void setMatchingRequestParameterName(String matchingRequestParameterName) { this.matchingRequestParameterName = matchingRequestParameterName; } private ServerHttpRequest stripMatchingRequestParameterName(ServerHttpRequest request) { if (this.matchingRequestParameterName == null) { return request; } // @formatter:off URI uri = UriComponentsBuilder.fromUri(request.getURI()) .replaceQueryParam(this.matchingRequestParameterName) .build() .toUri(); return request.mutate() .uri(uri) .build(); // @formatter:on } private static String pathInApplication(ServerHttpRequest request) { String path = request.getPath().pathWithinApplication().value(); String query = request.getURI().getRawQuery(); return path + ((query != null) ? "?" + query : ""); }
private URI createRedirectUri(String uri) { if (this.matchingRequestParameterName == null) { return URI.create(uri); } // @formatter:off return UriComponentsBuilder.fromUriString(uri) .queryParam(this.matchingRequestParameterName) .build() .toUri(); // @formatter:on } private static ServerWebExchangeMatcher createDefaultRequestMatcher() { ServerWebExchangeMatcher get = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/**"); ServerWebExchangeMatcher notFavicon = new NegatedServerWebExchangeMatcher( ServerWebExchangeMatchers.pathMatchers("/favicon.*")); MediaTypeServerWebExchangeMatcher html = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML); html.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); return new AndServerWebExchangeMatcher(get, notFavicon, html); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\savedrequest\WebSessionServerRequestCache.java
1
请在Spring Boot框架中完成以下Java代码
public String showAddTodoPage(ModelMap model) { model.addAttribute("todo", new Todo(0, getLoggedInUserName(model), "Default Desc", new Date(), false)); return "todo"; } @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) public String deleteTodo(@RequestParam int id) { if(id==1) throw new RuntimeException("Something went wrong"); service.deleteTodo(id); return "redirect:/list-todos"; } @RequestMapping(value = "/update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { Todo todo = service.retrieveTodo(id); model.put("todo", todo); return "todo"; } @RequestMapping(value = "/update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) {
return "todo"; } todo.setUser(getLoggedInUserName(model)); service.updateTodo(todo); return "redirect:/list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.POST) public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(), false); return "redirect:/list-todos"; } }
repos\SpringBootForBeginners-master\02.Spring-Boot-Web-Application\src\main\java\com\in28minutes\springboot\web\controller\TodoController.java
2
请完成以下Java代码
public class Region implements Serializable { @Serial private static final long serialVersionUID = 1L; /** * 区划编号 */ @TableId(value = "code", type = IdType.INPUT) @Schema(description = "区划编号") private String code; /** * 父区划编号 */ @Schema(description = "父区划编号") private String parentCode; /** * 祖区划编号 */ @Schema(description = "祖区划编号") private String ancestors; /** * 区划名称 */ @Schema(description = "区划名称") private String name; /** * 省级区划编号 */ @Schema(description = "省级区划编号") private String provinceCode; /** * 省级名称 */ @Schema(description = "省级名称") private String provinceName; /** * 市级区划编号 */ @Schema(description = "市级区划编号") private String cityCode; /** * 市级名称 */ @Schema(description = "市级名称") private String cityName; /** * 区级区划编号 */ @Schema(description = "区级区划编号") private String districtCode; /** * 区级名称 */ @Schema(description = "区级名称") private String districtName; /** * 镇级区划编号 */ @Schema(description = "镇级区划编号") private String townCode; /** * 镇级名称 */ @Schema(description = "镇级名称")
private String townName; /** * 村级区划编号 */ @Schema(description = "村级区划编号") private String villageCode; /** * 村级名称 */ @Schema(description = "村级名称") private String villageName; /** * 层级 */ @Schema(description = "层级") private Integer level; /** * 排序 */ @Schema(description = "排序") private Integer sort; /** * 备注 */ @Schema(description = "备注") private String remark; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Region.java
1
请在Spring Boot框架中完成以下Java代码
public class RestService { @Autowired private RestTemplate restTemplate; private static String HOST = "http://localhost:8080"; private static String GET_URL = "/testGet"; private static String POST_URL = "/testPost"; private static String POST_PARAM_URL = "/testPostParam"; private static String PUT_URL = "/testPut"; private static String DEL_URL = "/testDel"; public void get() throws URISyntaxException { ResponseEntity<TestDTO> responseEntity = this.restTemplate.getForEntity(HOST + GET_URL, TestDTO.class); System.out.println("getForEntity: " + responseEntity.getBody()); TestDTO forObject = this.restTemplate.getForObject(HOST + GET_URL, TestDTO.class); System.out.println("getForObject: " + forObject); RequestEntity<Void> requestEntity = RequestEntity.get(new URI(HOST + GET_URL)).build(); ResponseEntity<TestDTO> exchange = this.restTemplate.exchange(requestEntity, TestDTO.class); System.out.println("exchange: " + exchange.getBody()); } public void post() throws URISyntaxException { TestDTO td = new TestDTO(); td.setId(1); td.setName("post"); String url = HOST + POST_URL;
HttpHeaders headers = new HttpHeaders(); HttpEntity<TestDTO> httpEntity = new HttpEntity<>(td, headers); ResponseEntity<TestDTO> responseEntity = this.restTemplate.postForEntity(url, httpEntity, TestDTO.class); System.out.println("postForEntity: " + responseEntity.getBody()); TestDTO testDTO = this.restTemplate.postForObject(url, httpEntity, TestDTO.class); System.out.println("postForObject: " + testDTO); ResponseEntity<TestDTO> exchange = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, TestDTO.class); System.out.println("exchange: " + exchange.getBody()); } public void post4Form() { String url = HOST + POST_PARAM_URL; HttpHeaders headers = new HttpHeaders(); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "100"); map.add("name", "post4Form"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, request, String.class); System.out.println("postForEntity: " + responseEntity.getBody()); } }
repos\spring-boot-quick-master\quick-rest-template\src\main\java\com\rest\template\service\RestService.java
2
请在Spring Boot框架中完成以下Java代码
public class WarehouseGroup { @NonNull WarehouseGroupId id; @NonNull String name; @Nullable String description; @NonNull ImmutableSet<WarehouseGroupAssignment> assignments; @NonNull ImmutableSetMultimap<WarehouseGroupAssignmentType, WarehouseId> warehouseIdsByAssignmentType; @Builder public WarehouseGroup( @NonNull final WarehouseGroupId id, @NonNull final String name, @Nullable final String description, @NonNull @Singular final ImmutableSet<WarehouseGroupAssignment> assignments) { this.id = id;
this.name = StringUtils.trimBlankToOptional(name) .orElseThrow(() -> new AdempiereException("Blank warehouse group name not allowed")); this.description = StringUtils.trimBlankToNull(description); this.assignments = assignments; this.warehouseIdsByAssignmentType = assignments .stream() .collect(ImmutableSetMultimap.toImmutableSetMultimap( WarehouseGroupAssignment::getAssignmentType, WarehouseGroupAssignment::getWarehouseId)); } public ImmutableSet<WarehouseId> getWarehouseIds(@NonNull final WarehouseGroupAssignmentType assignmentType) { return warehouseIdsByAssignmentType.get(assignmentType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\groups\WarehouseGroup.java
2
请完成以下Java代码
public @Nullable Object invoke(MethodInvocation mi) throws Throwable { PreFilterExpressionAttributeRegistry.PreFilterExpressionAttribute attribute = this.registry.getAttribute(mi); if (attribute == null) { return mi.proceed(); } MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler(); EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi); Object filterTarget = findFilterTarget(attribute.getFilterTarget(), ctx, mi); expressionHandler.filter(filterTarget, attribute.getExpression(), ctx); return mi.proceed(); } private Object findFilterTarget(String filterTargetName, EvaluationContext ctx, MethodInvocation methodInvocation) { Object filterTarget; if (StringUtils.hasText(filterTargetName)) { filterTarget = ctx.lookupVariable(filterTargetName); Assert.notNull(filterTarget, () -> "Filter target was null, or no argument with name '" + filterTargetName + "' found in method."); } else { Object[] arguments = methodInvocation.getArguments(); Assert.state(arguments.length == 1, "Unable to determine the method argument for filtering. Specify the filter target."); filterTarget = arguments[0]; Assert.notNull(filterTarget, "Filter target was null. Make sure you passing the correct value in the method argument."); }
Assert.state(!filterTarget.getClass().isArray(), "Pre-filtering on array types is not supported. Using a Collection will solve this problem."); return filterTarget; } private Authentication getAuthentication() { Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreFilterAuthorizationMethodInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
KafkaMessageListenerContainer<String, NotificationDispatchResponse> kafkaMessageListenerContainer( ConsumerFactory<String, NotificationDispatchResponse> consumerFactory ) { String replyTopic = synchronousKafkaProperties.replyTopic(); ContainerProperties containerProperties = new ContainerProperties(replyTopic); return new KafkaMessageListenerContainer<>(consumerFactory, containerProperties); } @Bean ReplyingKafkaTemplate<String, NotificationDispatchRequest, NotificationDispatchResponse> replyingKafkaTemplate( ProducerFactory<String, NotificationDispatchRequest> producerFactory, KafkaMessageListenerContainer<String, NotificationDispatchResponse> kafkaMessageListenerContainer ) { Duration replyTimeout = synchronousKafkaProperties.replyTimeout(); var replyingKafkaTemplate = new ReplyingKafkaTemplate<>(producerFactory, kafkaMessageListenerContainer); replyingKafkaTemplate.setDefaultReplyTimeout(replyTimeout); return replyingKafkaTemplate; } @Bean KafkaTemplate<String, NotificationDispatchResponse> kafkaTemplate(ProducerFactory<String, NotificationDispatchResponse> producerFactory) {
return new KafkaTemplate<>(producerFactory); } @Bean KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, NotificationDispatchRequest>> kafkaListenerContainerFactory( ConsumerFactory<String, NotificationDispatchRequest> consumerFactory, KafkaTemplate<String, NotificationDispatchResponse> kafkaTemplate ) { var factory = new ConcurrentKafkaListenerContainerFactory<String, NotificationDispatchRequest>(); factory.setConsumerFactory(consumerFactory); factory.setReplyTemplate(kafkaTemplate); return factory; } }
repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\kafka\synchronous\KafkaConfiguration.java
2
请完成以下Java代码
public abstract class AbstractDelegatingMessageListenerAdapter<T> implements ConsumerSeekAware, DelegatingMessageListener<T> { protected final LogAccessor logger = new LogAccessor(LogFactory.getLog(this.getClass())); // NOSONAR protected final T delegate; //NOSONAR protected final ListenerType delegateType; // NOSONAR private final @Nullable ConsumerSeekAware seekAware; public AbstractDelegatingMessageListenerAdapter(T delegate) { this.delegate = delegate; this.delegateType = ListenerUtils.determineListenerType(delegate); if (delegate instanceof ConsumerSeekAware) { this.seekAware = (ConsumerSeekAware) delegate; } else { this.seekAware = null; } } @Override public T getDelegate() { return this.delegate; } @Override public void registerSeekCallback(ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.registerSeekCallback(callback); } }
@Override public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.onPartitionsAssigned(assignments, callback); } } @Override public void onPartitionsRevoked(@Nullable Collection<TopicPartition> partitions) { if (this.seekAware != null) { this.seekAware.onPartitionsRevoked(partitions); } } @Override public void onIdleContainer(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) { if (this.seekAware != null) { this.seekAware.onIdleContainer(assignments, callback); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\AbstractDelegatingMessageListenerAdapter.java
1
请完成以下Java代码
public void setCharset(@Nullable Charset charset) { this.charset = charset; } /** * Set the name of the charset used for reading Mustache template files. * @param charset the charset * @deprecated since 4.1.0 for removal in 4.3.0 in favor of * {@link #setCharset(Charset)} */ @Deprecated(since = "4.1.0", forRemoval = true) public void setCharset(@Nullable String charset) { setCharset((charset != null) ? Charset.forName(charset) : null); } @Override public boolean checkResource(Locale locale) throws Exception { Resource resource = getResource(); return resource != null; } @Override protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Resource resource = getResource(); Assert.state(resource != null, "'resource' must not be null"); Template template = createTemplate(resource); if (template != null) { template.execute(model, response.getWriter()); } } private @Nullable Resource getResource() { ApplicationContext applicationContext = getApplicationContext(); String url = getUrl(); if (applicationContext == null || url == null) { return null; } Resource resource = applicationContext.getResource(url);
return (resource.exists()) ? resource : null; } private Template createTemplate(Resource resource) throws IOException { try (Reader reader = getReader(resource)) { Assert.state(this.compiler != null, "'compiler' must not be null"); return this.compiler.compile(reader); } } private Reader getReader(Resource resource) throws IOException { if (this.charset != null) { return new InputStreamReader(resource.getInputStream(), this.charset); } return new InputStreamReader(resource.getInputStream()); } }
repos\spring-boot-main\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\servlet\view\MustacheView.java
1
请完成以下Java代码
public Message<?> preSend(Message<?> message, MessageChannel channel) { if (!this.matcher.matches(message)) { return message; } Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); CsrfToken expectedToken = (sessionAttributes != null) ? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null; if (expectedToken == null) { throw new MissingCsrfTokenException(null); } String actualToken = SimpMessageHeaderAccessor.wrap(message) .getFirstNativeHeader(expectedToken.getHeaderName()); String actualTokenValue = XorCsrfTokenUtils.getTokenValue(actualToken, expectedToken.getToken()); boolean csrfCheckPassed = equalsConstantTime(expectedToken.getToken(), actualTokenValue); if (!csrfCheckPassed) { throw new InvalidCsrfTokenException(expectedToken, actualToken); } return message; } /** * Constant time comparison to prevent against timing attacks. * @param expected
* @param actual * @return */ private static boolean equalsConstantTime(String expected, @Nullable String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\web\csrf\XorCsrfChannelInterceptor.java
1
请完成以下Java代码
public List<Execution> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return (List) commandContext .getExecutionManager() .findExecutionsByQueryCriteria(this, page); } //getters //////////////////////////////////////////////////// public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; }
public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) { if (isPasswordLengthInvalid(passwordChangeDto.getNewPassword())) { throw new InvalidPasswordException(); } userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword()); } /** * {@code POST /account/reset-password/init} : Send an email to reset the password of the user. * * @param mail the mail of the user. */ @PostMapping(path = "/account/reset-password/init") public void requestPasswordReset(@RequestBody String mail) { Optional<User> user = userService.requestPasswordReset(mail); if (user.isPresent()) { mailService.sendPasswordResetMail(user.orElseThrow()); } else { // Pretend the request has been successful to prevent checking which emails really exist // but log that an invalid attempt has been made log.warn("Password reset requested for non existing mail"); } } /** * {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
* * @param keyAndPassword the generated key and the new password. * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect. * @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset. */ @PostMapping(path = "/account/reset-password/finish") public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this reset key"); } } private static boolean isPasswordLengthInvalid(String password) { return ( StringUtils.isEmpty(password) || password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH || password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH ); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\web\rest\AccountResource.java
1
请完成以下Java代码
public SqlLookupDescriptorProviderBuilder setAD_Val_Rule_ID(@NonNull final LookupDescriptorProvider.LookupScope scope, @Nullable final AdValRuleId AD_Val_Rule_ID) { if (AD_Val_Rule_ID == null) { adValRuleIdByScope.remove(scope); } else { adValRuleIdByScope.put(scope, AD_Val_Rule_ID); } return this; } public SqlLookupDescriptorProviderBuilder addValidationRule(final IValidationRule validationRule) { additionalValidationRules.add(validationRule);
return this; } public SqlLookupDescriptorProviderBuilder setReadOnlyAccess() { this.requiredAccess = Access.READ; return this; } public SqlLookupDescriptorProviderBuilder setPageLength(final Integer pageLength) { this.pageLength = pageLength; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorProviderBuilder.java
1
请在Spring Boot框架中完成以下Java代码
private ProductId getProductId() { final I_PP_Order_BOMLine coProductLine = getCOProductLine(); if (coProductLine != null) { return ProductId.ofRepoId(coProductLine.getM_Product_ID()); } else { final I_PP_Order ppOrder = getPPOrder(); return ProductId.ofRepoId(ppOrder.getM_Product_ID()); } } @NonNull private Quantity getTotalQtyReceived() { clearLoadedData(); final I_PP_Order_BOMLine ppOrderBomLine = getCOProductLine(); if (ppOrderBomLine != null) { return loadingAndSavingSupportServices.getQuantities(ppOrderBomLine).getQtyIssuedOrReceived().negate(); } return loadingAndSavingSupportServices.getQuantities(getPPOrder()).getQtyReceived(); } private boolean isCoProduct() { return getCOProductLine() != null; } private void setQRCodeAttribute(@NonNull final I_M_HU hu)
{ if (barcode == null) {return;} final IAttributeStorage huAttributes = handlingUnitsBL.getAttributeStorage(hu); if (!huAttributes.hasAttribute(HUAttributeConstants.ATTR_QRCode)) {return;} huAttributes.setSaveOnChange(true); huAttributes.setValue(HUAttributeConstants.ATTR_QRCode, barcode.getAsString()); } private void save() { newSaver().saveActivityStatuses(job); } @NonNull private ManufacturingJobLoaderAndSaver newSaver() {return new ManufacturingJobLoaderAndSaver(loadingAndSavingSupportServices);} private void autoIssueForWhatWasReceived() { job = jobService.autoIssueWhatWasReceived(job, RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\receive\ReceiveGoodsCommand.java
2
请完成以下Java代码
class CookieValue { private final HttpServletRequest request; private final HttpServletResponse response; private final String cookieValue; private int cookieMaxAge = -1; /** * Creates a new instance. * @param request the {@link HttpServletRequest} to use. Useful for determining * the context in which the cookie is set. Cannot be null. * @param response the {@link HttpServletResponse} to use. * @param cookieValue the value of the cookie to be written. This value may be * modified by the {@link CookieSerializer} when writing to the actual cookie so * long as the original value is returned when the cookie is read. */ public CookieValue(HttpServletRequest request, HttpServletResponse response, String cookieValue) { this.request = request; this.response = response; this.cookieValue = cookieValue; if ("".equals(this.cookieValue)) { this.cookieMaxAge = 0; } } /** * Gets the request to use. * @return the request to use. Cannot be null. */ public HttpServletRequest getRequest() { return this.request; } /** * Gets the response to write to. * @return the response to write to. Cannot be null.
*/ public HttpServletResponse getResponse() { return this.response; } /** * The value to be written. This value may be modified by the * {@link CookieSerializer} before written to the cookie. However, the value must * be the same as the original when it is read back in. * @return the value to be written */ public String getCookieValue() { return this.cookieValue; } /** * Get the cookie max age. The default is -1 which signals to delete the cookie * when the browser is closed, or 0 if cookie value is empty. * @return the cookie max age */ public int getCookieMaxAge() { return this.cookieMaxAge; } /** * Set the cookie max age. * @param cookieMaxAge the cookie max age */ public void setCookieMaxAge(int cookieMaxAge) { this.cookieMaxAge = cookieMaxAge; } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\CookieSerializer.java
1
请完成以下Java代码
public void listenGroupFoo(String message) { System.out.println("Received Message in group 'foo': " + message); latch.countDown(); } @KafkaListener(topics = "${message.topic.name}", groupId = "bar", containerFactory = "barKafkaListenerContainerFactory") public void listenGroupBar(String message) { System.out.println("Received Message in group 'bar': " + message); latch.countDown(); } @KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory") public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); latch.countDown(); } @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }), containerFactory = "partitionsKafkaListenerContainerFactory") public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition);
this.partitionLatch.countDown(); } @KafkaListener(topics = "${filtered.topic.name}", containerFactory = "filterKafkaListenerContainerFactory") public void listenWithFilter(String message) { System.out.println("Received Message in filtered listener: " + message); this.filterLatch.countDown(); } @KafkaListener(topics = "${greeting.topic.name}", containerFactory = "greetingKafkaListenerContainerFactory") public void greetingListener(Greeting greeting) { System.out.println("Received greeting message: " + greeting); this.greetingLatch.countDown(); } } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\spring\kafka\KafkaApplication.java
1
请在Spring Boot框架中完成以下Java代码
public DocumentReferenceType getInvoiceReference() { return invoiceReference; } /** * Sets the value of the invoiceReference property. * * @param value * allowed object is * {@link DocumentReferenceType } * */ public void setInvoiceReference(DocumentReferenceType value) { this.invoiceReference = value; } /** * Gets the value of the stockEntryReference property. * * @return * possible object is * {@link DocumentReferenceType } * */ public DocumentReferenceType getStockEntryReference() { return stockEntryReference; } /** * Sets the value of the stockEntryReference property. * * @param value * allowed object is * {@link DocumentReferenceType } * */ public void setStockEntryReference(DocumentReferenceType value) {
this.stockEntryReference = value; } /** * Gets the value of the additionalReferences property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReferences property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReferences().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentReferenceType } * * */ public List<DocumentReferenceType> getAdditionalReferences() { if (additionalReferences == null) { additionalReferences = new ArrayList<DocumentReferenceType>(); } return this.additionalReferences; } } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVRPTListLineItemExtensionType.java
2
请完成以下Java代码
protected String doIt() throws Exception { final TableRecordReference startReference = TableRecordReference.of(adTableStart.getAD_Table_ID(), recordIdStart); final TableRecordReference goalReference = TableRecordReference.of(adTableGoal.getAD_Table_ID(), recordIdGoal); final IDLMService dlmService = Services.get(IDLMService.class); final IRecordCrawlerService recordCrawlerService = Services.get(IRecordCrawlerService.class); final FindPathIterateResult findPathIterateResult = new FindPathIterateResult( startReference, goalReference); final PartitionConfig config = dlmService.loadPartitionConfig(configDB); addLog("Starting at start record={}, searching for goal record={}", startReference, goalReference); recordCrawlerService.crawl(config, this, findPathIterateResult); addLog("Search done. Found goal record: {}", findPathIterateResult.isFoundGoalRecord()); // new GraphUI().showGraph(findPathIterateResult); if (!findPathIterateResult.isFoundGoalRecord()) { addLog("Upable to reach the goal record from the given start using DLM_Partition_Config= {}", config.getName()); return MSG_OK; }
final List<ITableRecordReference> path = findPathIterateResult.getPath(); if (path == null) { addLog("There is no path between start={} and goal={}", startReference, goalReference); return MSG_OK; } addLog("Records that make up the path from start to goal (size={}):", path.size()); for (int i = 0; i < path.size(); i++) { final ITableRecordReference pathElement = path.get(i); pathElement.getModel(this); // make sure the model is loaded and thus shown in the reference's toString output addLog("{}: {}", i, pathElement); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_FindPathBetweenRecords.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } @Transactional public void addAuthorWithBooks() { Author author = new Author(); author.setId(new AuthorId("Alicia Tom", 38)); author.setGenre("Anthology"); Book book1 = new Book(); book1.setIsbn("001-AT"); book1.setTitle("The book of swords"); Book book2 = new Book(); book2.setIsbn("002-AT"); book2.setTitle("Anthology of a day"); Book book3 = new Book(); book3.setIsbn("003-AT"); book3.setTitle("Anthology today"); author.addBook(book1); // use addBook() helper author.addBook(book2); author.addBook(book3); authorRepository.save(author); }
@Transactional(readOnly = true) public void fetchAuthorByName() { Author author = authorRepository.fetchByName("Alicia Tom"); System.out.println(author); } @Transactional public void removeBookOfAuthor() { Author author = authorRepository.fetchWithBooks(new AuthorId("Alicia Tom", 38)); author.removeBook(author.getBooks().get(0)); } @Transactional public void removeAuthor() { authorRepository.deleteById(new AuthorId("Alicia Tom", 38)); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public List<Event> findEventsByTaskId(String taskId) { return getDbSqlSession().selectList("selectEventsByTaskId", taskId); } @Override @SuppressWarnings("unchecked") public List<Event> findEventsByProcessInstanceId(String processInstanceId) { return getDbSqlSession().selectList("selectEventsByProcessInstanceId", processInstanceId); } @Override public void deleteCommentsByTaskId(String taskId) { getDbSqlSession().delete("deleteCommentsByTaskId", taskId, CommentEntityImpl.class); } @Override public void deleteCommentsByProcessInstanceId(String processInstanceId) { getDbSqlSession().delete("deleteCommentsByProcessInstanceId", processInstanceId, CommentEntityImpl.class); } @Override public void bulkDeleteCommentsForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteCommentsForTaskIds", createSafeInValuesList(taskIds), CommentEntityImpl.class); } @Override public void bulkDeleteCommentsForProcessInstanceIds(Collection<String> processInstanceIds) { getDbSqlSession().delete("bulkDeleteCommentsForProcessInstanceIds", createSafeInValuesList(processInstanceIds), CommentEntityImpl.class); } @Override @SuppressWarnings("unchecked") public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) { return getDbSqlSession().selectList("selectCommentsByProcessInstanceId", processInstanceId);
} @Override @SuppressWarnings("unchecked") public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) { Map<String, Object> params = new HashMap<>(); params.put("processInstanceId", processInstanceId); params.put("type", type); return getDbSqlSession().selectListWithRawParameter("selectCommentsByProcessInstanceIdAndType", params); } @Override public Comment findComment(String commentId) { return findById(commentId); } @Override public Event findEvent(String commentId) { return findById(commentId); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisCommentDataManager.java
1
请完成以下Java代码
public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyConfirmedBySupplier (final @Nullable BigDecimal QtyConfirmedBySupplier) { set_ValueNoCheck (COLUMNNAME_QtyConfirmedBySupplier, QtyConfirmedBySupplier); } @Override public BigDecimal getQtyConfirmedBySupplier() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConfirmedBySupplier); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDemand_QtySupply_V_ID (final int QtyDemand_QtySupply_V_ID) { if (QtyDemand_QtySupply_V_ID < 1) set_ValueNoCheck (COLUMNNAME_QtyDemand_QtySupply_V_ID, null); else set_ValueNoCheck (COLUMNNAME_QtyDemand_QtySupply_V_ID, QtyDemand_QtySupply_V_ID); } @Override public int getQtyDemand_QtySupply_V_ID() { return get_ValueAsInt(COLUMNNAME_QtyDemand_QtySupply_V_ID); } @Override public void setQtyForecasted (final @Nullable BigDecimal QtyForecasted) { set_ValueNoCheck (COLUMNNAME_QtyForecasted, QtyForecasted); } @Override public BigDecimal getQtyForecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyForecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyStock (final @Nullable BigDecimal QtyStock) { set_ValueNoCheck (COLUMNNAME_QtyStock, QtyStock); } @Override public BigDecimal getQtyStock() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyStock); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToMove (final @Nullable BigDecimal QtyToMove)
{ set_ValueNoCheck (COLUMNNAME_QtyToMove, QtyToMove); } @Override public BigDecimal getQtyToMove() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToMove); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToProduce (final @Nullable BigDecimal QtyToProduce) { set_ValueNoCheck (COLUMNNAME_QtyToProduce, QtyToProduce); } @Override public BigDecimal getQtyToProduce() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProduce); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyUnconfirmedBySupplier (final @Nullable BigDecimal QtyUnconfirmedBySupplier) { set_ValueNoCheck (COLUMNNAME_QtyUnconfirmedBySupplier, QtyUnconfirmedBySupplier); } @Override public BigDecimal getQtyUnconfirmedBySupplier() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUnconfirmedBySupplier); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_QtyDemand_QtySupply_V.java
1
请在Spring Boot框架中完成以下Java代码
public class CaseDefinitionDto { protected String id; protected String key; protected String category; protected String name; protected int version; protected String resource; protected String deploymentId; protected String tenantId; protected Integer historyTimeToLive; public String getId() { return id; } public String getKey() { return key; } public String getCategory() { return category; } public String getName() { return name; } public int getVersion() { return version; } public String getResource() { return resource; } public String getDeploymentId() { return deploymentId; } public String getTenantId() { return tenantId; }
public Integer getHistoryTimeToLive() { return historyTimeToLive; } public static CaseDefinitionDto fromCaseDefinition(CaseDefinition definition) { CaseDefinitionDto dto = new CaseDefinitionDto(); dto.id = definition.getId(); dto.key = definition.getKey(); dto.category = definition.getCategory(); dto.name = definition.getName(); dto.version = definition.getVersion(); dto.resource = definition.getResourceName(); dto.deploymentId = definition.getDeploymentId(); dto.tenantId = definition.getTenantId(); dto.historyTimeToLive = definition.getHistoryTimeToLive(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\CaseDefinitionDto.java
2
请在Spring Boot框架中完成以下Java代码
public class SentinelConfiguration { @Value("${spring.application.name}") private String applicationName; @Bean public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); } @Bean public ApolloDataSource apolloDataSource(ObjectMapper objectMapper) { // Apollo 配置。这里先写死,推荐后面写到 application.yaml 配置文件中。 String appId = applicationName; // Apollo 项目编号。一般情况下,推荐和 spring.application.name 保持一致 String serverAddress = "http://localhost:8080"; // Apollo Meta 服务器地址 String namespace = "application"; // Apollo 命名空间 String flowRuleKey = "sentinel.flow-rule"; // Apollo 配置项的 KEY // 创建 ApolloDataSource 对象 System.setProperty("app.id", appId); System.setProperty("apollo.meta", serverAddress); ApolloDataSource<List<FlowRule>> apolloDataSource = new ApolloDataSource<>(namespace, flowRuleKey, "",
new Converter<String, List<FlowRule>>() { // 转换器,将读取的 Apollo 配置,转换成 FlowRule 数组 @Override public List<FlowRule> convert(String value) { try { return Arrays.asList(objectMapper.readValue(value, FlowRule[].class)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); // 注册到 FlowRuleManager 中 FlowRuleManager.register2Property(apolloDataSource.getProperty()); return apolloDataSource; } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-apollo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java
2
请完成以下Java代码
public class CashBalanceAvailability2 { @XmlElement(name = "Dt", required = true) protected CashBalanceAvailabilityDate1 dt; @XmlElement(name = "Amt", required = true) protected ActiveOrHistoricCurrencyAndAmount amt; @XmlElement(name = "CdtDbtInd", required = true) @XmlSchemaType(name = "string") protected CreditDebitCode cdtDbtInd; /** * Gets the value of the dt property. * * @return * possible object is * {@link CashBalanceAvailabilityDate1 } * */ public CashBalanceAvailabilityDate1 getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link CashBalanceAvailabilityDate1 } * */ public void setDt(CashBalanceAvailabilityDate1 value) { this.dt = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value
* allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashBalanceAvailability2.java
1
请在Spring Boot框架中完成以下Java代码
private static final String extractRemoteAddr(final HttpServletRequest httpRequest) { try { final String remoteAddr = httpRequest.getRemoteAddr(); if (remoteAddr == null || remoteAddr.isEmpty()) { return MDC_Param_RemoteAddr_DefaultValue; } return remoteAddr; } catch (final Exception e) { return "?"; } } private static final String extractLoggedUser(final HttpServletRequest httpRequest) { try { final UserSession userSession = UserSession.getCurrentOrNull(); if (userSession == null) { return "_noSession"; } if (!userSession.isLoggedIn()) { return "_notLoggedIn"; } else { return extractUserName(userSession); } } catch (final Exception e) { e.printStackTrace(); return "_error"; } } private static final String extractUserName(final UserSession userSession) { final String userName = userSession.getUserName(); if (!Check.isEmpty(userName, true)) { return userName; } final UserId loggedUserId = userSession.getLoggedUserIdIfExists().orElse(null); if (loggedUserId != null) { return String.valueOf(loggedUserId.getRepoId()); }
return "?"; } private static final String extractUserAgent(final HttpServletRequest httpRequest) { try { final String userAgent = httpRequest.getHeader("User-Agent"); return userAgent; } catch (final Exception e) { e.printStackTrace(); return "?"; } } private static final String extractLoggedUserAndRemoteAddr(final String loggedUser, final String remoteAddr) { // NOTE: guard against null parameters, if those at this point they shall not return (loggedUser == null ? "?" : loggedUser) + "/" + (remoteAddr == null ? "?" : remoteAddr); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\ServletLoggingFilter.java
2
请完成以下Java代码
public final class WebServerGracefulShutdownLifecycle implements SmartLifecycle { /** * {@link SmartLifecycle#getPhase() SmartLifecycle phase} in which graceful shutdown * of the web server is performed. * @deprecated as of 4.0.0 in favor of * {@link WebServerApplicationContext#GRACEFUL_SHUTDOWN_PHASE} */ @Deprecated(since = "4.0.0", forRemoval = true) public static final int SMART_LIFECYCLE_PHASE = SmartLifecycle.DEFAULT_PHASE - 1024; private final WebServer webServer; private volatile boolean running; /** * Creates a new {@code WebServerGracefulShutdownLifecycle} that will gracefully shut * down the given {@code webServer}. * @param webServer web server to shut down gracefully */ public WebServerGracefulShutdownLifecycle(WebServer webServer) { this.webServer = webServer; } @Override public void start() { this.running = true; }
@Override public void stop() { throw new UnsupportedOperationException("Stop must not be invoked directly"); } @Override public void stop(Runnable callback) { this.running = false; this.webServer.shutDownGracefully((result) -> callback.run()); } @Override public boolean isRunning() { return this.running; } @Override public int getPhase() { return WebServerApplicationContext.GRACEFUL_SHUTDOWN_PHASE; } @Override public boolean isPauseable() { return false; } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\context\WebServerGracefulShutdownLifecycle.java
1
请完成以下Java代码
private static boolean checkStrings(String ltrim, String rtrim) { boolean result = false; if (ltrimResult.equalsIgnoreCase(ltrim) && rtrimResult.equalsIgnoreCase(rtrim)) result = true; return result; } // Going through the String detecting Whitespaces @Benchmark public boolean whileCharacters() { String ltrim = whileLtrim(src); String rtrim = whileRtrim(src); return checkStrings(ltrim, rtrim); } // replaceAll() and Regular Expressions @Benchmark public boolean replaceAllRegularExpression() { String ltrim = src.replaceAll("^\\s+", ""); String rtrim = src.replaceAll("\\s+$", ""); return checkStrings(ltrim, rtrim); } public static String patternLtrim(String s) { return LTRIM.matcher(s) .replaceAll(""); } public static String patternRtrim(String s) { return RTRIM.matcher(s) .replaceAll(""); } // Pattern matches() with replaceAll @Benchmark public boolean patternMatchesLTtrimRTrim() { String ltrim = patternLtrim(src); String rtrim = patternRtrim(src);
return checkStrings(ltrim, rtrim); } // Guava CharMatcher trimLeadingFrom / trimTrailingFrom @Benchmark public boolean guavaCharMatcher() { String ltrim = CharMatcher.whitespace().trimLeadingFrom(src); String rtrim = CharMatcher.whitespace().trimTrailingFrom(src); return checkStrings(ltrim, rtrim); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { String ltrim = StringUtils.stripStart(src, null); String rtrim = StringUtils.stripEnd(src, null); return checkStrings(ltrim, rtrim); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\trim\LTrimRTrim.java
1
请在Spring Boot框架中完成以下Java代码
public String createCustomer(String email, String token) { String id = null; try { Stripe.apiKey = API_SECRET_KEY; Map<String, Object> customerParams = new HashMap<>(); // add customer unique id here to track them in your web application customerParams.put("description", "Customer for " + email); customerParams.put("email", email); customerParams.put("source", token); // ^ obtained with Stripe.js //create a new customer Customer customer = Customer.create(customerParams); id = customer.getId(); } catch (Exception ex) { ex.printStackTrace(); } return id; } public String createSubscription(String customerId, String plan, String coupon) { String id = null; try { Stripe.apiKey = API_SECRET_KEY; Map<String, Object> item = new HashMap<>(); item.put("price", plan); Map<String, Object> items = new HashMap<>(); items.put("0", item); Map<String, Object> params = new HashMap<>(); params.put("customer", customerId); params.put("items", items); //add coupon if available if (!coupon.isEmpty()) { params.put("coupon", coupon); } Subscription sub = Subscription.create(params); id = sub.getId(); } catch (Exception ex) { ex.printStackTrace(); } return id; } public boolean cancelSubscription(String subscriptionId) { boolean status; try { Stripe.apiKey = API_SECRET_KEY; Subscription sub = Subscription.retrieve(subscriptionId); sub.cancel((SubscriptionCancelParams) null);
status = true; } catch (Exception ex) { ex.printStackTrace(); status = false; } return status; } public Coupon retrieveCoupon(String code) { try { Stripe.apiKey = API_SECRET_KEY; return Coupon.retrieve(code); } catch (Exception ex) { ex.printStackTrace(); } return null; } public String createCharge(String email, String token, int amount) { String id = null; try { Stripe.apiKey = API_SECRET_KEY; Map<String, Object> chargeParams = new HashMap<>(); chargeParams.put("amount", amount); chargeParams.put("currency", "usd"); chargeParams.put("description", "Charge for " + email); chargeParams.put("source", token); // ^ obtained with Stripe.js //create a charge Charge charge = Charge.create(chargeParams); id = charge.getId(); } catch (Exception ex) { ex.printStackTrace(); } return id; } }
repos\springboot-demo-master\stripe\src\main\java\com\et\stripe\service\StripeService.java
2
请完成以下Java代码
public final class PathPatternRequestTransformer implements AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer { @Override public HttpServletRequest transform(HttpServletRequest request) { HttpServletRequest wrapped = new AttributesSupportingHttpServletRequest(request); ServletRequestPathUtils.parseAndCache(wrapped); return wrapped; } private static final class AttributesSupportingHttpServletRequest extends HttpServletRequestWrapper { private final Map<String, Object> attributes = new HashMap<>(); AttributesSupportingHttpServletRequest(HttpServletRequest request) { super(request); } @Override public @Nullable Object getAttribute(String name) { return this.attributes.get(name);
} @Override public void setAttribute(String name, Object value) { this.attributes.put(name, value); } @Override public void removeAttribute(String name) { this.attributes.remove(name); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\PathPatternRequestTransformer.java
1
请完成以下Java代码
public class JobDefinitionResourceImpl implements JobDefinitionResource { protected ProcessEngine engine; protected String jobDefinitionId; public JobDefinitionResourceImpl(ProcessEngine engine, String jobDefinitionId) { this.engine = engine; this.jobDefinitionId = jobDefinitionId; } public JobDefinitionDto getJobDefinition() { ManagementService managementService = engine.getManagementService(); JobDefinition jobDefinition = managementService.createJobDefinitionQuery().jobDefinitionId(jobDefinitionId).singleResult(); if (jobDefinition == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Job Definition with id " + jobDefinitionId + " does not exist"); } return JobDefinitionDto.fromJobDefinition(jobDefinition); } public void updateSuspensionState(JobDefinitionSuspensionStateDto dto) { try { dto.setJobDefinitionId(jobDefinitionId); dto.updateSuspensionState(engine); } catch (IllegalArgumentException e) { String message = String.format("The suspension state of Job Definition with id %s could not be updated due to: %s", jobDefinitionId, e.getMessage()); throw new InvalidRequestException(Status.BAD_REQUEST, e, message); } } public void setJobRetries(RetriesDto dto) { try { SetJobRetriesBuilder builder = engine.getManagementService() .setJobRetries(dto.getRetries()) .jobDefinitionId(jobDefinitionId); if (dto.isDueDateSet()) { builder.dueDate(dto.getDueDate()); } builder.execute(); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } @Override public void setJobPriority(JobDefinitionPriorityDto dto) {
try { ManagementService managementService = engine.getManagementService(); if (dto.getPriority() != null) { managementService.setOverridingJobPriorityForJobDefinition(jobDefinitionId, dto.getPriority(), dto.isIncludeJobs()); } else { if (dto.isIncludeJobs()) { throw new InvalidRequestException(Status.BAD_REQUEST, "Cannot reset priority for job definition " + jobDefinitionId + " with includeJobs=true"); } managementService.clearOverridingJobPriorityForJobDefinition(jobDefinitionId); } } catch (AuthorizationException e) { throw e; } catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\management\JobDefinitionResourceImpl.java
1
请完成以下Java代码
public class UserEntity extends BaseVersionedEntity<User> { @Column(name = ModelConstants.USER_TENANT_ID_PROPERTY) private UUID tenantId; @Column(name = ModelConstants.USER_CUSTOMER_ID_PROPERTY) private UUID customerId; @Enumerated(EnumType.STRING) @Column(name = ModelConstants.USER_AUTHORITY_PROPERTY) private Authority authority; @Column(name = ModelConstants.USER_EMAIL_PROPERTY, unique = true) private String email; @Column(name = ModelConstants.USER_FIRST_NAME_PROPERTY) private String firstName; @Column(name = ModelConstants.USER_LAST_NAME_PROPERTY) private String lastName; @Column(name = ModelConstants.PHONE_PROPERTY) private String phone; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.USER_ADDITIONAL_INFO_PROPERTY) private JsonNode additionalInfo; public UserEntity() { } public UserEntity(User user) { super(user); this.authority = user.getAuthority(); if (user.getTenantId() != null) { this.tenantId = user.getTenantId().getId(); } if (user.getCustomerId() != null) { this.customerId = user.getCustomerId().getId(); } this.email = user.getEmail(); this.firstName = user.getFirstName(); this.lastName = user.getLastName(); this.phone = user.getPhone(); this.additionalInfo = user.getAdditionalInfo(); }
@Override public User toData() { User user = new User(new UserId(this.getUuid())); user.setCreatedTime(createdTime); user.setVersion(version); user.setAuthority(authority); if (tenantId != null) { user.setTenantId(TenantId.fromUUID(tenantId)); } if (customerId != null) { user.setCustomerId(new CustomerId(customerId)); } user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setPhone(phone); user.setAdditionalInfo(additionalInfo); return user; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\UserEntity.java
1
请完成以下Java代码
public Stream<PickingJobStepPickedToHU> stream() {return actualPickedHUs.stream();} @Nullable public PickingJobStepPickedTo removing(final List<PickingJobStepPickedToHU> toRemove) { if (toRemove.isEmpty()) { return this; } final ImmutableList<PickingJobStepPickedToHU> actualPickedHUsNew = this.actualPickedHUs.stream() .filter(pickedHU -> !toRemove.contains(pickedHU)) .collect(ImmutableList.toImmutableList()); if (actualPickedHUsNew.size() == actualPickedHUs.size()) { return this; } if (actualPickedHUsNew.isEmpty() && this.qtyRejected == null) { return null; } return toBuilder().actualPickedHUs(actualPickedHUsNew).build();
} @NonNull public List<HuId> getPickedHuIds() { return actualPickedHUs.stream() .map(PickingJobStepPickedToHU::getActualPickedHU) .map(HUInfo::getId) .collect(ImmutableList.toImmutableList()); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHu() { return actualPickedHUs.stream() .max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickedTo.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<RateLimit> extractRateLimit(final HttpHeaders httpHeaders) { final List<String> rateLimitRemaining = httpHeaders.get(RATE_LIMIT_REMAINING.getValue()); final List<String> rateLimitReset = httpHeaders.get(RATE_LIMIT_RESET.getValue()); if (!Check.isEmpty(rateLimitRemaining) && !Check.isEmpty(rateLimitReset)) { final int remainingReq = NumberUtils.asInteger(rateLimitRemaining.get(0), 0); final long utcSeconds = Long.parseLong(rateLimitReset.get(0)); final LocalDateTime rateLimitResetTimestamp = LocalDateTime.ofEpochSecond(utcSeconds,0, ZoneOffset.UTC); return Optional.of( RateLimit.builder() .remainingReq(remainingReq) .resetDate(rateLimitResetTimestamp) .build() ); } return Optional.empty(); } public void waitForLimitReset(final RateLimit rateLimit) { final long msToLimitReset = MILLIS.between(LocalDateTime.now(ZoneId.of(UTC_TIMEZONE)), rateLimit.getResetDate()); Loggables.withLogger(log, Level.DEBUG).addLog("RateLimitService.waitForLimitReset() with rateLimit: {}, and time to wait {} ms", rateLimit, msToLimitReset); if (msToLimitReset < 0) { //reset timestamp is in the past return; } final int maxTimeToWait = sysConfigBL.getIntValue(MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getName(),
MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getDefaultValue() ); if (msToLimitReset > maxTimeToWait) { throw new AdempiereException("Limit Reset is too far in the future! aborting!") .appendParametersToMessage() .setParameter("RateLimit", rateLimit) .setParameter("MaxMsToWaitForLimitReset", maxTimeToWait); } try { Thread.sleep(msToLimitReset); } catch (final InterruptedException e) { throw new AdempiereException(e.getMessage(), e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\service\RateLimitService.java
2
请在Spring Boot框架中完成以下Java代码
public class CostRevaluationId implements RepoIdAware { @JsonCreator public static CostRevaluationId ofRepoId(final int repoId) { return new CostRevaluationId(repoId); } public static int toRepoId(@Nullable final CostRevaluationId costRevaluationId) { return costRevaluationId != null ? costRevaluationId.getRepoId() : -1; } int repoId;
private CostRevaluationId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_CostRevaluation_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static CostRevaluationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new CostRevaluationId(repoId) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\CostRevaluationId.java
2
请完成以下Java代码
public org.compiere.model.I_AD_Role getAD_Role() { return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class); } @Override public void setAD_Role(final org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } @Override public void setAD_Role_ID (final int AD_Role_ID) { if (AD_Role_ID < 0) set_Value (COLUMNNAME_AD_Role_ID, null); else set_Value (COLUMNNAME_AD_Role_ID, AD_Role_ID); } @Override public int getAD_Role_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_ID); } @Override public void setAD_Role_TableOrg_Access_ID (final int AD_Role_TableOrg_Access_ID) { if (AD_Role_TableOrg_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, AD_Role_TableOrg_Access_ID); } @Override public int getAD_Role_TableOrg_Access_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_TableOrg_Access_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_TableOrg_Access.java
1
请完成以下Java代码
public final IClientUIInvoker setLongOperation(final boolean longOperation) { this.longOperation = longOperation; return this; } protected final boolean isLongOperation() { return longOperation; } @Override public IClientUIInvoker setShowGlassPane(final boolean showGlassPane) { this.showGlassPane = showGlassPane; return this; } protected final boolean isShowGlassPane() { return showGlassPane; } @Override public final IClientUIInvoker setOnFail(OnFail onFail) { Check.assumeNotNull(onFail, "onFail not null"); this.onFail = onFail; return this; } private final OnFail getOnFail() { return onFail; } @Override public final IClientUIInvoker setExceptionHandler(IExceptionHandler exceptionHandler) { Check.assumeNotNull(exceptionHandler, "exceptionHandler not null"); this.exceptionHandler = exceptionHandler; return this; } private final IExceptionHandler getExceptionHandler() { return exceptionHandler; }
@Override public abstract IClientUIInvoker setParentComponent(final Object parentComponent); @Override public abstract IClientUIInvoker setParentComponentByWindowNo(final int windowNo); protected final void setParentComponent(final int windowNo, final Object component) { this.parentWindowNo = windowNo; this.parentComponent = component; } protected final Object getParentComponent() { return parentComponent; } protected final int getParentWindowNo() { return parentWindowNo; } @Override public final IClientUIInvoker setRunnable(final Runnable runnable) { this.runnable = runnable; return this; } private final Runnable getRunnable() { return runnable; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInvoker.java
1
请完成以下Java代码
public class DocLine_CostRevaluation extends DocLine<Doc_CostRevaluation> { private final CostRevaluationLine costRevaluationLine; public DocLine_CostRevaluation(final @NonNull I_M_CostRevaluationLine lineRecord, final @NonNull Doc_CostRevaluation doc) { super(InterfaceWrapperHelper.getPO(lineRecord), doc); costRevaluationLine = CostRevaluationRepository.fromRecord(lineRecord); } public CostAmount getCreateCosts(@NonNull final AcctSchema as) { final CostSegmentAndElement costSegmentAndElement = costRevaluationLine.getCostSegmentAndElement(); if (!AcctSchemaId.equals(costSegmentAndElement.getAcctSchemaId(), as.getId())) { throw new AdempiereException("Accounting schema not matching: " + costRevaluationLine + ", " + as); } if (isReversalLine()) { throw new UnsupportedOperationException(); // TODO impl // return services.createReversalCostDetails(CostDetailReverseRequest.builder() // .acctSchemaId(as.getId()) // .reversalDocumentRef(CostingDocumentRef.ofCostRevaluationLineId(get_ID())) // .initialDocumentRef(CostingDocumentRef.ofCostRevaluationLineId(getReversalLine_ID()))
// .date(getDateAcctAsInstant()) // .build()) // .getTotalAmountToPost(as); } else { return services.createCostDetail( CostDetailCreateRequest.builder() .acctSchemaId(costSegmentAndElement.getAcctSchemaId()) .clientId(costSegmentAndElement.getClientId()) .orgId(costSegmentAndElement.getOrgId()) .productId(costSegmentAndElement.getProductId()) .attributeSetInstanceId(costSegmentAndElement.getAttributeSetInstanceId()) .documentRef(CostingDocumentRef.ofCostRevaluationLineId(costRevaluationLine.getId())) .qty(costRevaluationLine.getCurrentQty().toZero()) .amt(costRevaluationLine.getDeltaAmountToBook()) .explicitCostPrice(costRevaluationLine.getNewCostPrice()) .date(getDateAcctAsInstant()) .build()) .getMainAmountToPost(as); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_CostRevaluation.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** * Status AD_Reference_ID=541011 * Reference name: C_Payment_Reservation_Status */ public static final int STATUS_AD_Reference_ID=541011; /** WAITING_PAYER_APPROVAL = W */ public static final String STATUS_WAITING_PAYER_APPROVAL = "W"; /** APPROVED = A */ public static final String STATUS_APPROVED = "A"; /** VOIDED = V */ public static final String STATUS_VOIDED = "V"; /** COMPLETED = C */
public static final String STATUS_COMPLETED = "C"; /** Set Status. @param Status Status */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; }
public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunEntry.java
1
请完成以下Java代码
public byte[] getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * byte[] */ public void setValue(byte[] value) { this.value = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
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\SignatureValueType.java
1
请完成以下Java代码
public ImmutableCredentialRecordBuilder credentialType(@Nullable PublicKeyCredentialType credentialType) { this.credentialType = credentialType; return this; } public ImmutableCredentialRecordBuilder credentialId(Bytes credentialId) { this.credentialId = credentialId; return this; } public ImmutableCredentialRecordBuilder userEntityUserId(Bytes userEntityUserId) { this.userEntityUserId = userEntityUserId; return this; } public ImmutableCredentialRecordBuilder publicKey(PublicKeyCose publicKey) { this.publicKey = publicKey; return this; } public ImmutableCredentialRecordBuilder signatureCount(long signatureCount) { this.signatureCount = signatureCount; return this; } public ImmutableCredentialRecordBuilder uvInitialized(boolean uvInitialized) { this.uvInitialized = uvInitialized; return this; } public ImmutableCredentialRecordBuilder transports(Set<AuthenticatorTransport> transports) { this.transports = transports; return this; } public ImmutableCredentialRecordBuilder backupEligible(boolean backupEligible) { this.backupEligible = backupEligible; return this; } public ImmutableCredentialRecordBuilder backupState(boolean backupState) { this.backupState = backupState; return this; } public ImmutableCredentialRecordBuilder attestationObject(@Nullable Bytes attestationObject) { this.attestationObject = attestationObject; return this; }
public ImmutableCredentialRecordBuilder attestationClientDataJSON(@Nullable Bytes attestationClientDataJSON) { this.attestationClientDataJSON = attestationClientDataJSON; return this; } public ImmutableCredentialRecordBuilder created(Instant created) { this.created = created; return this; } public ImmutableCredentialRecordBuilder lastUsed(Instant lastUsed) { this.lastUsed = lastUsed; return this; } public ImmutableCredentialRecordBuilder label(String label) { this.label = label; return this; } public ImmutableCredentialRecord build() { return new ImmutableCredentialRecord(this.credentialType, this.credentialId, this.userEntityUserId, this.publicKey, this.signatureCount, this.uvInitialized, this.transports, this.backupEligible, this.backupState, this.attestationObject, this.attestationClientDataJSON, this.created, this.lastUsed, this.label); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutableCredentialRecord.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int age; private String name; private String genre; @Lob private Blob avatar; @Lob private Clob biography; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public Blob getAvatar() { return avatar; } public void setAvatar(Blob avatar) { this.avatar = avatar; } public Clob getBiography() { return biography; } public void setBiography(Clob biography) { this.biography = biography; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMappingLobToClobAndBlob\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public String getExclude() { return this.exclude; } public void setExclude(String exclude) { this.exclude = exclude; } public @Nullable String getAdditionalExclude() { return this.additionalExclude; } public void setAdditionalExclude(@Nullable String additionalExclude) { this.additionalExclude = additionalExclude; } public Duration getPollInterval() { return this.pollInterval; } public void setPollInterval(Duration pollInterval) { this.pollInterval = pollInterval; } public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } public @Nullable String getTriggerFile() { return this.triggerFile; } public void setTriggerFile(@Nullable String triggerFile) { this.triggerFile = triggerFile; } public List<File> getAdditionalPaths() { return this.additionalPaths; } public void setAdditionalPaths(List<File> additionalPaths) { this.additionalPaths = additionalPaths; } public boolean isLogConditionEvaluationDelta() { return this.logConditionEvaluationDelta; } public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) { this.logConditionEvaluationDelta = logConditionEvaluationDelta; } }
/** * LiveReload properties. */ public static class Livereload { /** * Whether to enable a livereload.com-compatible server. */ private boolean enabled; /** * Server port. */ private int port = 35729; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
2
请完成以下Java代码
void triggerReload() throws IOException { if (this.webSocket) { logger.debug("Triggering LiveReload"); writeWebSocketFrame(new Frame("{\"command\":\"reload\",\"path\":\"/\"}")); } } private void writeWebSocketFrame(Frame frame) throws IOException { frame.write(this.outputStream); } private String getWebsocketAcceptResponse() throws NoSuchAlgorithmException { Matcher matcher = WEBSOCKET_KEY_PATTERN.matcher(this.header); Assert.state(matcher.find(), "No Sec-WebSocket-Key"); String response = matcher.group(1).trim() + WEBSOCKET_GUID;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(response.getBytes(), 0, response.length()); return Base64.getEncoder().encodeToString(messageDigest.digest()); } /** * Close the connection. * @throws IOException in case of I/O errors */ void close() throws IOException { this.running = false; this.socket.close(); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\Connection.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxConnections() { return this.maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public int getMaxMessageCount() { return this.maxMessageCount; } public void setMaxMessageCount(int maxMessageCount) { this.maxMessageCount = maxMessageCount; } public int getMaxThreads() { return this.maxThreads; } public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; } public int getMaxTimeBetweenPings() { return this.maxTimeBetweenPings; } public void setMaxTimeBetweenPings(int maxTimeBetweenPings) { this.maxTimeBetweenPings = maxTimeBetweenPings; } public int getMessageTimeToLive() { return this.messageTimeToLive; } public void setMessageTimeToLive(int messageTimeToLive) { this.messageTimeToLive = messageTimeToLive; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public int getSocketBufferSize() { return this.socketBufferSize; }
public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } public int getSubscriptionCapacity() { return this.subscriptionCapacity; } public void setSubscriptionCapacity(int subscriptionCapacity) { this.subscriptionCapacity = subscriptionCapacity; } public String getSubscriptionDiskStoreName() { return this.subscriptionDiskStoreName; } public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) { this.subscriptionDiskStoreName = subscriptionDiskStoreName; } public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() { return this.subscriptionEvictionPolicy; } public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) { this.subscriptionEvictionPolicy = subscriptionEvictionPolicy; } public boolean isTcpNoDelay() { return this.tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
2
请完成以下Java代码
public String getInstrId() { return instrId; } /** * Sets the value of the instrId property. * * @param value * allowed object is * {@link String } * */ public void setInstrId(String value) { this.instrId = value; } /** * Gets the value of the endToEndId property. * * @return * possible object is * {@link String } * */
public String getEndToEndId() { return endToEndId; } /** * Sets the value of the endToEndId property. * * @param value * allowed object is * {@link String } * */ public void setEndToEndId(String value) { this.endToEndId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentIdentification1.java
1
请完成以下Java代码
private boolean isJustProcessed(final PO po, final int changeType) { if (!po.isActive()) { return false; } final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW; final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed); final boolean processedColumnAvailable = idxProcessed > 0; final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true; if (processedColumnAvailable) { if (isNew) { return processed; }
else if (po.is_ValueChanged(idxProcessed)) { return processed; } else { return false; } } else // Processed column is not available { // If is not available, we always consider the record as processed right after it was created // This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters) return isNew; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java
1
请完成以下Java代码
public class BatchManager extends AbstractManager { public void insertBatch(BatchEntity batch) { batch.setCreateUserId(getCommandContext().getAuthenticatedUserId()); getDbEntityManager().insert(batch); } public BatchEntity findBatchById(String id) { return getDbEntityManager().selectById(BatchEntity.class, id); } public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) { configureQuery(batchQuery); return (Long) getDbEntityManager().selectOne("selectBatchCountByQueryCriteria", batchQuery); } @SuppressWarnings("unchecked") public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery, Page page) { configureQuery(batchQuery); return getDbEntityManager().selectList("selectBatchesByQueryCriteria", batchQuery, page); }
public void updateBatchSuspensionStateById(String batchId, SuspensionState suspensionState) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("batchId", batchId); parameters.put("suspensionState", suspensionState.getStateCode()); ListQueryParameterObject queryParameter = new ListQueryParameterObject(); queryParameter.setParameter(parameters); getDbEntityManager().update(BatchEntity.class, "updateBatchSuspensionStateByParameters", queryParameter); } protected void configureQuery(BatchQueryImpl batchQuery) { getAuthorizationManager().configureBatchQuery(batchQuery); getTenantManager().configureQuery(batchQuery); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\BatchManager.java
1
请完成以下Spring Boot application配置
spring.application.name=spring-security spring.datasource.url= jdbc:h2:file:C:/your_folder_here/test;DB_CLOSE_DELAY=-1;IFEXISTS=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=qwerty spring.h2.conso
le.enabled=true spring.h2.console.path=/h2-console spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-url-http-method-auth\src\main\resources\application.properties
2
请完成以下Java代码
private BPartnerOrderParams ofRecord( @NonNull final I_C_BPartner billBPartnerRecord, @NonNull final I_C_BPartner shipBPartnerRecord, @NonNull final SOTrx soTrx) { final BPartnerEffective billBPartnerEffective = bPartnerEffectiveBL.getByRecord(billBPartnerRecord); final BPartnerEffective shipBPartnerEffective = bPartnerEffectiveBL.getByRecord(shipBPartnerRecord); return BPartnerOrderParams.builder() .deliveryRule(getDeliveryRuleOrNull(shipBPartnerRecord, soTrx)) .deliveryViaRule(getDeliveryViaRuleOrNull(shipBPartnerRecord, soTrx)) .freightCostRule(getFreightCostRule(shipBPartnerRecord)) .invoiceRule(billBPartnerEffective.getInvoiceRule(soTrx)) .paymentRule(getPaymentRule(billBPartnerEffective, soTrx)) .paymentTermId(billBPartnerEffective.getPaymentTermId(soTrx)) .pricingSystemId(billBPartnerEffective.getPricingSystemId(soTrx)) .shipperId(getShipperId(shipBPartnerRecord)) //FIXME doesn't consider possibility of overwrite in c_bp_location .isAutoInvoice(billBPartnerEffective.isAutoInvoice(soTrx)) .incoterms(shipBPartnerEffective.getIncoterms(soTrx)) .build(); } private Optional<FreightCostRule> getFreightCostRule(@NonNull final I_C_BPartner bpartnerRecord) { return Optional.ofNullable(FreightCostRule.ofNullableCode(bpartnerRecord.getFreightCostRule())); } private Optional<DeliveryRule> getDeliveryRuleOrNull(@NonNull final I_C_BPartner bpartnerRecord, @NonNull final SOTrx soTrx) { if (soTrx.isSales()) { return Optional.ofNullable(DeliveryRule.ofNullableCode(bpartnerRecord.getDeliveryRule())); } return Optional.empty(); // shall not happen } private Optional<DeliveryViaRule> getDeliveryViaRuleOrNull(@NonNull final I_C_BPartner bpartnerRecord, @NonNull final SOTrx soTrx) { if (soTrx.isSales())
{ return Optional.ofNullable(DeliveryViaRule.ofNullableCode(bpartnerRecord.getDeliveryViaRule())); } else if (soTrx.isPurchase()) { return Optional.ofNullable(DeliveryViaRule.ofNullableCode(bpartnerRecord.getPO_DeliveryViaRule())); } return Optional.empty(); // shall not happen } private Optional<ShipperId> getShipperId(@NonNull final I_C_BPartner bpartnerRecord) { final int shipperId = bpartnerRecord.getM_Shipper_ID(); return Optional.ofNullable(ShipperId.ofRepoIdOrNull(shipperId)); } private PaymentRule getPaymentRule(@NonNull final BPartnerEffective bpartnerRecord, @NonNull final SOTrx soTrx) { // note that we fall back to a default because while the column is mandatory in the DB, it might be null in unit tests final PaymentRule paymentRule = bpartnerRecord.getPaymentRule(soTrx); if (soTrx.isSales() && paymentRule.isCashOrCheck()) // No Cash/Check/Transfer: { // for SO_Trx return PaymentRule.OnCredit; // Payment Term } if (soTrx.isPurchase() && paymentRule.isCash()) // No Cash for PO_Trx { return PaymentRule.OnCredit; // Payment Term } return paymentRule; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\BPartnerOrderParamsRepository.java
1
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String url = WebUtils.getSourceUrl(request); String host = WebUtils.getHost(url); assert host != null; if (isNotTrustHost(host)) { String html = this.notTrustHostHtmlView.replace("${current_host}", host); response.getWriter().write(html); response.getWriter().close(); } else { chain.doFilter(request, response); } } public boolean isNotTrustHost(String host) { // 如果配置了黑名单,优先检查黑名单 if (CollectionUtils.isNotEmpty(ConfigConstants.getNotTrustHostSet())) { return ConfigConstants.getNotTrustHostSet().contains(host); } // 如果配置了白名单,检查是否在白名单中 if (CollectionUtils.isNotEmpty(ConfigConstants.getTrustHostSet())) { // 支持通配符 * 表示允许所有主机 if (ConfigConstants.getTrustHostSet().contains("*")) { logger.debug("允许所有主机访问(通配符模式): {}", host); return false; }
return !ConfigConstants.getTrustHostSet().contains(host); } // 安全加固:默认拒绝所有未配置的主机(防止SSRF攻击) // 如果需要允许所有主机,请在配置文件中明确设置 trust.host = * logger.warn("未配置信任主机列表,拒绝访问主机: {},请在配置文件中设置 trust.host 或 KK_TRUST_HOST 环境变量", host); return true; } @Override public void destroy() { } }
repos\kkFileView-master\server\src\main\java\cn\keking\web\filter\TrustHostFilter.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Role. @return Responsibility Role */ public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID)
{ if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_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_CM_AccessListRole.java
1
请完成以下Java代码
public boolean isMysql() { return dbSqlSessionFactory.getDatabaseType().equals("mysql"); } public boolean isMariaDb() { return dbSqlSessionFactory.getDatabaseType().equals("mariadb"); } public boolean isOracle() { return dbSqlSessionFactory.getDatabaseType().equals("oracle"); } // query factory methods // //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ModelQueryImpl createModelQueryImpl() { return new ModelQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); } public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); } public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请完成以下Java代码
public void onError(String params, Exception e) { if (e instanceof TimeoutException || e instanceof org.eclipse.leshan.core.request.exception.TimeoutException) { client.setLastSentRpcId(null); transportService.process(client.getSession(), this.request, RpcStatus.TIMEOUT, TransportServiceCallback.EMPTY); } else if (!(e instanceof ClientSleepingException)) { sendRpcReplyOnError(e); } if (callback != null) { callback.onError(params, e); } } protected void reply(LwM2MRpcResponseBody response) { TransportProtos.ToDeviceRpcResponseMsg.Builder msg = TransportProtos.ToDeviceRpcResponseMsg.newBuilder().setRequestId(request.getRequestId()); String responseAsString = JacksonUtil.toString(response); if (StringUtils.isEmpty(response.getError())) { msg.setPayload(responseAsString); } else { msg.setError(responseAsString); } transportService.process(client.getSession(), msg.build(), null); }
abstract protected void sendRpcReplyOnSuccess(T response); protected void sendRpcReplyOnValidationError(String msg) { reply(LwM2MRpcResponseBody.builder().result(ResponseCode.BAD_REQUEST.getName()).error(msg).build()); } protected void sendRpcReplyOnError(Exception e) { String error = e.getMessage(); if (error == null) { error = e.toString(); } reply(LwM2MRpcResponseBody.builder().result(ResponseCode.INTERNAL_SERVER_ERROR.getName()).error(error).build()); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\rpc\RpcDownlinkRequestCallbackProxy.java
1
请完成以下Java代码
public String checkHostname() { String hostname; try { hostname = getHostname(); } catch (UnknownHostException e) { throw LOG.cannotGetHostnameException(e); } return hostname; } public String getHostname() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } public String getBaseUrl() { return urlResolver.getBaseUrl(); } protected String getWorkerId() { return workerId; } protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; }
public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; } public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setData(String data) { this.data = data; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getIdPrefix() { // id prefix is empty because sequence is used instead of id prefix return ""; } @Override public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public long getLogNumber() { return logNumber; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override
public String getData() { return data; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } @Override public boolean equals(Object obj) { if (this == obj) { return true;
} if(obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } IdGenBook other = (IdGenBook) obj; return id != null && id.equals(other.getId()); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\IdGenBook.java
1
请完成以下Java代码
public DbOperation addRemovalTimeToCommentsByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(CommentEntity.class, "updateCommentsByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToCommentsByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(CommentEntity.class, "updateCommentsByProcessInstanceId", parameters);
} public DbOperation deleteCommentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(CommentEntity.class, "deleteCommentsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentManager.java
1
请在Spring Boot框架中完成以下Java代码
public CronTriggerFactoryBean executeJobTrigger(@Qualifier("executeJobDetail") JobDetail jobDetail) { //每天凌晨3点执行 return cronTriggerFactoryBean(jobDetail, "0 1 0 * * ? "); } /** * 加载job * * 新建job 类用来代理 * * * @return */ @Bean public JobDetailFactoryBean executeJobDetail() { return createJobDetail(InvokingJobDetailFactory.class, GROUP_NAME, "executeJob"); } /** * 执行规则job工厂 * * 配置job 类中需要定时执行的 方法 execute
* @param jobClass * @param groupName * @param targetObject * @return */ private static JobDetailFactoryBean createJobDetail(Class<? extends Job> jobClass, String groupName, String targetObject) { JobDetailFactoryBean factoryBean = new JobDetailFactoryBean(); factoryBean.setJobClass(jobClass); factoryBean.setDurability(true); factoryBean.setRequestsRecovery(true); factoryBean.setGroup(groupName); Map<String, String> map = new HashMap<>(); map.put("targetMethod", "execute"); map.put("targetObject", targetObject); factoryBean.setJobDataAsMap(map); return factoryBean; } }
repos\springBoot-master\springboot-Quartz\src\main\java\com\abel\quartz\config\QuartzConfig.java
2
请完成以下Java代码
public int getRowCount() { return (int)view.size(); } } private static class ListRowsSupplier implements RowsSupplier { private final ImmutableList<IViewRow> rows; private ListRowsSupplier(@NonNull final IView view, @NonNull final DocumentIdsSelection rowIds) { Check.assume(!rowIds.isAll(), "rowIds is not ALL"); this.rows = view.streamByIds(rowIds).collect(ImmutableList.toImmutableList()); } @Override public IViewRow getRow(final int rowIndex) { Check.assume(rowIndex >= 0, "rowIndex >= 0"); final int rowsCount = rows.size(); Check.assume(rowIndex < rowsCount, "rowIndex < {}", rowsCount); return rows.get(rowIndex); }
@Override public int getRowCount() { return rows.size(); } } @Override protected List<CellValue> getNextRow() { final ArrayList<CellValue> result = new ArrayList<>(); for (int i = 0; i < getColumnCount(); i++) { result.add(getValueAt(rowNumber, i)); } rowNumber++; return result; } @Override protected boolean hasNextRow() { return rowNumber < getRowCount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewExcelExporter.java
1
请在Spring Boot框架中完成以下Java代码
public void updateModifiableFieldsFromEntity(DecisionRequirementsDefinitionEntity updatingDefinition) { } /** * Returns the cached version if exists; does not update the entity from the database in that case */ protected DecisionRequirementsDefinitionEntity loadDecisionRequirementsDefinition(String decisionRequirementsDefinitionId) { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); DeploymentCache deploymentCache = configuration.getDeploymentCache(); DecisionRequirementsDefinitionEntity decisionRequirementsDefinition = deploymentCache.findDecisionRequirementsDefinitionFromCache(decisionRequirementsDefinitionId); if (decisionRequirementsDefinition == null) { CommandContext commandContext = Context.getCommandContext(); DecisionRequirementsDefinitionManager manager = commandContext.getDecisionRequirementsDefinitionManager(); decisionRequirementsDefinition = manager.findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); if (decisionRequirementsDefinition != null) { decisionRequirementsDefinition = deploymentCache.resolveDecisionRequirementsDefinition(decisionRequirementsDefinition); } } return decisionRequirementsDefinition; } public String getPreviousDecisionRequirementsDefinitionId() { ensurePreviousDecisionRequirementsDefinitionIdInitialized(); return previousDecisionRequirementsDefinitionId; } public void setPreviousDecisionDefinitionId(String previousDecisionDefinitionId) { this.previousDecisionRequirementsDefinitionId = previousDecisionDefinitionId;
} protected void resetPreviousDecisionRequirementsDefinitionId() { previousDecisionRequirementsDefinitionId = null; ensurePreviousDecisionRequirementsDefinitionIdInitialized(); } protected void ensurePreviousDecisionRequirementsDefinitionIdInitialized() { if (previousDecisionRequirementsDefinitionId == null && !firstVersion) { previousDecisionRequirementsDefinitionId = Context .getCommandContext() .getDecisionRequirementsDefinitionManager() .findPreviousDecisionRequirementsDefinitionId(key, version, tenantId); if (previousDecisionRequirementsDefinitionId == null) { firstVersion = true; } } } public void setHistoryTimeToLive(Integer historyTimeToLive) { throw new UnsupportedOperationException(); } @Override public String toString() { return "DecisionRequirementsDefinitionEntity [id=" + id + ", revision=" + revision + ", name=" + name + ", category=" + category + ", key=" + key + ", version=" + version + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionEntity.java
2
请完成以下Java代码
public class MongoAppender extends AppenderSkeleton { private MongoClient mongoClient; private MongoDatabase mongoDatabase; private MongoCollection<BasicDBObject> logsCollection; private String connectionUrl; private String databaseName; private String collectionName; @Override protected void append(LoggingEvent loggingEvent) { if(mongoDatabase == null) { MongoClientURI connectionString = new MongoClientURI(connectionUrl); mongoClient = new MongoClient(connectionString); mongoDatabase = mongoClient.getDatabase(databaseName); logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class); } logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage()); } @Override public void close() { if(mongoClient != null) { mongoClient.close(); } } @Override public boolean requiresLayout() { return false; }
public String getConnectionUrl() { return connectionUrl; } public void setConnectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getCollectionName() { return collectionName; } public void setCollectionName(String collectionName) { this.collectionName = collectionName; } }
repos\SpringBoot-Learning-master\1.x\Chapter4-2-5\src\main\java\com\didispace\log\MongoAppender.java
1
请在Spring Boot框架中完成以下Java代码
public static LanguageKey ofString(@NonNull final String languageInfo) { final String separator = languageInfo.contains("-") ? "-" : "_"; final String[] localeParts = languageInfo.trim().split(separator); if (localeParts.length == 0) { // shall not happen throw new IllegalArgumentException("Invalid languageInfo: " + languageInfo); } else if (localeParts.length == 1) { final String language = localeParts[0]; final String country = ""; final String variant = ""; return new LanguageKey(language, country, variant); } else if (localeParts.length == 2) { final String language = localeParts[0]; final String country = localeParts[1]; final String variant = ""; return new LanguageKey(language, country, variant); } else // if (localeParts.length >= 3) { final String language = localeParts[0]; final String country = localeParts[1]; final String variant = localeParts[2]; return new LanguageKey(language, country, variant); } } public static LanguageKey ofLocale(@NonNull final Locale locale) { return new LanguageKey(locale.getLanguage(), locale.getCountry(), locale.getVariant()); } public static LanguageKey getDefault() { return ofLocale(Locale.getDefault()); } @NonNull String language; @NonNull String country; @NonNull String variant;
public Locale toLocale() { return new Locale(language, country, variant); } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { final StringBuilder sb = new StringBuilder(); sb.append(language); if (!country.isBlank()) { sb.append("_").append(country); } if (!variant.isBlank()) { sb.append("_").append(variant); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\LanguageKey.java
2
请在Spring Boot框架中完成以下Java代码
public class ProxyResponseAutoConfiguration implements WebFluxConfigurer { @Autowired private ApplicationContext context; @Bean @ConditionalOnMissingBean public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver(Optional<WebClient.Builder> optional, ProxyExchangeWebfluxProperties properties) { WebClient.Builder builder = optional.orElse(WebClient.builder()); WebClient template = builder.build(); ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver(template); resolver.setHeaders(properties.convertHeaders()); resolver.setAutoForwardedHeaders(properties.getAutoForward()); Set<String> excludedHeaderNames = new HashSet<>(); if (!CollectionUtils.isEmpty(properties.getSensitive())) { excludedHeaderNames.addAll(properties.getSensitive());
} if (!CollectionUtils.isEmpty(properties.getSkipped())) { excludedHeaderNames.addAll(properties.getSkipped()); } resolver.setExcluded(excludedHeaderNames); return resolver; } @Override public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { WebFluxConfigurer.super.configureArgumentResolvers(configurer); configurer.addCustomResolver(context.getBean(ProxyExchangeArgumentResolver.class)); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\config\ProxyResponseAutoConfiguration.java
2
请完成以下Java代码
public void changeState() { if (runtimeService == null) { throw new FlowableException("RuntimeService cannot be null, Obtain your builder instance from the RuntimeService to access this feature"); } runtimeService.changeActivityState(this); } public String getProcessInstanceId() { return processInstanceId; } public List<MoveExecutionIdContainer> getMoveExecutionIdList() { return moveExecutionIdList; } public List<MoveActivityIdContainer> getMoveActivityIdList() {
return moveActivityIdList; } public List<EnableActivityIdContainer> getEnableActivityIdList() { return enableActivityIdList; } public Map<String, Object> getProcessInstanceVariables() { return processVariables; } public Map<String, Map<String, Object>> getLocalVariables() { return localVariables; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ChangeActivityStateBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<UserVO> get(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return Mono.just(user); } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get2") public Mono<CommonResult<UserVO>> get2(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return Mono.just(CommonResult.success(user)); } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get3") public UserVO get3(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return user; } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get4") public CommonResult<UserVO> get4(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id);
// 返回 return CommonResult.success(user); } /** * 测试抛出 NullPointerException 异常 */ @GetMapping("/exception-01") public UserVO exception01() { throw new NullPointerException("没有粗面鱼丸"); } /** * 测试抛出 ServiceException 异常 */ @GetMapping("/exception-02") public UserVO exception02() { throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND); } // @PostMapping(value = "/add", // // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 // consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, // // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 // produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} // ) @PostMapping(value = "/add", // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 consumes = {MediaType.APPLICATION_XML_VALUE}, // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 produces = {MediaType.APPLICATION_XML_VALUE} ) // @PostMapping(value = "/add") public Mono<UserVO> add(@RequestBody Mono<UserVO> user) { return user; } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请完成以下Java代码
public String getName() { return title; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [title="); builder.append(title); builder.append(", tenantId="); builder.append(tenantId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country); builder.append(", state="); builder.append(state); builder.append(", city=");
builder.append(city); builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java
1
请完成以下Java代码
public class AuthorizationResourceImpl extends AbstractAuthorizedRestResource implements AuthorizationResource { protected final AuthorizationService authorizationService; protected String relativeRootResourcePath; public AuthorizationResourceImpl(String processEngineName, String resourceId, String relativeRootResourcePath, ObjectMapper objectMapper) { super(processEngineName, AUTHORIZATION, resourceId, objectMapper); this.relativeRootResourcePath = relativeRootResourcePath; authorizationService = getProcessEngine().getAuthorizationService(); } public AuthorizationDto getAuthorization(UriInfo context) { Authorization dbAuthorization = getDbAuthorization(); return AuthorizationDto.fromAuthorization(dbAuthorization, getProcessEngine().getProcessEngineConfiguration()); } public void deleteAuthorization() { Authorization dbAuthorization = getDbAuthorization(); authorizationService.deleteAuthorization(dbAuthorization.getId()); } public void updateAuthorization(AuthorizationDto dto) { // get db auth Authorization dbAuthorization = getDbAuthorization(); // copy values from dto AuthorizationDto.update(dto, dbAuthorization, getProcessEngine().getProcessEngineConfiguration()); // save authorizationService.saveAuthorization(dbAuthorization); } public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); URI uri = context.getBaseUriBuilder() .path(relativeRootResourcePath)
.path(AuthorizationRestService.PATH) .path(resourceId) .build(); dto.addReflexiveLink(uri, HttpMethod.GET, "self"); if (isAuthorized(DELETE)) { dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); } if (isAuthorized(UPDATE)) { dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); } return dto; } // utils ////////////////////////////////////////////////// protected Authorization getDbAuthorization() { Authorization dbAuthorization = authorizationService.createAuthorizationQuery() .authorizationId(resourceId) .singleResult(); if (dbAuthorization == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Authorization with id " + resourceId + " does not exist."); } else { return dbAuthorization; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\authorization\impl\AuthorizationResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
private void cleanUp(TenantId tenantId) { if (!partitionService.resolve(ServiceType.TB_CORE, tenantId, tenantId).isMyPartition()) { return; } Optional<DefaultTenantProfileConfiguration> tenantProfileConfiguration = tenantProfileCache.get(tenantId).getProfileConfiguration(); if (tenantProfileConfiguration.isEmpty() || tenantProfileConfiguration.get().getAlarmsTtlDays() == 0) { return; } long ttl = TimeUnit.DAYS.toMillis(tenantProfileConfiguration.get().getAlarmsTtlDays()); long expirationTime = System.currentTimeMillis() - ttl; PageLink removalBatchRequest = new PageLink(removalBatchSize, 0); long totalRemoved = 0; Set<String> typesToRemove = new HashSet<>(); while (true) { PageData<AlarmId> toRemove = alarmDao.findAlarmsIdsByEndTsBeforeAndTenantId(expirationTime, tenantId, removalBatchRequest); for (AlarmId alarmId : toRemove.getData()) { Alarm alarm = alarmService.delAlarm(tenantId, alarmId, false).getAlarm(); if (alarm != null) { entityActionService.pushEntityActionToRuleEngine(alarm.getOriginator(), alarm, tenantId, null, ActionType.ALARM_DELETE, null); totalRemoved++; typesToRemove.add(alarm.getType()); }
} if (!toRemove.hasNext()) { break; } } alarmService.delAlarmTypes(tenantId, typesToRemove); if (totalRemoved > 0) { getLogger().info("Removed {} outdated alarm(s) for tenant {} older than {}", totalRemoved, tenantId, new Date(expirationTime)); } } // wrapper for tests to spy on static logger Logger getLogger() { return log; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\AlarmsCleanUpService.java
2
请完成以下Java代码
public Method functionMethod() { if (method != null) { return method; } method = findMethod(functionName); return method; } // Helper methods protected static Object getVariableValue(VariableContainer variableContainer, String variableName) { if (variableName == null) { throw new FlowableIllegalArgumentException("Variable name passed is null"); } return variableContainer.getVariable(variableName); } protected static boolean valuesAreNumbers(Object variableValue, Object actualValue) { return actualValue instanceof Number && variableValue instanceof Number; } @Override public Collection<String> getFunctionNames() { Collection<String> functionNames = new LinkedHashSet<>(); for (String functionPrefix : prefixes()) { for (String functionNameOption : localNames()) { functionNames.add(functionPrefix + ":" + functionNameOption); } } return functionNames; } @Override public AstFunction createFunction(String name, int index, AstParameters parameters, boolean varargs, FlowableExpressionParser parser) {
Method method = functionMethod(); int parametersCardinality = parameters.getCardinality(); int methodParameterCount = method.getParameterCount(); if (method.isVarArgs() || parametersCardinality < methodParameterCount) { // If the method is a varargs or the number of parameters is less than the defined in the method // then create an identifier for the variableContainer // and analyze the parameters List<AstNode> newParameters = new ArrayList<>(parametersCardinality + 1); newParameters.add(parser.createIdentifier(variableScopeName)); if (methodParameterCount >= 1) { // If the first parameter is an identifier we have to convert it to a text node // We want to allow writing variables:get(varName) where varName is without quotes newParameters.add(createVariableNameNode(parameters.getChild(0))); for (int i = 1; i < parametersCardinality; i++) { // the rest of the parameters should be treated as is newParameters.add(parameters.getChild(i)); } } return new AstFunction(name, index, new AstParameters(newParameters), varargs); } else { // If the resolved parameters are of the same size as the current method then nothing to do return new AstFunction(name, index, parameters, varargs); } } protected AstNode createVariableNameNode(AstNode variableNode) { if (variableNode instanceof AstIdentifier) { return new AstText(((AstIdentifier) variableNode).getName()); } else { return variableNode; } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\AbstractFlowableVariableExpressionFunction.java
1
请完成以下Java代码
private I_M_PriceList_Version toPriceListVersionRecord(@NonNull final PriceListVersion request) { final I_M_PriceList_Version existingRecord = getRecordById(request.getPriceListVersionId()); existingRecord.setAD_Org_ID(request.getOrgId().getRepoId()); existingRecord.setM_PriceList_ID(request.getPriceListId().getRepoId()); existingRecord.setValidFrom(TimeUtil.asTimestamp(request.getValidFrom())); existingRecord.setIsActive(request.getIsActive()); existingRecord.setDescription(request.getDescription()); return existingRecord; } @NonNull private I_M_PriceList_Version getRecordById(@NonNull final PriceListVersionId priceListVersionId) { return queryBL.createQueryBuilder(I_M_PriceList_Version.class) .addEqualsFilter(I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, priceListVersionId.getRepoId()) .create() .firstOnlyNotNull(I_M_PriceList_Version.class);
} @NonNull private PriceListVersion toPriceListVersion(@NonNull final I_M_PriceList_Version record) { return PriceListVersion.builder() .priceListVersionId(PriceListVersionId.ofRepoId(record.getM_PriceList_Version_ID())) .priceListId(PriceListId.ofRepoId(record.getM_PriceList_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .description(record.getDescription()) .validFrom(TimeUtil.asInstant(record.getValidFrom())) .isActive(record.isActive()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\pricelist\PriceListVersionRepository.java
1
请完成以下Java代码
public int getMD_Cockpit_ID() { return get_ValueAsInt(COLUMNNAME_MD_Cockpit_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQtyPending (final BigDecimal QtyPending) { set_Value (COLUMNNAME_QtyPending, QtyPending); } @Override public BigDecimal getQtyPending() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPending); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DDOrder_Detail.java
1
请完成以下Java代码
public boolean isPassiva() { String accountType = getAccountType(); return (ACCOUNTTYPE_Liability.equals(accountType) || ACCOUNTTYPE_OwnerSEquity.equals(accountType)); } // isPassiva @Override public String toString() { return getValue() + " - " + getName(); } /** * Extended String Representation * * @return info */ public String toStringX() { return "MElementValue[" + get_ID() + "," + getValue() + " - " + getName() + "]"; } @Override protected boolean beforeSave(boolean newRecord) { // // Transform to summary level account if (!newRecord && isSummary() && is_ValueChanged(COLUMNNAME_IsSummary)) { // // Check if we have accounting facts boolean match = new Query(getCtx(), I_Fact_Acct.Table_Name, I_Fact_Acct.COLUMNNAME_Account_ID + "=?", ITrx.TRXNAME_ThreadInherited) .setParameters(getC_ElementValue_ID()) .anyMatch(); if (match) { throw new AdempiereException("@AlreadyPostedTo@"); } // // Check Valid Combinations - teo_sarca FR [ 1883533 ] String whereClause = MAccount.COLUMNNAME_Account_ID + "=?"; POResultSet<MAccount> rs = new Query(getCtx(), MAccount.Table_Name, whereClause, ITrx.TRXNAME_ThreadInherited) .setParameters(getC_ElementValue_ID()) .scroll(); try { while (rs.hasNext()) { rs.next().deleteEx(true); } } finally
{ DB.close(rs); } } return true; } // beforeSave @Override protected boolean afterSave(boolean newRecord, boolean success) { // Value/Name change if (!newRecord && (is_ValueChanged(COLUMNNAME_Value) || is_ValueChanged(COLUMNNAME_Name))) { MAccount.updateValueDescription(getCtx(), "Account_ID=" + getC_ElementValue_ID(), get_TrxName()); if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList1.getCode()))) { MAccount.updateValueDescription(getCtx(), "User1_ID=" + getC_ElementValue_ID(), get_TrxName()); } if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList2.getCode()))) { MAccount.updateValueDescription(getCtx(), "User2_ID=" + getC_ElementValue_ID(), get_TrxName()); } } return success; } // afterSave } // MElementValue
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MElementValue.java
1
请完成以下Java代码
protected void posTag(char[] charArray, int[] wordNet, Nature[] natureArray) { if (config.speechTagging) { for (int i = 0; i < natureArray.length; ) { if (natureArray[i] == null) { int j = i + 1; for (; j < natureArray.length; ++j) { if (natureArray[j] != null) break; } List<AtomNode> atomNodeList = quickAtomSegment(charArray, i, j); for (AtomNode atomNode : atomNodeList) { if (atomNode.sWord.length() >= wordNet[i]) { wordNet[i] = atomNode.sWord.length(); natureArray[i] = atomNode.getNature(); i += wordNet[i]; }
} i = j; } else { ++i; } } } } @Override public Segment enableCustomDictionary(boolean enable) { if (enable) { logger.warning("为基于词典的分词器开启用户词典太浪费了,建议直接将所有词典的路径传入构造函数,这样速度更快、内存更省"); } return super.enableCustomDictionary(enable); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\DictionaryBasedSegment.java
1
请完成以下Java代码
public PaymentsToReconcileView getByIdOrNull(@NonNull final ViewId paymentsToReconcileViewId) { final ViewId bankStatementReconciliationViewId = toBankStatementReconciliationViewId(paymentsToReconcileViewId); final BankStatementReconciliationView bankStatementReconciliationView = banksStatementReconciliationViewFactory.getByIdOrNull(bankStatementReconciliationViewId); return bankStatementReconciliationView != null ? bankStatementReconciliationView.getPaymentsToReconcileView() : null; } private static ViewId toBankStatementReconciliationViewId(@NonNull final ViewId paymentsToReconcileViewId) { return paymentsToReconcileViewId.withWindowId(BankStatementReconciliationViewFactory.WINDOW_ID); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { // nothing } @Override
public Stream<IView> streamAllViews() { return banksStatementReconciliationViewFactory.streamAllViews() .map(BankStatementReconciliationView::cast) .map(BankStatementReconciliationView::getPaymentsToReconcileView); } @Override public void invalidateView(final ViewId paymentsToReconcileViewId) { final PaymentsToReconcileView paymentsToReconcileView = getByIdOrNull(paymentsToReconcileViewId); if (paymentsToReconcileView != null) { paymentsToReconcileView.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentsToReconcileViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class UserDaoImpl implements UserDao { @Autowired private MongoTemplate mongoTemplate; /** * 创建对象 * @param user */ @Override public void saveUser(UserEntity user) { mongoTemplate.save(user); } /** * 根据用户名查询对象 * @param userName * @return */ @Override public UserEntity findUserByUserName(String userName) { Query query=new Query(Criteria.where("userName").is(userName)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class); return user; } /** * 更新对象 * @param user */ @Override public int updateUser(UserEntity user) {
Query query=new Query(Criteria.where("id").is(user.getId())); Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); //更新查询返回结果集的第一条 WriteResult result =mongoTemplate.updateFirst(query,update,UserEntity.class); //更新查询返回结果集的所有 // mongoTemplate.updateMulti(query,update,UserEntity.class); if(result!=null) return result.getN(); else return 0; } /** * 删除对象 * @param id */ @Override public void deleteUserById(Long id) { Query query=new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,UserEntity.class); } }
repos\spring-boot-leaning-master\1.x\第12课:MongoDB 实战\spring-boot-mongodb-template\src\main\java\com\neo\repository\impl\UserDaoImpl.java
2
请在Spring Boot框架中完成以下Java代码
public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@NonNull final JsonGetNextEligiblePickFromLineRequest request, @NonNull final UserId callerId) { final DistributionJobId jobId = DistributionJobId.ofWFProcessId(request.getWfProcessId()); final DistributionJob job = getJobById(jobId); job.assertCanEdit(callerId); final HUQRCode huQRCode = huService.resolveHUQRCode(request.getHuQRCode()); final ProductId productId; if (request.getProductScannedCode() != null) { productId = productService.getProductIdByScannedProductCode(request.getProductScannedCode()); huService.assetHUContainsProduct(huQRCode, productId); } else { productId = huService.getSingleProductId(huQRCode); } final DistributionJobLineId nextEligiblePickFromLineId; if (request.getLineId() != null) { final DistributionJobLine line = job.getLineById(request.getLineId()); nextEligiblePickFromLineId = line.isEligibleForPicking() ? line.getId() : null; } else { nextEligiblePickFromLineId = job.getNextEligiblePickFromLineId(productId).orElse(null); }
return JsonGetNextEligiblePickFromLineResponse.builder() .lineId(nextEligiblePickFromLineId) .build(); } public void printMaterialInTransitReport( @NonNull final UserId userId, @NonNull final String adLanguage) { @NonNull final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId) .map(LocatorQRCode::getLocatorId) .orElseThrow(() -> new AdempiereException("No trolley found for user: " + userId)); ddOrderMoveScheduleService.printMaterialInTransitReport(inTransitLocatorId, adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionRestService.java
2
请完成以下Java代码
public Long getId() { return id; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } 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 PartyIdentificationSEPA2 getDbtr() { return dbtr; } /** * Sets the value of the dbtr property. * * @param value * allowed object is * {@link PartyIdentificationSEPA2 } * */ public void setDbtr(PartyIdentificationSEPA2 value) { this.dbtr = value; } /** * Gets the value of the dbtrAcct property. * * @return * possible object is * {@link CashAccountSEPA2 } * */ public CashAccountSEPA2 getDbtrAcct() { return dbtrAcct; } /** * Sets the value of the dbtrAcct property. * * @param value * allowed object is * {@link CashAccountSEPA2 } * */ public void setDbtrAcct(CashAccountSEPA2 value) { this.dbtrAcct = value; } /** * Gets the value of the ultmtDbtr property. * * @return * possible object is * {@link PartyIdentificationSEPA1 } * */ public PartyIdentificationSEPA1 getUltmtDbtr() { return ultmtDbtr; } /** * Sets the value of the ultmtDbtr property. * * @param value * allowed object is * {@link PartyIdentificationSEPA1 } * */ public void setUltmtDbtr(PartyIdentificationSEPA1 value) { this.ultmtDbtr = value; } /**
* Gets the value of the purp property. * * @return * possible object is * {@link PurposeSEPA } * */ public PurposeSEPA getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link PurposeSEPA } * */ public void setPurp(PurposeSEPA value) { this.purp = value; } /** * Gets the value of the rmtInf property. * * @return * possible object is * {@link RemittanceInformationSEPA1Choice } * */ public RemittanceInformationSEPA1Choice getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformationSEPA1Choice } * */ public void setRmtInf(RemittanceInformationSEPA1Choice value) { this.rmtInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\DirectDebitTransactionInformationSDD.java
1
请在Spring Boot框架中完成以下Java代码
private SessionAuthenticationStrategy getSessionAuthenticationStrategy() { if (this.sessionAuthenticationStrategy != null) { return this.sessionAuthenticationStrategy; } CsrfAuthenticationStrategy csrfAuthenticationStrategy = new CsrfAuthenticationStrategy( this.csrfTokenRepository); if (this.requestHandler != null) { csrfAuthenticationStrategy.setRequestHandler(this.requestHandler); } return csrfAuthenticationStrategy; } private ObservationRegistry getObservationRegistry() { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); String[] names = context.getBeanNamesForType(ObservationRegistry.class); if (names.length == 1) { return context.getBean(ObservationRegistry.class); } else { return ObservationRegistry.NOOP; } } /** * Allows registering {@link RequestMatcher} instances that should be ignored (even if * the {@link HttpServletRequest} matches the * {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @author Rob Winch * @since 4.0 */ private class IgnoreCsrfProtectionRegistry extends AbstractRequestMatcherRegistry<IgnoreCsrfProtectionRegistry> { IgnoreCsrfProtectionRegistry(ApplicationContext context) { setApplicationContext(context);
} @Override protected IgnoreCsrfProtectionRegistry chainRequestMatchers(List<RequestMatcher> requestMatchers) { CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers); return this; } } private static final class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler { private final CsrfTokenRequestAttributeHandler plain = new CsrfTokenRequestAttributeHandler(); private final CsrfTokenRequestAttributeHandler xor = new XorCsrfTokenRequestAttributeHandler(); SpaCsrfTokenRequestHandler() { this.xor.setCsrfRequestAttributeName(null); } @Override public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> csrfToken) { this.xor.handle(request, response, csrfToken); } @Override public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) { String headerValue = request.getHeader(csrfToken.getHeaderName()); return (StringUtils.hasText(headerValue) ? this.plain : this.xor).resolveCsrfTokenValue(request, csrfToken); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\CsrfConfigurer.java
2
请完成以下Java代码
/* package */class BooleanGetterMethodInfo extends AbstractModelMethodInfo { private final String propertyName; private final Class<?> returnType; public BooleanGetterMethodInfo(final Method interfaceMethod, final String propertyName) { super(interfaceMethod); this.propertyName = propertyName; this.returnType = interfaceMethod.getReturnType(); } @Override public Object invoke(final IModelInternalAccessor model, final Object[] methodArgs) throws Exception { // TODO: optimization: cache matched PropertyName and ColumnIndex String propertyNameToUse = propertyName; int ii = model.getColumnIndex(propertyNameToUse); if (ii >= 0) { return model.getValue(propertyNameToUse, ii, returnType); } propertyNameToUse = "Is" + propertyName;
ii = model.getColumnIndex(propertyNameToUse); if (ii >= 0) { return model.getValue(propertyNameToUse, ii, returnType); } propertyNameToUse = "is" + propertyName; ii = model.getColumnIndex(propertyNameToUse); if (ii >= 0) { return model.getValue(propertyNameToUse, ii, returnType); } final Method interfaceMethod = getInterfaceMethod(); if (interfaceMethod.isDefault()) { return model.invokeParent(interfaceMethod, methodArgs); } // throw new IllegalArgumentException("Method " + interfaceMethod + " is not supported on model " + model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\BooleanGetterMethodInfo.java
1
请完成以下Java代码
public static void fillTypes( Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { fillJsonTypes(convertersToBpmnMap); fillBpmnTypes(convertersToJsonMap); } public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_EVENT_SUB_PROCESS, EventSubProcessJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { convertersToJsonMap.put(EventSubProcess.class, EventSubProcessJsonConverter.class); } protected String getStencilId(BaseElement baseElement) { return STENCIL_EVENT_SUB_PROCESS; } protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { SubProcess subProcess = (SubProcess) baseElement; propertiesNode.put("activitytype", "Event-Sub-Process"); propertiesNode.put("subprocesstype", "Embedded"); ArrayNode subProcessShapesArrayNode = objectMapper.createArrayNode(); GraphicInfo graphicInfo = model.getGraphicInfo(subProcess.getId()); processor.processFlowElements( subProcess, model, subProcessShapesArrayNode, formKeyMap, decisionTableKeyMap, graphicInfo.getX(), graphicInfo.getY() ); flowElementNode.set("childShapes", subProcessShapesArrayNode); } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode,
Map<String, JsonNode> shapeMap ) { EventSubProcess subProcess = new EventSubProcess(); JsonNode childShapesArray = elementNode.get(EDITOR_CHILD_SHAPES); processor.processJsonElements( childShapesArray, modelNode, subProcess, shapeMap, formMap, decisionTableMap, model ); return subProcess; } @Override public void setFormMap(Map<String, String> formMap) { this.formMap = formMap; } @Override public void setFormKeyMap(Map<String, ModelInfo> formKeyMap) { this.formKeyMap = formKeyMap; } @Override public void setDecisionTableMap(Map<String, String> decisionTableMap) { this.decisionTableMap = decisionTableMap; } @Override public void setDecisionTableKeyMap(Map<String, ModelInfo> decisionTableKeyMap) { this.decisionTableKeyMap = decisionTableKeyMap; } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\EventSubProcessJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class ClientWebConfigJava implements WebMvcConfigurer { public ClientWebConfigJava() { super(); } @Bean public MessageSource messageSource() { final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); ms.setBasenames("messages"); return ms; } @Bean public ResourceBundle getBeanResourceBundle() { final Locale locale = Locale.getDefault(); return new MessageSourceResourceBundle(messageSource(), locale); } @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/sample.html"); }
@Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-xml\src\main\java\com\baeldung\spring\ClientWebConfigJava.java
2
请在Spring Boot框架中完成以下Java代码
public class Company extends User { // ============== // PRIVATE FIELDS // ============== // Company's name private String name; // Company's headquarters city private String hqCity; // ============== // PUBLIC METHODS // ============== /** * @return the name */ public String getName() { return name; }
/** * @return the hqCity */ public String getHqCity() { return hqCity; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @param hqCity the hqCity to set */ public void setHqCity(String hqCity) { this.hqCity = hqCity; } } // class Company
repos\spring-boot-samples-master\spring-boot-springdatajpa-inheritance\src\main\java\netgloo\models\Company.java
2