instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static DemandDetail forSupplyRequiredDescriptor(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { return DemandDetail.builder() .demandCandidateId(toUnspecifiedIfZero(supplyRequiredDescriptor.getDemandCandidateId())) .forecastId(toUnspecifiedIfZero(supplyRequiredDescriptor.getForecastId())) .forecastLineId(toUnspecifiedIfZero(supplyRequiredDescriptor.getForecastLineId())) .orderId(toUnspecifiedIfZero(supplyRequiredDescriptor.getOrderId())) .orderLineId(toUnspecifiedIfZero(supplyRequiredDescriptor.getOrderLineId())) .shipmentScheduleId(toUnspecifiedIfZero(supplyRequiredDescriptor.getShipmentScheduleId())) .subscriptionProgressId(toUnspecifiedIfZero(supplyRequiredDescriptor.getSubscriptionProgressId())) .qty(supplyRequiredDescriptor.getQtyToSupplyBD()) .build(); } public static DemandDetail forShipmentScheduleIdAndOrderLineId( final int shipmentScheduleId, final int orderLineId, final int orderId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .shipmentScheduleId(shipmentScheduleId) .orderLineId(orderLineId) .orderId(orderId) .qty(qty).build(); } @NonNull public static DemandDetail forShipmentLineId( final int inOutLineId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .inOutLineId(inOutLineId) .qty(qty) .build(); } public static DemandDetail forForecastLineId( final int forecastLineId, final int forecastId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .forecastLineId(forecastLineId) .forecastId(forecastId) .qty(qty).build(); } int forecastId; int forecastLineId;
int shipmentScheduleId; int orderId; int orderLineId; int subscriptionProgressId; int inOutLineId; BigDecimal qty; /** * Used when a new supply candidate is created, to link it to it's respective demand candidate; * When a demand detail is loaded from DB, this field is always <= 0. */ int demandCandidateId; /** * dev-note: it's about an {@link de.metas.material.event.MaterialEvent} traceId, currently used when posting SupplyRequiredEvents */ @With @Nullable String traceId; @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.SHIPMENT; } public static DemandDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail) { return businessCaseDetail instanceof DemandDetail ? cast(businessCaseDetail) : null; } public static DemandDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (DemandDetail)businessCaseDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DemandDetail.java
1
请完成以下Java代码
public class ThreeDimensionalArrayList { public static void main(String args[]) { int x_axis_length = 2; int y_axis_length = 2; int z_axis_length = 2; ArrayList< ArrayList< ArrayList<String> > > space = new ArrayList<>(x_axis_length); //Initializing each element of ArrayList with ArrayList< ArrayList<String> > for(int i = 0; i < x_axis_length; i++) { space.add(new ArrayList< ArrayList<String> >(y_axis_length)); for(int j = 0; j < y_axis_length; j++) { space.get(i).add(new ArrayList<String>(z_axis_length)); } } //Set Red color for points (0,0,0) and (0,0,1) space.get(0).get(0).add(0,"Red"); space.get(0).get(0).add(1,"Red");
//Set Blue color for points (0,1,0) and (0,1,1) space.get(0).get(1).add(0,"Blue"); space.get(0).get(1).add(1,"Blue"); //Set Green color for points (1,0,0) and (1,0,1) space.get(1).get(0).add(0,"Green"); space.get(1).get(0).add(1,"Green"); //Set Yellow color for points (1,1,0) and (1,1,1) space.get(1).get(1).add(0,"Yellow"); space.get(1).get(1).add(1,"Yellow"); //Printing colors for all the points for(int i = 0; i < x_axis_length; i++) { for(int j = 0; j < y_axis_length; j++) { for(int k = 0; k < z_axis_length; k++) { System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k)); } } } } }
repos\tutorials-master\core-java-modules\core-java-collections-array-list\src\main\java\com\baeldung\list\multidimensional\ThreeDimensionalArrayList.java
1
请在Spring Boot框架中完成以下Java代码
public void setBankTradeAmount(BigDecimal bankTradeAmount) { this.bankTradeAmount = bankTradeAmount; } public BigDecimal getRefundAmount() { return refundAmount; } public void setRefundAmount(BigDecimal refundAmount) { this.refundAmount = refundAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getOrgCheckFilePath() { return orgCheckFilePath; } public void setOrgCheckFilePath(String orgCheckFilePath) { this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim(); } public String getReleaseCheckFilePath() { return releaseCheckFilePath; } public void setReleaseCheckFilePath(String releaseCheckFilePath) { this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim();
} public String getReleaseStatus() { return releaseStatus; } public void setReleaseStatus(String releaseStatus) { this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim(); } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public String getCheckFailMsg() { return checkFailMsg; } public void setCheckFailMsg(String checkFailMsg) { this.checkFailMsg = checkFailMsg; } public String getBankErrMsg() { return bankErrMsg; } public void setBankErrMsg(String bankErrMsg) { this.bankErrMsg = bankErrMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
2
请完成以下Java代码
public static InputStream convertOutputStreamToInputStream(OutputStream outputStream) { byte[] data = ((ByteArrayOutputStream) outputStream).toByteArray(); return new ByteArrayInputStream(data); } /** * Converts a {@link DomDocument} to its String representation * * @param document the XML document to convert */ public static String convertXmlDocumentToString(DomDocument document) { StringWriter stringWriter = new StringWriter(); StreamResult result = new StreamResult(stringWriter); transformDocumentToXml(document, result); return stringWriter.toString(); } /** * Writes a {@link DomDocument} to an {@link OutputStream} by transforming the DOM to XML. * * @param document the DOM document to write * @param outputStream the {@link OutputStream} to write to */ public static void writeDocumentToOutputStream(DomDocument document, OutputStream outputStream) { StreamResult result = new StreamResult(outputStream); transformDocumentToXml(document, result); } /** * Transforms a {@link DomDocument} to XML output. *
* @param document the DOM document to transform * @param result the {@link StreamResult} to write to */ public static void transformDocumentToXml(DomDocument document, StreamResult result) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); synchronized(document) { transformer.transform(document.getDomSource(), result); } } catch (TransformerConfigurationException e) { throw new ModelIoException("Unable to create a transformer for the model", e); } catch (TransformerException e) { throw new ModelIoException("Unable to transform model to xml", e); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\IoUtil.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_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_S_Training.java
1
请完成以下Java代码
public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() { return new NativeHistoricProcessInstanceQueryImpl(commandExecutor); } @Override public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() { return new NativeHistoricTaskInstanceQueryImpl(commandExecutor); } @Override public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() { return new NativeHistoricActivityInstanceQueryImpl(commandExecutor); } @Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId)); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null)); } @Override public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) { return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java
1
请完成以下Java代码
private void updateBillBPartnerForInvoiceCandidate(@NonNull final FlatrateTermBillPartnerRequest request) { final I_C_Flatrate_Term term = flatrateDAO.getById(request.getFlatrateTermId()); final I_C_Invoice_Candidate ic = flatrateDAO.retrieveInvoiceCandidate(term); if (ic == null) { return; } InterfaceWrapperHelper.disableReadOnlyColumnCheck(ic); // disable it because Bill_BPartner_ID is not updateable ic.setBill_BPartner_ID(request.getBillBPartnerId().getRepoId()); ic.setBill_Location_ID(request.getBillLocationId().getRepoId()); ic.setBill_User_ID(BPartnerContactId.toRepoId(request.getBillUserId())); invoiceCandDAO.save(ic); } private IPricingResult computeFlatrateTermPrice(@NonNull final FlatrateTermPriceRequest request) { return FlatrateTermPricing.builder() .term(request.getFlatrateTerm()) .termRelatedProductId(request.getProductId()) .priceDate(request.getPriceDate()) .qty(BigDecimal.ONE) .build() .computeOrThrowEx(); } @Override public I_C_Flatrate_Term getById(@NonNull final FlatrateTermId flatrateTermId) { return flatrateDAO.getById(flatrateTermId); } @Override public ImmutableList<I_C_Flatrate_Term> retrieveNextFlatrateTerms(@NonNull final I_C_Flatrate_Term term) { I_C_Flatrate_Term currentTerm = term; final ImmutableList.Builder<I_C_Flatrate_Term> nextFTsBuilder = ImmutableList.builder();
while (currentTerm.getC_FlatrateTerm_Next_ID() > 0) { nextFTsBuilder.add(currentTerm.getC_FlatrateTerm_Next()); currentTerm = currentTerm.getC_FlatrateTerm_Next(); } return nextFTsBuilder.build(); } @Override public final boolean existsTermForOrderLine(final I_C_OrderLine ol) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class, ol) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Flatrate_Term.COLUMN_C_OrderLine_Term_ID, ol.getC_OrderLine_ID()) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateBL.java
1
请完成以下Java代码
public int getPP_Order_Next_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Next_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Order_Node getPP_Order_Node() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class); } @Override public void setPP_Order_Node(org.eevolution.model.I_PP_Order_Node PP_Order_Node) { set_ValueFromPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class, PP_Order_Node); } /** Set Manufacturing Order Activity. @param PP_Order_Node_ID Workflow Node (activity), step or process */ @Override public void setPP_Order_Node_ID (int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, Integer.valueOf(PP_Order_Node_ID)); } /** Get Manufacturing Order Activity. @return Workflow Node (activity), step or process */ @Override public int getPP_Order_Node_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Manufacturing Order Activity Next. @param PP_Order_NodeNext_ID Manufacturing Order Activity Next */ @Override public void setPP_Order_NodeNext_ID (int PP_Order_NodeNext_ID) { if (PP_Order_NodeNext_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, Integer.valueOf(PP_Order_NodeNext_ID)); } /** Get Manufacturing Order Activity Next. @return Manufacturing Order Activity Next */ @Override public int getPP_Order_NodeNext_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_NodeNext_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Transition Code. @param TransitionCode Code resulting in TRUE of FALSE */ @Override public void setTransitionCode (java.lang.String TransitionCode) { set_Value (COLUMNNAME_TransitionCode, TransitionCode); } /** Get Transition Code. @return Code resulting in TRUE of FALSE */ @Override public java.lang.String getTransitionCode () { return (java.lang.String)get_Value(COLUMNNAME_TransitionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_NodeNext.java
1
请在Spring Boot框架中完成以下Java代码
private void applyConnectionDetails(LiquibaseConnectionDetails connectionDetails, DataSourceBuilder<?> builder) { builder.username(connectionDetails.getUsername()); builder.password(connectionDetails.getPassword()); String driverClassName = connectionDetails.getDriverClassName(); if (StringUtils.hasText(driverClassName)) { builder.driverClassName(driverClassName); } } } @ConditionalOnClass(Customizer.class) @Configuration(proxyBeanMethods = false) static class CustomizerConfiguration { @Bean @ConditionalOnBean(Customizer.class) SpringLiquibaseCustomizer springLiquibaseCustomizer(Customizer<Liquibase> customizer) { return (springLiquibase) -> springLiquibase.setCustomizer(customizer); } } static final class LiquibaseDataSourceCondition extends AnyNestedCondition { LiquibaseDataSourceCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(DataSource.class) private static final class DataSourceBeanCondition { } @ConditionalOnBean(JdbcConnectionDetails.class) private static final class JdbcConnectionDetailsCondition { } @ConditionalOnProperty("spring.liquibase.url") private static final class LiquibaseUrlCondition { } } static class LiquibaseAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("db/changelog/**"); } } /** * Adapts {@link LiquibaseProperties} to {@link LiquibaseConnectionDetails}. */ static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails { private final LiquibaseProperties properties; PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) { this.properties = properties; }
@Override public @Nullable String getUsername() { return this.properties.getUser(); } @Override public @Nullable String getPassword() { return this.properties.getPassword(); } @Override public @Nullable String getJdbcUrl() { return this.properties.getUrl(); } @Override public @Nullable String getDriverClassName() { String driverClassName = this.properties.getDriverClassName(); return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName(); } } @FunctionalInterface interface SpringLiquibaseCustomizer { /** * Customize the given {@link SpringLiquibase} instance. * @param springLiquibase the instance to configure */ void customize(SpringLiquibase springLiquibase); } }
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private String contentToString(byte[] content) { if (isZippedResponse()) { byte[] unzippedContent = unzipContent(content); return new String(unzippedContent, StandardCharsets.UTF_8); } return new String(content, StandardCharsets.UTF_8); } private boolean isZippedResponse() { return ( !originalResponse.getHeaders().isEmpty() && originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING) != null && Objects.requireNonNull(originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING)).contains("gzip") ); } private byte[] unzipContent(byte[] content) { try { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(content)); byte[] unzippedContent = gzipInputStream.readAllBytes(); gzipInputStream.close(); return unzippedContent; } catch (IOException e) { log.error("Error when unzip content during modify servers from api-doc of {}: {}", path, e.getMessage()); } return content;
} private byte[] zipContent(String content) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.length()); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream); gzipOutputStream.write(content.getBytes(StandardCharsets.UTF_8)); gzipOutputStream.flush(); gzipOutputStream.close(); return byteArrayOutputStream.toByteArray(); } catch (IOException e) { log.error("Error when zip content during modify servers from api-doc of {}: {}", path, e.getMessage()); } return content.getBytes(); } } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\filter\ModifyServersOpenApiFilter.java
2
请在Spring Boot框架中完成以下Java代码
public class ServerApplication { private static final String MESSAGE_QUEUE = "pizza-message-queue"; private static final String PUB_SUB_TOPIC = "notification-topic"; private static final String PUB_SUB_EMAIL_QUEUE = "email-queue"; private static final String PUB_SUB_TEXT_QUEUE = "text-queue"; @Bean public Queue queue() { return new Queue(MESSAGE_QUEUE); } @Bean public Queue emailQueue() { return new Queue(PUB_SUB_EMAIL_QUEUE); } @Bean public Queue textQueue() { return new Queue(PUB_SUB_TEXT_QUEUE); } @Bean public TopicExchange exchange() { return new TopicExchange(PUB_SUB_TOPIC);
} @Bean public Binding emailBinding(Queue emailQueue, TopicExchange exchange) { return BindingBuilder.bind(emailQueue).to(exchange).with("notification"); } @Bean public Binding textBinding(Queue textQueue, TopicExchange exchange) { return BindingBuilder.bind(textQueue).to(exchange).with("notification"); } @Bean public Publisher publisher(RabbitTemplate rabbitTemplate) { return new Publisher(rabbitTemplate, MESSAGE_QUEUE, PUB_SUB_TOPIC); } public static void main(String[] args) { SpringApplication.run(ServerApplication.class, args); } }
repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\pubsubmq\server\ServerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public Candidate retrieveExistingStockEstimateCandidateOrNull(@NonNull final AbstractStockEstimateEvent event) { final CandidatesQuery query = createCandidatesQuery(event); return candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query); } @Nullable public Candidate retrievePreviousStockCandidateOrNull(@NonNull final AbstractStockEstimateEvent event) { final CandidatesQuery query = createPreviousStockCandidatesQuery(event); return candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query); } @NonNull private CandidatesQuery createCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final StockChangeDetailQuery stockChangeDetailQuery = StockChangeDetailQuery.builder() .freshQuantityOnHandLineRepoId(event.getFreshQtyOnHandLineId()) .build(); return CandidatesQuery.builder() .businessCase(CandidateBusinessCase.STOCK_CHANGE) .materialDescriptorQuery(MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor())) .stockChangeDetailQuery(stockChangeDetailQuery) .build(); }
@NonNull private CandidatesQuery createPreviousStockCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor()) .toBuilder() .timeRangeEnd(DateAndSeqNo.builder() .date(event.getDate()) .operator(DateAndSeqNo.Operator.EXCLUSIVE) .build()) .build(); return CandidatesQuery.builder() .materialDescriptorQuery(materialDescriptorQuery) .type(CandidateType.STOCK) .matchExactStorageAttributesKey(true) .parentId(CandidateId.UNSPECIFIED) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateEventService.java
2
请完成以下Java代码
public Pet status(StatusEnum status) { this.status = status; return this; } /** * pet status in the store * @return status **/ @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pet pet = (Pet) o; return Objects.equals(this.id, pet.id) && Objects.equals(this.category, pet.category) && Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && Objects.equals(this.status, pet.status); } @Override public int hashCode() { return Objects.hash(id, category, name, photoUrls, tags, status); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java
1
请完成以下Java代码
public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteMobileAppsByTenantId, tenantId [{}]", tenantId); mobileAppBundleDao.deleteByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findMobileAppBundleById(tenantId, new MobileAppBundleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(mobileAppBundleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteMobileAppBundleById(tenantId, (MobileAppBundleId) id); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP_BUNDLE; } private void fetchOauth2Clients(MobileAppBundleInfo mobileAppBundleInfo) { List<OAuth2ClientInfo> clients = oauth2ClientDao.findByMobileAppBundleId(mobileAppBundleInfo.getUuidId()).stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); mobileAppBundleInfo.setOauth2ClientInfos(clients); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppBundleServiceImpl.java
1
请完成以下Java代码
void startNaive() { List<CompletableFuture<String>> futures = new ArrayList<>(); for (int i = 1; i <= 1000; i++) { String operationId = "Naive-Operation-" + i; futures.add(asyncOperation(operationId)); } CompletableFuture<List<String>> aggregate = CompletableFuture.completedFuture(new ArrayList<>()); for (CompletableFuture<String> future : futures) { aggregate = aggregate.thenCompose(list -> { try { list.add(future.get()); return CompletableFuture.completedFuture(list); } catch (Exception e) { final CompletableFuture<List<String>> excFuture = new CompletableFuture<>(); excFuture.completeExceptionally(e); return excFuture; } }); } try { final List<String> results = aggregate.join(); System.out.println("Printing first 10 results"); for (int i = 0; i < 10; i++) { System.out.println("Finished " + results.get(i)); } } finally { close(); } } void start() { List<CompletableFuture<String>> futures = new ArrayList<>(); for (int i = 1; i <= 1000; i++) { String operationId = "Operation-" + i; futures.add(asyncOperation(operationId)); } CompletableFuture<?>[] futuresArray = futures.toArray(new CompletableFuture<?>[0]); CompletableFuture<List<String>> listFuture = CompletableFuture.allOf(futuresArray).thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())); try { final List<String> results = listFuture.join();
System.out.println("Printing first 10 results"); for (int i = 0; i < 10; i++) { System.out.println("Finished " + results.get(i)); } } finally { close(); } } void close() { asyncOperationEmulation.shutdownNow(); } public static void main(String[] args) { new Application().initialize() // Switch between .startNaive() and .start() to test both implementations // .startNaive(); .start(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-3\src\main\java\com\baeldung\concurrent\completablefuturelist\Application.java
1
请完成以下Java代码
public class CustomMovieIterator implements Iterator<Movie> { private int currentIndex; private final List<Movie> list; public CustomMovieIterator(List<Movie> list) { this.list = list; this.currentIndex = 0; } @Override public boolean hasNext() { while (currentIndex < list.size()) { Movie currentMovie = list.get(currentIndex); if (isMovieEligible(currentMovie)) { return true; }
currentIndex++; } return false; } @Override public Movie next() { if (!hasNext()) { throw new NoSuchElementException(); } return list.get(currentIndex++); } private boolean isMovieEligible(Movie movie) { return movie.getRating() >= 8; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\CustomMovieIterator.java
1
请在Spring Boot框架中完成以下Java代码
private void pushNotificationToEdge(EdgeNotificationMsgProto edgeNotificationMsg, int retryCount, int retryLimit, TbCallback callback) { TenantId tenantId = TenantId.fromUUID(new UUID(edgeNotificationMsg.getTenantIdMSB(), edgeNotificationMsg.getTenantIdLSB())); log.debug("[{}] Pushing notification to edge {}", tenantId, edgeNotificationMsg); try { EdgeEventType type = EdgeEventType.valueOf(edgeNotificationMsg.getType()); ListenableFuture<Void> future = edgeCtx.getProcessor(type).processEntityNotification(tenantId, edgeNotificationMsg); Futures.addCallback(future, new FutureCallback<>() { @Override public void onSuccess(@Nullable Void unused) { callback.onSuccess(); } @Override public void onFailure(@NotNull Throwable throwable) { if (retryCount < retryLimit) { log.warn("[{}] Retry {} for message due to failure: {}", tenantId, retryCount + 1, throwable.getMessage()); pushNotificationToEdge(edgeNotificationMsg, retryCount + 1, retryLimit, callback); } else { callBackFailure(tenantId, edgeNotificationMsg, callback, throwable); } } }, MoreExecutors.directExecutor()); } catch (Exception e) { if (retryCount < retryLimit) { log.warn("[{}] Retry {} for message due to exception: {}", tenantId, retryCount + 1, e.getMessage()); pushNotificationToEdge(edgeNotificationMsg, retryCount + 1, retryLimit, callback); } else { callBackFailure(tenantId, edgeNotificationMsg, callback, e); } } } private void callBackFailure(TenantId tenantId, EdgeNotificationMsgProto edgeNotificationMsg, TbCallback callback, Throwable throwable) { log.error("[{}] Can't push to edge updates, edgeNotificationMsg [{}]", tenantId, edgeNotificationMsg, throwable); callback.onFailure(throwable); }
@Scheduled(fixedDelayString = "${queue.edge.stats.print-interval-ms}") public void printStats() { if (statsEnabled) { stats.printStats(); stats.reset(); } } @Override protected void stopConsumers() { super.stopConsumers(); mainConsumer.stop(); mainConsumer.awaitStop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbEdgeConsumerService.java
2
请完成以下Java代码
/* package */ void validateBbanEntries(final String iban, final BBANStructure code) { final String bban = getBBAN(iban); int bbanEntryOffset = 0; for (final BBANStructureEntry entry : code.getEntries()) { final int entryLength = entry.getLength(); final String entryValue = bban.substring(bbanEntryOffset, bbanEntryOffset + entryLength); bbanEntryOffset = bbanEntryOffset + entryLength; // validate character type validateBbanEntryCharacterType(entry, entryValue); } } /* package */ void validateBbanEntryCharacterType(final BBANStructureEntry entry, final String entryValue) { switch (entry.getCharacterType()) { case a: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isUpperCase(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Upper_Letters", new Object[] { entryValue })); } break; case c: for (char ch : entryValue.toCharArray())
{ Check.assume(Character.isLetterOrDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Letters_Digits", new Object[] { entryValue })); } break; case n: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Digits", new Object[] { entryValue })); } break; } } /* package */ BBANStructure getBBANCode(final String iban) { final String countryCode = getCountryCode(iban); return Services.get(IBBANStructureBL.class).getBBANStructureForCountry(countryCode); } private String fromCharCode(int... codePoints) { return new String(codePoints, 0, codePoints.length); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\IBANValidationBL.java
1
请完成以下Java代码
final class ClientRegistrationDeserializer extends ValueDeserializer<ClientRegistration> { private static final StdConverter<JsonNode, ClientAuthenticationMethod> CLIENT_AUTHENTICATION_METHOD_CONVERTER = new StdConverters.ClientAuthenticationMethodConverter(); private static final StdConverter<JsonNode, AuthorizationGrantType> AUTHORIZATION_GRANT_TYPE_CONVERTER = new StdConverters.AuthorizationGrantTypeConverter(); private static final StdConverter<JsonNode, AuthenticationMethod> AUTHENTICATION_METHOD_CONVERTER = new StdConverters.AuthenticationMethodConverter(); @Override public ClientRegistration deserialize(JsonParser parser, DeserializationContext context) { JsonNode clientRegistrationNode = context.readTree(parser); JsonNode providerDetailsNode = JsonNodeUtils.findObjectNode(clientRegistrationNode, "providerDetails"); JsonNode userInfoEndpointNode = JsonNodeUtils.findObjectNode(providerDetailsNode, "userInfoEndpoint"); return ClientRegistration .withRegistrationId(JsonNodeUtils.findStringValue(clientRegistrationNode, "registrationId")) .clientId(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientId")) .clientSecret(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientSecret")) .clientAuthenticationMethod(CLIENT_AUTHENTICATION_METHOD_CONVERTER .convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "clientAuthenticationMethod"))) .authorizationGrantType(AUTHORIZATION_GRANT_TYPE_CONVERTER .convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "authorizationGrantType"))) .redirectUri(JsonNodeUtils.findStringValue(clientRegistrationNode, "redirectUri")) .scope(JsonNodeUtils.findValue(clientRegistrationNode, "scopes", JsonNodeUtils.STRING_SET, context))
.clientName(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientName")) .authorizationUri(JsonNodeUtils.findStringValue(providerDetailsNode, "authorizationUri")) .tokenUri(JsonNodeUtils.findStringValue(providerDetailsNode, "tokenUri")) .userInfoUri(JsonNodeUtils.findStringValue(userInfoEndpointNode, "uri")) .userInfoAuthenticationMethod(AUTHENTICATION_METHOD_CONVERTER .convert(JsonNodeUtils.findObjectNode(userInfoEndpointNode, "authenticationMethod"))) .userNameAttributeName(JsonNodeUtils.findStringValue(userInfoEndpointNode, "userNameAttributeName")) .jwkSetUri(JsonNodeUtils.findStringValue(providerDetailsNode, "jwkSetUri")) .issuerUri(JsonNodeUtils.findStringValue(providerDetailsNode, "issuerUri")) .providerConfigurationMetadata(JsonNodeUtils.findValue(providerDetailsNode, "configurationMetadata", JsonNodeUtils.STRING_OBJECT_MAP, context)) .build(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\jackson\ClientRegistrationDeserializer.java
1
请在Spring Boot框架中完成以下Java代码
private Contract importContractNoCascade(final BPartner bpartner, final SyncContract syncContract, Contract contract) { final String uuid = syncContract.getUuid(); if (contract != null && !Objects.equals(uuid, contract.getUuid())) { contract = null; } if (contract == null) { contract = new Contract(); contract.setUuid(uuid); contract.setBpartner(bpartner); } contract.setDeleted(false); contract.setDateFrom(syncContract.getDateFrom()); contract.setDateTo(syncContract.getDateTo()); contract.setRfq_uuid(syncContract.getRfq_uuid()); contractsRepo.save(contract); logger.debug("Imported: {} -> {}", syncContract, contract); return contract; } @Nullable private ContractLine importContractLineNoSave(final Contract contract, final SyncContractLine syncContractLine, final Map<String, ContractLine> contractLines) { // If delete request, skip importing the contract line. // As a result, if there is a contract line for this sync-contract line, it will be deleted below. if (syncContractLine.isDeleted()) { return null; } ContractLine contractLine = contractLines.remove(syncContractLine.getUuid()); // // Product
final SyncProduct syncProductNoDelete = assertNotDeleteRequest_WarnAndFix(syncContractLine.getProduct(), "importing contract lines"); Product product = contractLine == null ? null : contractLine.getProduct(); product = productsImportService.importProduct(syncProductNoDelete, product) .orElseThrow(() -> new RuntimeException("Deleted product cannot be used in " + syncContractLine)); // // Contract Line if (contractLine == null) { contractLine = new ContractLine(); contractLine.setUuid(syncContractLine.getUuid()); contractLine.setContract(contract); } contractLine.setDeleted(false); contractLine.setProduct(product); logger.debug("Imported: {} -> {}", syncContractLine, contractLine); return contractLine; } public void deleteContract(final Contract contract) { contractsRepo.delete(contract); contractsRepo.flush(); logger.debug("Deleted: {}", contract); } private void deleteContractLine(final ContractLine contractLine) { contractLinesRepo.delete(contractLine); contractLinesRepo.flush(); logger.debug("Deleted: {}", contractLine); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncContractImportService.java
2
请完成以下Java代码
public class DeleteHistoricCaseInstanceCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String caseInstanceId; public DeleteHistoricCaseInstanceCmd(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @Override public Object execute(CommandContext commandContext) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null"); } // Check if case instance is still running CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); HistoricCaseInstanceEntity instance = cmmnEngineConfiguration.getHistoricCaseInstanceEntityManager().findById(caseInstanceId);
if (instance == null) { throw new FlowableObjectNotFoundException("No historic case instance found with id: " + caseInstanceId, HistoricCaseInstance.class); } if (instance.isDeleted()) { return null; } if (instance.getEndTime() == null) { throw new FlowableException("Case instance is still running, cannot delete " + instance); } cmmnEngineConfiguration.getCmmnHistoryManager().recordHistoricCaseInstanceDeleted(caseInstanceId, instance.getTenantId()); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteHistoricCaseInstanceCmd.java
1
请完成以下Java代码
public void run(final String localTrxName) { InterfaceWrapperHelper.refresh(doc, localTrxName); docActionBL.processEx(doc, docAction, null); // expectedDocStatus=null because it is *not* always equal to the docAaction (Prepay-Order) addLog("Document " + doc + ": Processed"); countOK++; } @Override public boolean doCatch(final Throwable e) { final String msg = "Processing of document " + doc + ": Failed - ProccessMsg: " + documentBL.getDocument(doc).getProcessMsg() + "; ExceptionMsg: " + e.getMessage();
addLog(msg); log.warn(msg, e); countError++; return true; // rollback } @Override public void doFinally() { // nothing } }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\AbstractProcessDocumentsTemplate.java
1
请完成以下Java代码
public ThreadPoolTaskExecutor build() { return configure(new ThreadPoolTaskExecutor()); } /** * Build a new {@link ThreadPoolTaskExecutor} instance of the specified type and * configure it using this builder. * @param <T> the type of task executor * @param taskExecutorClass the template type to create * @return a configured {@link ThreadPoolTaskExecutor} instance. * @see #build() * @see #configure(ThreadPoolTaskExecutor) */ public <T extends ThreadPoolTaskExecutor> T build(Class<T> taskExecutorClass) { return configure(BeanUtils.instantiateClass(taskExecutorClass)); } /** * Configure the provided {@link ThreadPoolTaskExecutor} instance using this builder. * @param <T> the type of task executor * @param taskExecutor the {@link ThreadPoolTaskExecutor} to configure * @return the task executor instance * @see #build() * @see #build(Class) */
public <T extends ThreadPoolTaskExecutor> T configure(T taskExecutor) { PropertyMapper map = PropertyMapper.get(); map.from(this.queueCapacity).to(taskExecutor::setQueueCapacity); map.from(this.corePoolSize).to(taskExecutor::setCorePoolSize); map.from(this.maxPoolSize).to(taskExecutor::setMaxPoolSize); map.from(this.keepAlive).asInt(Duration::getSeconds).to(taskExecutor::setKeepAliveSeconds); map.from(this.allowCoreThreadTimeOut).to(taskExecutor::setAllowCoreThreadTimeOut); map.from(this.acceptTasksAfterContextClose).to(taskExecutor::setAcceptTasksAfterContextClose); map.from(this.awaitTermination).to(taskExecutor::setWaitForTasksToCompleteOnShutdown); map.from(this.awaitTerminationPeriod).as(Duration::toMillis).to(taskExecutor::setAwaitTerminationMillis); map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix); map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskExecutor)); } return taskExecutor; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\ThreadPoolTaskExecutorBuilder.java
1
请完成以下Java代码
public VerfuegbarkeitDefektgrund getGrund() { return grund; } /** * Sets the value of the grund property. * * @param value * allowed object is * {@link VerfuegbarkeitDefektgrund } * */ public void setGrund(VerfuegbarkeitDefektgrund value) { this.grund = value; }
/** * Gets the value of the tourabweichung property. * */ public boolean isTourabweichung() { return tourabweichung; } /** * Sets the value of the tourabweichung property. * */ public void setTourabweichung(boolean value) { this.tourabweichung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VerfuegbarkeitAnteil.java
1
请在Spring Boot框架中完成以下Java代码
private static void unzipFile(Path zipFilePath, Path targetDir, Consumer<File> afterExtract) throws IOException { long totalUnzippedSize = 0; int entryCount = 0; if (!Files.exists(targetDir)) { Files.createDirectories(targetDir); } try (ZipFile zipFile = new ZipFile(zipFilePath.toFile())) { Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); entryCount++; if (entryCount > MAX_ENTRY_COUNT) { throw new IOException("解压文件数量超限,可能是zip bomb攻击"); } Path newPath = safeResolve(targetDir, entry.getName()); if (entry.isDirectory()) { Files.createDirectories(newPath); } else { Files.createDirectories(newPath.getParent()); try (InputStream is = zipFile.getInputStream(entry); OutputStream os = Files.newOutputStream(newPath)) { long bytesCopied = copyLimited(is, os, MAX_FILE_SIZE); totalUnzippedSize += bytesCopied; if (totalUnzippedSize > MAX_TOTAL_SIZE) { throw new IOException("解压总大小超限,可能是zip bomb攻击"); } } // 解压完成后回调 if (afterExtract != null) { afterExtract.accept(newPath.toFile()); } } } } } /** * 安全解析路径,防止Zip Slip攻击 * * @param targetDir
* @param entryName * @return * @throws IOException * @author chenrui * @date 2025/4/28 16:46 */ private static Path safeResolve(Path targetDir, String entryName) throws IOException { Path resolvedPath = targetDir.resolve(entryName).normalize(); if (!resolvedPath.startsWith(targetDir)) { throw new IOException("ZIP 路径穿越攻击被阻止:" + entryName); } return resolvedPath; } /** * 复制输入流到输出流,并限制最大字节数 * * @param in * @param out * @param maxBytes * @return * @throws IOException * @author chenrui * @date 2025/4/28 17:03 */ private static long copyLimited(InputStream in, OutputStream out, long maxBytes) throws IOException { byte[] buffer = new byte[8192]; long totalCopied = 0; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { totalCopied += bytesRead; if (totalCopied > maxBytes) { throw new IOException("单个文件解压超限,可能是zip bomb攻击"); } out.write(buffer, 0, bytesRead); } return totalCopied; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\service\impl\AiragKnowledgeDocServiceImpl.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Year. @param FiscalYear The Fiscal Year */ public void setFiscalYear (String FiscalYear) { set_Value (COLUMNNAME_FiscalYear, FiscalYear); } /** Get Year. @return The Fiscal Year */ public String getFiscalYear () { return (String)get_Value(COLUMNNAME_FiscalYear); } /** Get Record ID/ColumnName
@return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getFiscalYear()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java
1
请完成以下Java代码
public String getLastErrorMessage() { return m_errorMessage; } /** * Method getLastErrorDescription * @return String */ public String getLastErrorDescription() { return m_errorDescription; } /** * @author ET * @version $Id: OFXBankStatementHandler.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $ */ class StatementLine { protected String routingNo = null; protected String bankAccountNo = null; protected String statementReference = null; protected Timestamp statementLineDate = null; protected String reference = null; protected Timestamp valutaDate; protected String trxType = null;
protected boolean isReversal = false; protected String currency = null; protected BigDecimal stmtAmt = null; protected String memo = null; protected String chargeName = null; protected BigDecimal chargeAmt = null; protected String payeeAccountNo = null; protected String payeeName = null; protected String trxID = null; protected String checkNo = null; /** * Constructor for StatementLine * @param RoutingNo String * @param BankAccountNo String * @param Currency String */ public StatementLine(String RoutingNo, String BankAccountNo, String Currency) { bankAccountNo = BankAccountNo; routingNo = RoutingNo; currency = Currency; } } } //OFXBankStatementHandler
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\impexp\OFXBankStatementHandler.java
1
请完成以下Java代码
public String modelChange(final PO po, final int type) throws Exception { // nothing return null; } @Override public String docValidate(final PO po, final int timing) { // nothing return null; } private void registerInstanceValidator(final I_C_ReferenceNo_Type type) { final Properties ctx = InterfaceWrapperHelper.getCtx(type); final IReferenceNoGeneratorInstance instance = Services.get(IReferenceNoBL.class).getReferenceNoGeneratorInstance(ctx, type); if (instance == null) { return; } final ReferenceNoGeneratorInstanceValidator validator = new ReferenceNoGeneratorInstanceValidator(instance); engine.addModelValidator(validator); docValidators.add(validator); } private void unregisterInstanceValidator(final I_C_ReferenceNo_Type type) {
final Iterator<ReferenceNoGeneratorInstanceValidator> it = docValidators.iterator(); while (it.hasNext()) { final ReferenceNoGeneratorInstanceValidator validator = it.next(); if (validator.getInstance().getType().getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID()) { validator.unregister(); it.remove(); } } } public void updateInstanceValidator(final I_C_ReferenceNo_Type type) { unregisterInstanceValidator(type); registerInstanceValidator(type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\Main.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_GL_Category[") .append(get_ID()).append("]"); return sb.toString(); } /** CategoryType AD_Reference_ID=207 */ public static final int CATEGORYTYPE_AD_Reference_ID=207; /** Manual = M */ public static final String CATEGORYTYPE_Manual = "M"; /** Import = I */ public static final String CATEGORYTYPE_Import = "I"; /** Document = D */ public static final String CATEGORYTYPE_Document = "D"; /** System generated = S */ public static final String CATEGORYTYPE_SystemGenerated = "S"; /** Set Category Type. @param CategoryType Source of the Journal with this category */ public void setCategoryType (String CategoryType) { set_Value (COLUMNNAME_CategoryType, CategoryType); } /** Get Category Type. @return Source of the Journal with this category */ public String getCategoryType () { return (String)get_Value(COLUMNNAME_CategoryType); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set GL Category. @param GL_Category_ID General Ledger Category */ public void setGL_Category_ID (int GL_Category_ID) { if (GL_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID)); }
/** Get GL Category. @return General Ledger Category */ public int getGL_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Category.java
1
请完成以下Java代码
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_Value (COLUMNNAME_ES_FTS_Config_ID, null); else set_Value (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_FTS_Index_Queue_ID (final int ES_FTS_Index_Queue_ID) { if (ES_FTS_Index_Queue_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, ES_FTS_Index_Queue_ID); } @Override public int getES_FTS_Index_Queue_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Index_Queue_ID); } /** * EventType AD_Reference_ID=541373 * Reference name: ES_FTS_Index_Queue_EventType */ public static final int EVENTTYPE_AD_Reference_ID=541373; /** Update = U */ public static final String EVENTTYPE_Update = "U"; /** Delete = D */ public static final String EVENTTYPE_Delete = "D"; @Override public void setEventType (final java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } @Override public java.lang.String getEventType() { return get_ValueAsString(COLUMNNAME_EventType); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); }
@Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessingTag (final @Nullable java.lang.String ProcessingTag) { set_Value (COLUMNNAME_ProcessingTag, ProcessingTag); } @Override public java.lang.String getProcessingTag() { return get_ValueAsString(COLUMNNAME_ProcessingTag); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java
1
请在Spring Boot框架中完成以下Java代码
public InternalHistoryVariableManager getInternalHistoryVariableManager() { return internalHistoryVariableManager; } public VariableServiceConfiguration setInternalHistoryVariableManager(InternalHistoryVariableManager internalHistoryVariableManager) { this.internalHistoryVariableManager = internalHistoryVariableManager; return this; } public ExpressionManager getExpressionManager() { return expressionManager; } public VariableServiceConfiguration setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; return this; } public int getMaxLengthString() { return maxLengthString; } public VariableServiceConfiguration setMaxLengthString(int maxLengthString) { this.maxLengthString = maxLengthString; return this; } public boolean isLoggingSessionEnabled() { return loggingSessionEnabled; } public VariableServiceConfiguration setLoggingSessionEnabled(boolean loggingSessionEnabled) { this.loggingSessionEnabled = loggingSessionEnabled; return this; } public boolean isSerializableVariableTypeTrackDeserializedObjects() { return serializableVariableTypeTrackDeserializedObjects;
} public void setSerializableVariableTypeTrackDeserializedObjects(boolean serializableVariableTypeTrackDeserializedObjects) { this.serializableVariableTypeTrackDeserializedObjects = serializableVariableTypeTrackDeserializedObjects; } public VariableJsonMapper getVariableJsonMapper() { return variableJsonMapper; } public void setVariableJsonMapper(VariableJsonMapper variableJsonMapper) { this.variableJsonMapper = variableJsonMapper; } public VariableInstanceValueModifier getVariableInstanceValueModifier() { return variableInstanceValueModifier; } public void setVariableInstanceValueModifier(VariableInstanceValueModifier variableInstanceValueModifier) { this.variableInstanceValueModifier = variableInstanceValueModifier; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\VariableServiceConfiguration.java
2
请完成以下Java代码
public static MHRAttribute forValue(Properties ctx, String value, int C_BPartner_ID, Timestamp date) { if (Check.isEmpty(value, true)) { return null; } int AD_Client_ID = Env.getAD_Client_ID(ctx); final String whereClause = COLUMNNAME_C_BPartner_ID+"=? AND AD_Client_ID IN (?,?) " + " AND " + COLUMNNAME_ValidFrom +"<=?" + " AND EXISTS (SELECT 1 FROM HR_Concept c WHERE HR_Attribute.HR_Concept_ID = c.HR_Concept_ID" + " AND c.Value=?)"; MHRAttribute att = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{C_BPartner_ID, 0, AD_Client_ID, date, value}) .setOnlyActiveRecords(true) .setOrderBy(COLUMNNAME_ValidFrom + " DESC") .first(); return att; } /** * Get Concept by Value * @param ctx * @param value * @param C_BPartner_ID * @param startDate * @param endDate * @return attribute */ public static MHRAttribute forValue(Properties ctx, String value, int C_BPartner_ID, Timestamp startDate, Timestamp endDate) { if (Check.isEmpty(value, true)) { return null; } if (endDate == null) { return forValue(ctx, value, C_BPartner_ID, startDate); } else { int AD_Client_ID = Env.getAD_Client_ID(ctx); final String whereClause = COLUMNNAME_C_BPartner_ID+"=? AND AD_Client_ID IN (?,?) "
+ " AND " + COLUMNNAME_ValidFrom +"<=? AND " + COLUMNNAME_ValidTo +">=?" + " AND EXISTS (SELECT 1 FROM HR_Concept c WHERE HR_Attribute.HR_Concept_ID = c.HR_Concept_ID" + " AND c.Value=?)"; MHRAttribute att = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{C_BPartner_ID, 0, AD_Client_ID, startDate, endDate, value}) .setOnlyActiveRecords(true) .setOrderBy(COLUMNNAME_ValidFrom + " DESC") .first(); return att; } } /** * @param ctx * @param HR_Attribute_ID * @param trxName */ public MHRAttribute(Properties ctx, int HR_Attribute_ID, String trxName) { super(ctx, HR_Attribute_ID, trxName); } /** * @param ctx * @param rs * @param trxName */ public MHRAttribute(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } @Override public I_HR_Concept getHR_Concept() { return MHRConcept.get(getCtx(), getHR_Concept_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRAttribute.java
1
请完成以下Java代码
public class SpringBootProcessEnginePlugin extends SpringProcessEnginePlugin { @Override public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { springProcessEngineConfiguration(processEngineConfiguration) .ifPresent(this::preInit); } @Override public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) { springProcessEngineConfiguration(processEngineConfiguration) .ifPresent(this::postInit); } @Override
public void postProcessEngineBuild(ProcessEngine processEngine) { processEngineImpl(processEngine).ifPresent(this::postProcessEngineBuild); } public void preInit(SpringProcessEngineConfiguration processEngineConfiguration) { } public void postInit(SpringProcessEngineConfiguration processEngineConfiguration) { } public void postProcessEngineBuild(ProcessEngineImpl processEngine) { } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEnginePlugin.java
1
请完成以下Java代码
public class M_ShipperTransportation_AddShipments extends JavaProcess implements IProcessPrecondition { private final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); private final IShipperTransportationDAO shipperTransportationDAO = Services.get(IShipperTransportationDAO.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { final List<I_M_ShipperTransportation> selectedModels = context.getSelectedModels(I_M_ShipperTransportation.class); if (selectedModels.size() == 1) { return ProcessPreconditionsResolution.acceptIf(!selectedModels.get(0).isProcessed()); } return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
} @Override protected String doIt() throws Exception { final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(ShipperTransportationId.ofRepoId(getRecord_ID())); final ImmutableList<InOutId> inOutIds = inOutDAO.retrieveShipmentsWithoutShipperTransportation(shipperTransportation.getDateDoc()); final InOutToTransportationOrderService service = SpringContextHolder.instance.getBean(InOutToTransportationOrderService.class); service.addShipmentsToTransportationOrder(ShipperTransportationId.ofRepoId(getRecord_ID()), inOutIds); return "OK"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\process\M_ShipperTransportation_AddShipments.java
1
请在Spring Boot框架中完成以下Java代码
public class CommentsRestController { protected static final String ENDPOINT = WindowRestController.ENDPOINT + "/{windowId}/{documentId}/comments"; private final UserSession userSession; private final DocumentDescriptorFactory documentDescriptorFactory; private final CommentsService commentsService; public CommentsRestController( final UserSession userSession, final DocumentDescriptorFactory documentDescriptorFactory, final CommentsService commentsService) { this.userSession = userSession; this.documentDescriptorFactory = documentDescriptorFactory; this.commentsService = commentsService; } @GetMapping public List<JSONComment> getAll( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentId ) { userSession.assertLoggedIn();
final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), documentId); final ZoneId zoneId = JSONOptions.of(userSession).getZoneId(); return commentsService.getRowCommentsAsJson(documentPath, zoneId); } @PostMapping public void addComment( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentId, @RequestBody final JSONCommentCreateRequest jsonCommentCreateRequest ) { userSession.assertLoggedIn(); final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), documentId); commentsService.addComment(documentPath, jsonCommentCreateRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\comments\CommentsRestController.java
2
请完成以下Java代码
public I_C_BankStatement_Import_File getC_BankStatement_Import_File() { return get_ValueAsPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class); } @Override public void setC_BankStatement_Import_File(final I_C_BankStatement_Import_File C_BankStatement_Import_File) { set_ValueFromPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class, C_BankStatement_Import_File); } @Override public void setC_BankStatement_Import_File_ID (final int C_BankStatement_Import_File_ID) { if (C_BankStatement_Import_File_ID < 1) set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, null); else set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, C_BankStatement_Import_File_ID); } @Override public int getC_BankStatement_Import_File_ID() { return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_ID); } @Override public void setC_BankStatement_Import_File_Log_ID (final int C_BankStatement_Import_File_Log_ID) { if (C_BankStatement_Import_File_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, C_BankStatement_Import_File_Log_ID);
} @Override public int getC_BankStatement_Import_File_Log_ID() { return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_Log_ID); } @Override public void setLogmessage (final @Nullable java.lang.String Logmessage) { set_Value (COLUMNNAME_Logmessage, Logmessage); } @Override public java.lang.String getLogmessage() { return get_ValueAsString(COLUMNNAME_Logmessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File_Log.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isDisabled() {
return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Set<Address> getAddresses() { return addresses; } public void setAddresses(Set<Address> addresses) { this.addresses = addresses; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\security\entities\User.java
1
请完成以下Java代码
public String benchmarkStringFormat_d() { return String.format(formatDigit, sampleNumber); } @Benchmark public boolean benchmarkStringEquals() { return longString.equals(baeldung); } @Benchmark public boolean benchmarkStringEqualsIgnoreCase() { return longString.equalsIgnoreCase(baeldung); } @Benchmark public boolean benchmarkStringMatches() { return longString.matches(baeldung); } @Benchmark public boolean benchmarkPrecompiledMatches() { return longPattern.matcher(baeldung).matches(); }
@Benchmark public int benchmarkStringCompareTo() { return longString.compareTo(baeldung); } @Benchmark public boolean benchmarkStringIsEmpty() { return longString.isEmpty(); } @Benchmark public boolean benchmarkStringLengthZero() { return longString.length() == 0; } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(StringPerformance.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-strings\src\main\java\com\baeldung\stringperformance\StringPerformance.java
1
请完成以下Java代码
public abstract class Tree { private double mass; private double height; private Position position; public Tree(double mass, double height) { this.mass = mass; this.height = height; } public void setMass(double mass) { this.mass = mass; } public void setHeight(double height) { this.height = height; } public void setPosition(Position position) { this.position = position; }
public double getMass() { return mass; } public double getHeight() { return height; } public Position getPosition() { return position; } @Override public String toString() { return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]"; } public abstract Tree copy(); }
repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\prototype\Tree.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleWorkflowService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Transactional public void startProcess(Article article) { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("author", article.getAuthor()); variables.put("url", article.getUrl()); runtimeService.startProcessInstanceByKey("articleReview", variables); } @Transactional public List<Article> getTasks(String assignee) { List<Task> tasks = taskService.createTaskQuery() .taskCandidateGroup(assignee) .list();
List<Article> articles = tasks.stream() .map(task -> { Map<String, Object> variables = taskService.getVariables(task.getId()); return new Article( task.getId(), (String) variables.get("author"), (String) variables.get("url")); }) .collect(Collectors.toList()); return articles; } @Transactional public void submitReview(Approval approval) { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("approved", approval.isStatus()); taskService.complete(approval.getId(), variables); } }
repos\tutorials-master\spring-boot-modules\spring-boot-flowable\src\main\java\com\baeldung\service\ArticleWorkflowService.java
2
请完成以下Spring Boot application配置
# WhatsApp API configuration whatsapp.verify_token=BaeldungDemo-Verify-Token whatsapp.api_url=https://graph.facebook.com/v20.0/PHONE_NUMBER_ID/messages whatsapp.access_token=ACCESS_TOKEN # Ollama API configuration ollama.api_url=http://localhost:11434/ ollama.model=qwen2:1.5b ollama.timeout=30 ollama.max_response_length=1000 # Logging configuration logging.level.root=INFO logging.level.com.baeldung.chatbot=DEBUG logging.level.com.baeldung.dynamically.updating.properties=DEBUG logging.level.org.springframework.boot.actuate=DEBUG # We can disable Spring Cloud Config to prevent the application from trying to connect to a configuratio
n server spring.cloud.config.enabled=false # Enable the Spring Boot Actuator endpoints to trigger a refresh management.endpoint.refresh.enabled=true management.endpoints.web.exposure.include=refresh # Example property to be changed at runtime my.custom.property=defaultValue
repos\tutorials-master\spring-boot-modules\spring-boot-3-3\src\main\resources\application.properties
2
请完成以下Java代码
public class CustomRealm extends JdbcRealm { private Logger logger = LoggerFactory.getLogger(CustomRealm.class); private Map<String, String> credentials = new HashMap<>(); private Map<String, Set<String>> roles = new HashMap<>(); private Map<String, Set<String>> permissions = new HashMap<>(); { credentials.put("Tom", "password"); credentials.put("Jerry", "password"); roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN"))); roles.put("Tom", new HashSet<>(Arrays.asList("USER"))); permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE"))); permissions.put("USER", new HashSet<>(Arrays.asList("READ"))); } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken userToken = (UsernamePasswordToken) token; if (userToken.getUsername() == null || userToken.getUsername() .isEmpty() || !credentials.containsKey(userToken.getUsername())) { throw new UnknownAccountException("User doesn't exist"); } return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName()); } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Set<String> roles = new HashSet<>(); Set<String> permissions = new HashSet<>(); for (Object user : principals) { try { roles.addAll(getRoleNamesForUser(null, (String) user)); permissions.addAll(getPermissions(null, null, roles)); } catch (SQLException e) {
logger.error(e.getMessage()); } } SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles); authInfo.setStringPermissions(permissions); return authInfo; } @Override protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException { if (!roles.containsKey(username)) { throw new SQLException("User doesn't exist"); } return roles.get(username); } @Override protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException { Set<String> userPermissions = new HashSet<>(); for (String role : roles) { if (!permissions.containsKey(role)) { throw new SQLException("Role doesn't exist"); } userPermissions.addAll(permissions.get(role)); } return userPermissions; } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\shiro\CustomRealm.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Doctor doctor = (Doctor) o; return Objects.equals(this._id, doctor._id) && Objects.equals(this.gender, doctor.gender) && Objects.equals(this.titleShort, doctor.titleShort) && Objects.equals(this.title, doctor.title) && Objects.equals(this.firstName, doctor.firstName) && Objects.equals(this.lastName, doctor.lastName) && Objects.equals(this.address, doctor.address) && Objects.equals(this.postalCode, doctor.postalCode) && Objects.equals(this.city, doctor.city) && Objects.equals(this.phone, doctor.phone) && Objects.equals(this.fax, doctor.fax) && Objects.equals(this.timestamp, doctor.timestamp); } @Override public int hashCode() { return Objects.hash(_id, gender, titleShort, title, firstName, lastName, address, postalCode, city, phone, fax, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Doctor {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" titleShort: ").append(toIndentedString(titleShort)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Doctor.java
2
请完成以下Java代码
public void setDerKurier_DeliveryOrderLine_ID (int DerKurier_DeliveryOrderLine_ID) { if (DerKurier_DeliveryOrderLine_ID < 1) set_Value (COLUMNNAME_DerKurier_DeliveryOrderLine_ID, null); else set_Value (COLUMNNAME_DerKurier_DeliveryOrderLine_ID, Integer.valueOf(DerKurier_DeliveryOrderLine_ID)); } /** Get DerKurier_DeliveryOrderLine. @return DerKurier_DeliveryOrderLine */ @Override public int getDerKurier_DeliveryOrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DerKurier_DeliveryOrderLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DerKurier_DeliveryOrderLine_Package. @param DerKurier_DeliveryOrderLine_Package_ID DerKurier_DeliveryOrderLine_Package */ @Override public void setDerKurier_DeliveryOrderLine_Package_ID (int DerKurier_DeliveryOrderLine_Package_ID) { if (DerKurier_DeliveryOrderLine_Package_ID < 1) set_ValueNoCheck (COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID, null); else set_ValueNoCheck (COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID, Integer.valueOf(DerKurier_DeliveryOrderLine_Package_ID)); } /** Get DerKurier_DeliveryOrderLine_Package. @return DerKurier_DeliveryOrderLine_Package */ @Override public int getDerKurier_DeliveryOrderLine_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Package getM_Package() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class); }
@Override public void setM_Package(org.compiere.model.I_M_Package M_Package) { set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package); } /** Set Packstück. @param M_Package_ID Shipment Package */ @Override public void setM_Package_ID (int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID)); } /** Get Packstück. @return Shipment Package */ @Override public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine_Package.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomerTradeMarginLine { @Nullable CustomerTradeMarginLineId customerTradeMarginLineId; @NonNull CustomerTradeMarginId customerTradeMarginId; @NonNull Boolean active; @NonNull Integer seqNo; @NonNull Integer marginPercent; @Nullable BPartnerId customerId; @Nullable ProductId productId; @Nullable ProductCategoryId productCategoryId; @Builder CustomerTradeMarginLine( @Nullable final CustomerTradeMarginLineId customerTradeMarginLineId, @NonNull final CustomerTradeMarginId customerTradeMarginId, @NonNull final Boolean active, @NonNull final Integer seqNo, @NonNull final Integer marginPercent, @Nullable final BPartnerId customerId, @Nullable final ProductId productId, @Nullable final ProductCategoryId productCategoryId) { this.customerTradeMarginLineId = customerTradeMarginLineId; this.customerTradeMarginId = customerTradeMarginId; this.active = active; this.seqNo = seqNo; this.marginPercent = marginPercent; this.customerId = customerId; this.productId = productId; this.productCategoryId = productCategoryId; } @NonNull public CustomerTradeMarginLineId getIdNotNull() { if (this.customerTradeMarginLineId == null) { throw new AdempiereException("getIdNotNull() should be called only for already persisted CustomerTradeMarginLine objects!") .appendParametersToMessage() .setParameter("CustomerTradeMarginLine", this); } return customerTradeMarginLineId; } public boolean appliesTo(@NonNull final MappingCriteria mappingCriteria) { return appliesToCustomer(mappingCriteria.getCustomerId()) && appliesToProduct(mappingCriteria.getProductId()) && appliesToProductCategory(mappingCriteria.getProductCategoryId());
} private boolean appliesToCustomer(@NonNull final BPartnerId customerCandidateId) { if (this.customerId == null) { return true; } return this.customerId.equals(customerCandidateId); } private boolean appliesToProduct(@NonNull final ProductId productId) { if (this.productId == null) { return true; } return this.productId.equals(productId); } private boolean appliesToProductCategory(@NonNull final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; } return this.productCategoryId.equals(productCategoryId); } @NonNull public Percent getPercent() { return Percent.of(this.marginPercent); } @Value @Builder public static class MappingCriteria { @NonNull BPartnerId customerId; @NonNull ProductId productId; @NonNull ProductCategoryId productCategoryId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginLine.java
2
请在Spring Boot框架中完成以下Java代码
public class EmployeeDAO { private JdbcTemplate jdbcTemplate; private NamedParameterJdbcTemplate namedJdbcTemplate; public void setDataSource(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } public List<Employee> getEmployeesFromIdListNamed(List<Integer> ids) { SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); List<Employee> employees = namedJdbcTemplate.query( "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", parameters, (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); return employees; } public List<Employee> getEmployeesFromIdList(List<Integer> ids) { String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); List<Employee> employees = jdbcTemplate.query( String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name")), ids.toArray()); return employees; } public List<Employee> getEmployeesFromLargeIdList(List<Integer> ids) {
jdbcTemplate.execute("CREATE TEMPORARY TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)"); List<Object[]> employeeIds = new ArrayList<>(); for (Integer id : ids) { employeeIds.add(new Object[] { id }); } jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds); List<Employee> employees = jdbcTemplate.query( "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); jdbcTemplate.update("DELETE FROM employee_tmp"); return employees; } }
repos\tutorials-master\persistence-modules\spring-jdbc\src\main\java\com\baeldung\spring\jdbc\template\inclause\EmployeeDAO.java
2
请完成以下Java代码
public final class InvoiceLineAttribute implements IInvoiceLineAttribute { private final String aggregationKey; @ToStringBuilder(skip = true) private final I_M_AttributeInstance attributeInstanceTemplate; /** * @param attributeInstance attribute instance used to extract the informations from */ public InvoiceLineAttribute(@NonNull final I_M_AttributeInstance attributeInstance) { // // Build aggregation key { final int attributeId = attributeInstance.getM_Attribute_ID(); final I_M_Attribute attribute = Services.get(IAttributeDAO.class).getAttributeRecordById(attributeId); final StringBuilder aggregationKey = new StringBuilder(); aggregationKey.append(attribute.getName()); aggregationKey.append("="); String value = attributeInstance.getValue(); if (Check.isEmpty(value)) { BigDecimal valueNumber = attributeInstance.getValueNumber(); valueNumber = NumberUtils.stripTrailingDecimalZeros(valueNumber); value = valueNumber.toString(); // try valueNumber too } aggregationKey.append(value); this.aggregationKey = aggregationKey.toString(); } // // Copy given attribute instance, we will use it as a template this.attributeInstanceTemplate = InterfaceWrapperHelper.newInstance(I_M_AttributeInstance.class, attributeInstance); InterfaceWrapperHelper.copyValues(attributeInstance, attributeInstanceTemplate); this.attributeInstanceTemplate.setM_AttributeSetInstance(null); // reset it this.attributeInstanceTemplate.setIsActive(true); InterfaceWrapperHelper.setSaveDeleteDisabled(attributeInstanceTemplate, true); } @Override public String toString() { return ObjectUtils.toString(this); } @Override public boolean equals(final Object obj) {
if (this == obj) { return true; } final InvoiceLineAttribute other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.aggregationKey, other.aggregationKey) .isEqual(); } @Override public int hashCode() { return new HashcodeBuilder() .append(aggregationKey) .toHashcode(); } @Override public String toAggregationKey() { return aggregationKey; } @Override public I_M_AttributeInstance getAttributeInstanceTemplate() { return attributeInstanceTemplate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAttribute.java
1
请完成以下Java代码
protected void build(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule_Alloc rsa) { super.build(rsa); final I_M_ReceiptSchedule_Alloc rsaHU = InterfaceWrapperHelper.create(rsa, I_M_ReceiptSchedule_Alloc.class); // // HU_QtyAllocated final StockQtyAndUOMQty huQtyAllocatedSrc = getHU_QtyAllocated(); final BigDecimal huQtyAllocated; if (huQtyAllocatedSrc != null) { // // Convert qty in Stock-UOM from given UOM to receipt schedule's UOM final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); final UomId uomIdTo = UomId.ofRepoId(receiptSchedule.getC_UOM_ID()); final ProductId productId = ProductId.ofRepoId(receiptSchedule.getM_Product_ID()); final UOMConversionContext uomConversionCtx = UOMConversionContext.of(productId); huQtyAllocated = uomConversionBL .convertQuantityTo(huQtyAllocatedSrc.getStockQty(), uomConversionCtx, uomIdTo) .toBigDecimal(); } else { huQtyAllocated = null; } rsaHU.setHU_QtyAllocated(huQtyAllocated); // // LU/TU/VHU rsaHU.setM_LU_HU(getM_LU_HU()); rsaHU.setM_TU_HU(getM_TU_HU()); rsaHU.setVHU(getVHU()); } public HUReceiptScheduleAllocBuilder setHU_QtyAllocated(@NonNull final StockQtyAndUOMQty huQtyAllocated) { _huQtyAllocated = huQtyAllocated; return this; } private StockQtyAndUOMQty getHU_QtyAllocated() {
return _huQtyAllocated; } private I_M_HU getM_LU_HU() { return _luHU; } public HUReceiptScheduleAllocBuilder setM_LU_HU(final I_M_HU luHU) { _luHU = luHU; return this; } private I_M_HU getM_TU_HU() { return _tuHU; } public HUReceiptScheduleAllocBuilder setM_TU_HU(final I_M_HU tuHU) { _tuHU = tuHU; return this; } private I_M_HU getVHU() { return _vhu; } public HUReceiptScheduleAllocBuilder setVHU(final I_M_HU vhu) { _vhu = vhu; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\HUReceiptScheduleAllocBuilder.java
1
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder("MPrintFont["); sb.append("ID=").append(get_ID()) .append(",Name=").append(getName()) .append("PSName=").append(getFont().getPSName()) .append(getFont()) .append("]"); return sb.toString(); } // toString /** * Get PostScript Level 2 definition. * e.g. /dialog 12 selectfont * @return PostScript command */ public String toPS() { final StringBuilder sb = new StringBuilder("/"); sb.append(getFont().getPSName()); if (getFont().isBold()) sb.append(" Bold"); if (getFont().isItalic()) sb.append(" Italic"); sb.append(" ").append(getFont().getSize()) .append(" selectfont"); return sb.toString(); } // toPS /** Cached Fonts */ private static final CCache<Integer,MPrintFont> s_fonts = new CCache<Integer,MPrintFont>(Table_Name, 20); /**
* Get Font * @param AD_PrintFont_ID id * @return Font */ static public MPrintFont get (final int AD_PrintFont_ID) { final MPrintFont printFont = s_fonts.get(AD_PrintFont_ID, new Callable<MPrintFont>() { @Override public MPrintFont call() throws Exception { return new MPrintFont (Env.getCtx(), AD_PrintFont_ID, ITrx.TRXNAME_None); } }); return printFont; } // get } // MPrintFont
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFont.java
1
请完成以下Java代码
public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Target URL. @param TargetURL URL for the Target */ public void setTargetURL (String TargetURL) { set_Value (COLUMNNAME_TargetURL, TargetURL); } /** Get Target URL. @return URL for the Target */ public String getTargetURL () { return (String)get_Value(COLUMNNAME_TargetURL); } /** Set User Agent. @param UserAgent Browser Used */ public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } public I_W_ClickCount getW_ClickCount() throws RuntimeException { return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name) .getPO(getW_ClickCount_ID(), get_TrxName()); }
/** Set Click Count. @param W_ClickCount_ID Web Click Management */ public void setW_ClickCount_ID (int W_ClickCount_ID) { if (W_ClickCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID)); } /** Get Click Count. @return Web Click Management */ public int getW_ClickCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Web Click. @param W_Click_ID Individual Web Click */ public void setW_Click_ID (int W_Click_ID) { if (W_Click_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Click_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID)); } /** Get Web Click. @return Individual Web Click */ public int getW_Click_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Click.java
1
请完成以下Java代码
private int getAD_Menu_ID() { Check.assumeNotNull(adMenuId, "adMenuId shall be set"); return adMenuId; } private String getId() { final int adMenuId = getAD_Menu_ID(); if (type == MenuNodeType.NewRecord) { return adMenuId + "-new"; } else { return String.valueOf(adMenuId); } } public Builder setCaption(final String caption) { this.caption = caption; return this; } public Builder setCaptionBreadcrumb(final String captionBreadcrumb) { this.captionBreadcrumb = captionBreadcrumb; return this; } public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId) { this.type = type; this.elementId = elementId; return this;
} public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId) { return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId)); } public void setTypeGroup() { setType(MenuNodeType.Group, null); } public void addChildToFirstsList(@NonNull final MenuNode child) { childrenFirst.add(child); } public void addChild(@NonNull final MenuNode child) { childrenRest.add(child); } public Builder setMainTableName(final String mainTableName) { this.mainTableName = mainTableName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java
1
请在Spring Boot框架中完成以下Java代码
public FormService getFormService() { return processEngine.getFormService(); } @Bean(name = "taskService") @Override public TaskService getTaskService() { return processEngine.getTaskService(); } @Bean(name = "historyService") @Override public HistoryService getHistoryService() { return processEngine.getHistoryService(); } @Bean(name = "identityService") @Override public IdentityService getIdentityService() { return processEngine.getIdentityService(); } @Bean(name = "managementService") @Override public ManagementService getManagementService() { return processEngine.getManagementService(); } @Bean(name = "authorizationService") @Override public AuthorizationService getAuthorizationService() { return processEngine.getAuthorizationService(); } @Bean(name = "caseService")
@Override public CaseService getCaseService() { return processEngine.getCaseService(); } @Bean(name = "filterService") @Override public FilterService getFilterService() { return processEngine.getFilterService(); } @Bean(name = "externalTaskService") @Override public ExternalTaskService getExternalTaskService() { return processEngine.getExternalTaskService(); } @Bean(name = "decisionService") @Override public DecisionService getDecisionService() { return processEngine.getDecisionService(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringProcessEngineServicesConfiguration.java
2
请完成以下Java代码
public String toString() { return toJson(this); } @JsonValue public String toJson() { return toJson(this); } public String getTableAlias() { String tableAlias = this._tableAlias; if (tableAlias == null) { tableAlias = this._tableAlias = "d" + idInt; } return tableAlias; } @Nullable public AdTabId toAdTabId() { if (PREFIX_AD_TAB_ID.equals(idPrefix)) { return AdTabId.ofRepoId(idInt); } return null; } @Override public int compareTo(@Nullable final DetailId o) { if (o == null) { return 1; }
return Objects.compare(toJson(), o.toJson(), Comparator.naturalOrder()); } public static boolean equals(@Nullable final DetailId o1, @Nullable final DetailId o2) { return Objects.equals(o1, o2); } public int getIdIntAssumingPrefix(@NonNull final String expectedPrefix) { assertIdPrefix(expectedPrefix); return getIdInt(); } private void assertIdPrefix(@NonNull final String expectedPrefix) { if (!expectedPrefix.equals(idPrefix)) { throw new AdempiereException("Expected id prefix `" + expectedPrefix + "` for " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DetailId.java
1
请完成以下Java代码
public static final WebuiImageId ofNullableObject(final Object obj) { if (obj == null) { return null; } try { final int id; if (obj instanceof Number) { id = ((Number)obj).intValue(); } else { final String idStr = obj.toString().trim(); id = !idStr.isEmpty() ? Integer.parseInt(idStr) : -1; } return ofRepoIdOrNull(id); } catch (final Exception ex) { throw new AdempiereException("Cannot convert `" + obj + "` from " + obj.getClass() + " to " + WebuiImageId.class, ex); } } public static WebuiImageId ofRepoId(final int repoId) {
return new WebuiImageId(repoId); } public static WebuiImageId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } private final int repoId; public WebuiImageId(final int repoId) { Check.assumeGreaterThanZero(repoId, "repoId"); this.repoId = repoId; } @JsonValue @Override public int getRepoId() { return repoId; } public AdImageId toAdImageId() {return AdImageId.ofRepoId(repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\WebuiImageId.java
1
请在Spring Boot框架中完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public AccountEntity getAccount() { return account; } public void setAccount(AccountEntity account) { this.account = account; } }
repos\spring-examples-java-17\spring-bank\bank-server\src\main\java\itx\examples\springbank\server\repository\model\ClientEntity.java
2
请在Spring Boot框架中完成以下Java代码
OtlpMeterRegistry otlpMeterRegistryVirtualThreads(OtlpConfig otlpConfig, Clock clock, ObjectProvider<OtlpMetricsSender> metricsSender) { VirtualThreadTaskExecutor executor = new VirtualThreadTaskExecutor("otlp-meter-registry-"); return builder(otlpConfig, clock, metricsSender).threadFactory(executor.getVirtualThreadFactory()).build(); } private OtlpMeterRegistry.Builder builder(OtlpConfig otlpConfig, Clock clock, ObjectProvider<OtlpMetricsSender> metricsSender) { OtlpMeterRegistry.Builder builder = OtlpMeterRegistry.builder(otlpConfig).clock(clock); metricsSender.ifAvailable(builder::metricsSender); return builder; } /** * Adapts {@link OtlpMetricsProperties} to {@link OtlpMetricsConnectionDetails}. */ static class PropertiesOtlpMetricsConnectionDetails implements OtlpMetricsConnectionDetails {
private final OtlpMetricsProperties properties; PropertiesOtlpMetricsConnectionDetails(OtlpMetricsProperties properties) { this.properties = properties; } @Override public @Nullable String getUrl() { return this.properties.getUrl(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsExportAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public AllocationAmounts movePayAmtToDiscount() { if (payAmt.signum() == 0) { return this; } else { return toBuilder() .payAmt(payAmt.toZero()) .discountAmt(discountAmt.add(payAmt)) .build(); } } public AllocationAmounts movePayAmtToWriteOff() { if (payAmt.signum() == 0) { return this; } else { return toBuilder() .payAmt(payAmt.toZero()) .writeOffAmt(writeOffAmt.add(payAmt)) .build(); } } public AllocationAmounts add(@NonNull final AllocationAmounts other) { return toBuilder() .payAmt(this.payAmt.add(other.payAmt)) .discountAmt(this.discountAmt.add(other.discountAmt)) .writeOffAmt(this.writeOffAmt.add(other.writeOffAmt)) .invoiceProcessingFee(this.invoiceProcessingFee.add(other.invoiceProcessingFee)) .build(); } public AllocationAmounts subtract(@NonNull final AllocationAmounts other) { return toBuilder() .payAmt(this.payAmt.subtract(other.payAmt)) .discountAmt(this.discountAmt.subtract(other.discountAmt)) .writeOffAmt(this.writeOffAmt.subtract(other.writeOffAmt)) .invoiceProcessingFee(this.invoiceProcessingFee.subtract(other.invoiceProcessingFee)) .build(); } public AllocationAmounts convertToRealAmounts(@NonNull final InvoiceAmtMultiplier invoiceAmtMultiplier) { return negateIf(invoiceAmtMultiplier.isNegateToConvertToRealValue()); } private AllocationAmounts negateIf(final boolean condition) { return condition ? negate() : this; } public AllocationAmounts negate() { if (isZero()) { return this;
} return toBuilder() .payAmt(this.payAmt.negate()) .discountAmt(this.discountAmt.negate()) .writeOffAmt(this.writeOffAmt.negate()) .invoiceProcessingFee(this.invoiceProcessingFee) // never negate the processing fee because it will be paid to the service provider no matter what kind of invoice it is applied to. .build(); } public Money getTotalAmt() { return payAmt.add(discountAmt).add(writeOffAmt).add(invoiceProcessingFee); } public boolean isZero() { return payAmt.signum() == 0 && discountAmt.signum() == 0 && writeOffAmt.signum() == 0 && invoiceProcessingFee.signum() == 0; } public AllocationAmounts toZero() { return isZero() ? this : AllocationAmounts.zero(getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationAmounts.java
2
请在Spring Boot框架中完成以下Java代码
public void register(User user, HttpServletRequest request) { validator.validate(user); if(validator.hasErrors()) { result.include("errors", validator.getErrors()); } validator.onErrorRedirectTo(this).registrationForm(); if(!user.getPassword() .equals(request.getParameter("password_confirmation"))) { result.include("error", "Passwords Do Not Match"); result.redirectTo(this).registrationForm(); } user.setPassword( BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); Object resp = userDao.add(user); if(resp != null) { result.include("status", "Registration Successful! Now Login"); result.redirectTo(this).loginForm(); } else { result.include("error", "There was an error during registration"); result.redirectTo(this).registrationForm(); } } @Get("/login") public void loginForm() { result.use(FreemarkerView.class).withTemplate("auth/login"); } @Post("/login") public void login(HttpServletRequest request) {
String password = request.getParameter("user.password"); String email = request.getParameter("user.email"); if(email.isEmpty() || password.isEmpty()) { result.include("error", "Email/Password is Required!"); result.redirectTo(AuthController.class).loginForm(); } User user = userDao.findByEmail(email); if(user != null && BCrypt.checkpw(password, user.getPassword())) { userInfo.setUser(user); result.include("status", "Login Successful!"); result.redirectTo(IndexController.class).index(); } else { result.include("error", "Email/Password Does Not Match!"); result.redirectTo(AuthController.class).loginForm(); } } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\controllers\AuthController.java
2
请完成以下Java代码
private CustomsInvoiceLine allocateShipmentLine( @NonNull final CustomsInvoiceLine customsInvoiceLineForProduct, @NonNull final InOutAndLineId inOutAndLineId, @NonNull final CurrencyId currencyId) { final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final CustomsInvoiceLineAlloc existingAlloc = customsInvoiceLineForProduct.getAllocationByInOutLineId(inOutAndLineId).orElse(null); Quantity qty = customsInvoiceLineForProduct.getQuantity(); Money lineNetAmt = customsInvoiceLineForProduct.getLineNetAmt(); if (existingAlloc != null) { final Quantity existingAllocQty = existingAlloc.getQuantityInPriceUOM(); final Money existingAllocNetAmt = existingAlloc.getNetAmt(); qty = Quantitys.subtract(UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), qty, existingAllocQty); lineNetAmt = lineNetAmt.subtract(existingAllocNetAmt); customsInvoiceLineForProduct.removeAllocation(existingAlloc); } final CustomsInvoiceLineAlloc newAlloc; { final Quantity inoutLineQty = getInOutLineQty(inOutAndLineId); final ProductPrice inoutLinePrice = getInOutLinePriceConverted(inOutAndLineId, currencyId); final Quantity inoutLineQtyInPriceUOM = uomConversionBL.convertQuantityTo(inoutLineQty, UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), inoutLinePrice.getUomId()); newAlloc = CustomsInvoiceLineAlloc.builder()
.inoutAndLineId(inOutAndLineId) .price(inoutLinePrice.toMoney()) .quantityInPriceUOM(inoutLineQtyInPriceUOM) .build(); customsInvoiceLineForProduct.addAllocation(newAlloc); } qty = Quantitys.add(UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), qty, newAlloc.getQuantityInPriceUOM()); lineNetAmt = lineNetAmt.add(newAlloc.getNetAmt()); return customsInvoiceLineForProduct.toBuilder() .lineNetAmt(lineNetAmt) .quantity(qty) .build(); } private Optional<CustomsInvoiceLine> findCustomsInvoiceLineForProductId(@NonNull final ProductId productId, @NonNull final Collection<CustomsInvoiceLine> existingLines) { return existingLines.stream() .filter(line -> line.getProductId().equals(productId)) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoiceService.java
1
请在Spring Boot框架中完成以下Java代码
public class UserInfoCollectionResource extends BaseUserResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected IdentityService identityService; @ApiOperation(value = "List user’s info", tags = { "Users" }, nickname = "listUserInfo") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the user was found and list of info (key and url) is returned."), @ApiResponse(code = 404, message = "Indicates the requested user was not found.") }) @GetMapping(value = "/identity/users/{userId}/info", produces = "application/json") public List<UserInfoResponse> getUserInfo(@ApiParam(name = "userId") @PathVariable String userId) { User user = getUserFromRequest(userId); return restResponseFactory.createUserInfoKeysResponse(identityService.getUserInfoKeys(user.getId()), user.getId()); } @ApiOperation(value = "Create a new user’s info entry", tags = { "Users" }, nickname = "createUserInfo", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the user was found and the info has been created."), @ApiResponse(code = 400, message = "Indicates the key or value was missing from the request body. Status description contains additional information about the error."), @ApiResponse(code = 404, message = "Indicates the requested user was not found."), @ApiResponse(code = 409, message = "Indicates there is already an info-entry with the given key for the user, update the resource instance (PUT).") }) @PostMapping(value = "/identity/users/{userId}/info", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public UserInfoResponse setUserInfo(@ApiParam(name = "userId") @PathVariable String userId, @RequestBody UserInfoRequest userRequest) {
User user = getUserFromRequest(userId); if (userRequest.getKey() == null) { throw new FlowableIllegalArgumentException("The key cannot be null."); } if (userRequest.getValue() == null) { throw new FlowableIllegalArgumentException("The value cannot be null."); } String existingValue = identityService.getUserInfo(user.getId(), userRequest.getKey()); if (existingValue != null) { throw new FlowableConflictException("User info with key '" + userRequest.getKey() + "' already exists for this user."); } identityService.setUserInfo(user.getId(), userRequest.getKey(), userRequest.getValue()); return restResponseFactory.createUserInfoResponse(userRequest.getKey(), userRequest.getValue(), user.getId()); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserInfoCollectionResource.java
2
请在Spring Boot框架中完成以下Java代码
public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public LocalDate getPublished() { return published; } public void setPublished(LocalDate published) { this.published = published; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BookDTO bookDTO = (BookDTO) o; if (bookDTO.getId() == null || getId() == null) {
return false; } return Objects.equals(getId(), bookDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "BookDTO{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\BookDTO.java
2
请在Spring Boot框架中完成以下Java代码
public SuperStreamBuilder name(String name) { this.name = name; return this; } /** * Set the partitions number. * @param partitions the partitions number * @return the builder */ public SuperStreamBuilder partitions(int partitions) { this.partitions = partitions; return this; } /** * Set a strategy to determine routing keys to use for the * partitions. The first parameter is the queue name, the second the number of * partitions, the returned list must have a size equal to the partitions. * @param routingKeyStrategy the strategy * @return the builder */ public SuperStreamBuilder routingKeyStrategy(BiFunction<String, Integer, List<String>> routingKeyStrategy) { this.routingKeyStrategy = routingKeyStrategy; return this; } /** * Builds a final Super Stream. * @return the Super Stream instance */
public SuperStream build() { if (!StringUtils.hasText(this.name)) { throw new IllegalArgumentException("Stream name can't be empty"); } if (this.partitions <= 0) { throw new IllegalArgumentException( String.format("Partitions number should be great then zero. Current value; %d", this.partitions) ); } if (this.routingKeyStrategy == null) { return new SuperStream(this.name, this.partitions, this.arguments); } return new SuperStream(this.name, this.partitions, this.routingKeyStrategy, this.arguments); } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\config\SuperStreamBuilder.java
2
请完成以下Java代码
default Optional<Object> get_ValueIfExists(@NonNull final String variableName, @NonNull final Class<?> targetType) { if (Integer.class.equals(targetType) || int.class.equals(targetType)) { final Integer valueInt = get_ValueAsInt(variableName, null); return Optional.ofNullable(valueInt); } else if (java.util.Date.class.equals(targetType)) { final java.util.Date valueDate = get_ValueAsDate(variableName, null); return Optional.ofNullable(valueDate); } else if (Timestamp.class.equals(targetType)) { final Timestamp valueDate = TimeUtil.asTimestamp(get_ValueAsDate(variableName, null)); return Optional.ofNullable(valueDate); }
else if (Boolean.class.equals(targetType)) { final Boolean valueBoolean = get_ValueAsBoolean(variableName, null); return Optional.ofNullable(valueBoolean); } else { final Object valueObj = get_ValueAsObject(variableName); return Optional.ofNullable(valueObj); } } default Evaluatee andComposeWith(final Evaluatee other) { return Evaluatees.compose(this, other); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Evaluatee.java
1
请完成以下Java代码
public String getASIDescription() { return asiDescription; } public int getASIId() { return asiId; } public String getPartnerName() { return partnerName; }
public String getDocBaseType() { return docBaseType; } public String getDocumentNo() { return documentNo; } public String getWarehouseName() { return warehouseName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\dao\impl\OrderLineHistoryVO.java
1
请在Spring Boot框架中完成以下Java代码
public void init() { this.transportCallbackExecutor = ThingsBoardExecutors.newWorkStealingPool(maxCallbackThreads, getClass()); TbQueueProducer<TbProtoQueueMsg<TransportApiResponseMsg>> producer = tbCoreQueueFactory.createTransportApiResponseProducer(); TbQueueConsumer<TbProtoQueueMsg<TransportApiRequestMsg>> consumer = tbCoreQueueFactory.createTransportApiRequestConsumer(); String key = StatsType.TRANSPORT.getName(); MessagesStats queueStats = statsFactory.createMessagesStats(key); DefaultTbQueueResponseTemplate.DefaultTbQueueResponseTemplateBuilder <TbProtoQueueMsg<TransportApiRequestMsg>, TbProtoQueueMsg<TransportApiResponseMsg>> builder = DefaultTbQueueResponseTemplate.builder(); builder.requestTemplate(consumer); builder.responseTemplate(producer); builder.maxPendingRequests(maxPendingRequests); builder.requestTimeout(requestTimeout); builder.pollInterval(responsePollDuration); builder.executor(transportCallbackExecutor); builder.handler(transportApiService); builder.stats(queueStats); transportApiTemplate = builder.build(); }
@AfterStartUp(order = AfterStartUp.REGULAR_SERVICE) public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { log.info("Received application ready event. Starting polling for events."); transportApiTemplate.subscribe(); transportApiTemplate.launch(transportApiService); } @PreDestroy public void destroy() { if (transportApiTemplate != null) { transportApiTemplate.stop(); } if (transportCallbackExecutor != null) { transportCallbackExecutor.shutdownNow(); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\transport\TbCoreTransportApiService.java
2
请完成以下Java代码
public void postLoad() { // make sure the serializer is initialized typedValueField.postLoad(); } // getters and setters ////////////////////////////////////////////////////// public String getTypeName() { return typedValueField.getTypeName(); } public String getVariableTypeName() { return getTypeName(); } public Date getTime() { return timestamp; } @Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision
+ ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
1
请完成以下Java代码
void onPubcompReceived() { pubrelRetransmissionHandler.stop(); } void onChannelClosed() { publishRetransmissionHandler.stop(); pubrelRetransmissionHandler.stop(); if (payload != null) { payload.release(); } } static Builder builder() { return new Builder(); } static class Builder { private int messageId; private Promise<Void> future; private ByteBuf payload; private MqttPublishMessage message; private MqttQoS qos; private String ownerId; private MqttClientConfig.RetransmissionConfig retransmissionConfig; private PendingOperation pendingOperation; Builder messageId(int messageId) { this.messageId = messageId; return this; } Builder future(Promise<Void> future) { this.future = future; return this; } Builder payload(ByteBuf payload) { this.payload = payload; return this; } Builder message(MqttPublishMessage message) { this.message = message; return this; } Builder qos(MqttQoS qos) {
this.qos = qos; return this; } Builder ownerId(String ownerId) { this.ownerId = ownerId; return this; } Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingPublish build() { return new MqttPendingPublish(messageId, future, payload, message, qos, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingPublish.java
1
请在Spring Boot框架中完成以下Java代码
class WebuiHUProcessDescriptor { @NonNull ProcessDescriptor processDescriptor; @NonNull @Getter(AccessLevel.NONE) HUProcessDescriptor huProcessDescriptor; public ProcessId getProcessId() { return processDescriptor.getProcessId(); } public AdProcessId getReportAdProcessId() { return huProcessDescriptor.getProcessId(); } public DocumentEntityDescriptor getParametersDescriptor() { return processDescriptor.getParametersDescriptor(); } public WebuiRelatedProcessDescriptor toWebuiRelatedProcessDescriptor() {
return WebuiRelatedProcessDescriptor.builder() .processId(processDescriptor.getProcessId()) .internalName(processDescriptor.getInternalName()) .processCaption(processDescriptor.getCaption()) .processDescription(processDescriptor.getDescription()) .displayPlace(DisplayPlace.ViewQuickActions) .preconditionsResolutionSupplier(ProcessPreconditionsResolution::accept) .build(); } public boolean appliesToHUUnitType(final HuUnitType huUnitType) { return huProcessDescriptor.appliesToHUUnitType(huUnitType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\WebuiHUProcessDescriptor.java
2
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); }
@Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectTask.java
1
请在Spring Boot框架中完成以下Java代码
public PersistenceUnitTransactionType getTransactionType() { return transactionType; } public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { this.jtaDataSource = jtaDataSource; this.nonjtaDataSource = null; transactionType = PersistenceUnitTransactionType.JTA; return this; } @Override public DataSource getJtaDataSource() { return jtaDataSource; } public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { this.nonjtaDataSource = nonJtaDataSource; this.jtaDataSource = null; transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; return this; } @Override public DataSource getNonJtaDataSource() { return nonjtaDataSource; } @Override public List<String> getMappingFileNames() { return mappingFileNames; } @Override public List<URL> getJarFileUrls() { return Collections.emptyList(); } @Override public URL getPersistenceUnitRootUrl() { return null; } @Override public List<String> getManagedClassNames() { return managedClassNames; }
@Override public boolean excludeUnlistedClasses() { return false; } @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.UNSPECIFIED; } @Override public ValidationMode getValidationMode() { return ValidationMode.AUTO; } public Properties getProperties() { return properties; } @Override public String getPersistenceXMLSchemaVersion() { return JPA_VERSION; } @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public void addTransformer(ClassTransformer transformer) { transformers.add(transformer); } @Override public ClassLoader getNewTempClassLoader() { return null; } }
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\jpabootstrap\config\HibernatePersistenceUnitInfo.java
2
请完成以下Java代码
protected final ImmutableMap<Resource, PermissionType> getPermissionsMap() { return permissions; } /** * Gets the "NO permission". * * It is an instance of PermissionType with all accesses revoked and with a generic {@link Resource}. * * <br/> * <b>NOTE to implementor: it is highly recommended that extended classes to not return <code>null</code> here.</b> * * @return no permission instance */ protected PermissionType noPermission() { return null; } @Override public final Optional<PermissionType> getPermissionIfExists(final Resource resource) { return Optional.fromNullable(permissions.get(resource)); } @Override public final PermissionType getPermissionOrDefault(final Resource resource) { // // Get the permission for given resource final Optional<PermissionType> permission = getPermissionIfExists(resource); if (permission.isPresent()) { return permission.get(); } // // Fallback: get the permission defined for the resource of "no permission", if any final PermissionType nonePermission = noPermission(); if (nonePermission == null)
{ return null; } final Resource defaultResource = nonePermission.getResource(); return getPermissionIfExists(defaultResource) // Fallback: return the "no permission" .or(nonePermission); } @Override public final boolean hasPermission(final Permission permission) { return permissions.values().contains(permission); } @Override public final boolean hasAccess(final Resource resource, final Access access) { return getPermissionOrDefault(resource).hasAccess(access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\AbstractPermissions.java
1
请在Spring Boot框架中完成以下Java代码
public class EventsourcingInstanceRepository implements InstanceRepository { private static final Logger log = LoggerFactory.getLogger(EventsourcingInstanceRepository.class); private final InstanceEventStore eventStore; private final Retry retryOptimisticLockException = Retry.max(10) .doBeforeRetry((s) -> log.debug("Retrying after OptimisticLockingException", s.failure())) .filter(OptimisticLockingException.class::isInstance); public EventsourcingInstanceRepository(InstanceEventStore eventStore) { this.eventStore = eventStore; } @Override public Mono<Instance> save(Instance instance) { return this.eventStore.append(instance.getUnsavedEvents()).then(Mono.just(instance.clearUnsavedEvents())); } @Override public Flux<Instance> findAll() { return this.eventStore.findAll() .groupBy(InstanceEvent::getInstance) .flatMap((f) -> f.reduce(Instance.create(f.key()), Instance::apply)); } @Override public Mono<Instance> find(InstanceId id) { return this.eventStore.find(id) .collectList() .filter((e) -> !e.isEmpty()) .map((e) -> Instance.create(id).apply(e)); } @Override public Flux<Instance> findByName(String name) { return findAll().filter((a) -> a.isRegistered() && name.equals(a.getRegistration().getName())); }
@Override public Mono<Instance> compute(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) { return this.find(id) .flatMap((application) -> remappingFunction.apply(id, application)) .switchIfEmpty(Mono.defer(() -> remappingFunction.apply(id, null))) .flatMap(this::save) .retryWhen(this.retryOptimisticLockException); } @Override public Mono<Instance> computeIfPresent(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) { return this.find(id) .flatMap((application) -> remappingFunction.apply(id, application)) .flatMap(this::save) .retryWhen(this.retryOptimisticLockException); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\EventsourcingInstanceRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void setWithoutDeleteReason(Boolean withoutDeleteReason) { this.withoutDeleteReason = withoutDeleteReason; } public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId;
} public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
private void reinitializeLoggingSystem() { log.info("Re-initializing Logging System"); // Reinitialize logging system to pick up any encrypted properties used in logging configuration LoggingApplicationListener loggingListener = ((AbstractApplicationContext) this.applicationContext) .getApplicationListeners() .stream() .filter(LoggingApplicationListener.class::isInstance) .map(LoggingApplicationListener.class::cast) .findFirst() .orElse(null); SpringApplication springApplication = BootstrapSpringApplicationListener.getSpringApplication(); if (loggingListener != null && springApplication != null) { LoggingSystem loggingSystem = LoggingSystem.get(springApplication.getClassLoader()); // Reset logging system loggingSystem.cleanUp(); for (LoggingSystemProperty property : LoggingSystemProperty.values()) { System.clearProperty(property.getEnvironmentVariableName()); } loggingListener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(null, springApplication, null, environment)); log.info("Logging System re-initialized by LoggingApplicationListener"); } } /** * Make sure the system environment wrapper is initialized with setWrapGetSource=true * For custom environments this is done early on in {@link EncryptableSystemEnvironmentPropertySourceWrapperGetSourceWrapperEnvironmentListener} * We'll force the call to that logic here via the static method. */ private void enableSystemEnvironmentSourceEncryptableMapWrapper() { log.info("Re-initializing EncryptableSystemEnvironmentPropertySourceWrapper map delegation"); EncryptableSystemEnvironmentPropertySourceWrapperGetSourceWrapperEnvironmentListener.enableGetSourceWrapping(environment); log.info("EncryptableSystemEnvironmentPropertySourceWrapper map delegation re-initialized"); } /** * {@inheritDoc}
*/ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { log.info("Post-processing PropertySource instances"); MutablePropertySources propSources = environment.getPropertySources(); converter.convertPropertySources(propSources); this.enableSystemEnvironmentSourceEncryptableMapWrapper(); this.reinitializeLoggingSystem(); } /** * {@inheritDoc} */ @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 100; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\EnableEncryptablePropertiesBeanFactoryPostProcessor.java
2
请完成以下Java代码
public class AlfrescoUserTask extends UserTask { public static final String ALFRESCO_SCRIPT_TASK_LISTENER = "org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener"; protected String runAs; protected String scriptProcessor; public String getRunAs() { return runAs; } public void setRunAs(String runAs) { this.runAs = runAs; } public String getScriptProcessor() { return scriptProcessor;
} public void setScriptProcessor(String scriptProcessor) { this.scriptProcessor = scriptProcessor; } public AlfrescoUserTask clone() { AlfrescoUserTask clone = new AlfrescoUserTask(); clone.setValues(this); return clone; } public void setValues(AlfrescoUserTask otherElement) { super.setValues(otherElement); setRunAs(otherElement.getRunAs()); setScriptProcessor(otherElement.getScriptProcessor()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\alfresco\AlfrescoUserTask.java
1
请完成以下Java代码
private @Nullable Mono<Object> getRequestBody() { for (String key : bindingContext.getModel().asMap().keySet()) { if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) { BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key); Object target = result.getTarget(); if (target != null) { return Mono.just(target); } } } return null; } protected static class BodyGrabber { public Publisher<Object> body(@RequestBody Publisher<Object> body) {
return body; } } protected static class BodySender { @ResponseBody public @Nullable Publisher<Object> body() { return null; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java
1
请完成以下Java代码
public void setDelay(Duration delay) { this.delay = delay; } /** * Return the jitter period to enable random retry attempts. * @return the jitter value */ public @Nullable Duration getJitter() { return this.jitter; } /** * Specify a jitter period for the base retry attempt, randomly subtracted or added to * the calculated delay, resulting in a value between {@code delay - jitter} and * {@code delay + jitter} but never below the {@linkplain #getDelay() base delay} or * above the {@linkplain #getMaxDelay() max delay}. * <p> * If a {@linkplain #getMultiplier() multiplier} is specified, it is applied to the * jitter value as well. * @param jitter the jitter value (must be positive) */ public void setJitter(@Nullable Duration jitter) { this.jitter = jitter; } /** * Return the value to multiply the current interval by for each attempt. The default * value, {@code 1.0}, effectively results in a fixed delay. * @return the value to multiply the current interval by for each attempt * @see #DEFAULT_MULTIPLIER */ public Double getMultiplier() { return this.multiplier; } /** * Specify a multiplier for a delay for the next retry attempt. * @param multiplier value to multiply the current interval by for each attempt (must * be greater than or equal to 1)
*/ public void setMultiplier(Double multiplier) { this.multiplier = multiplier; } /** * Return the maximum delay for any retry attempt. * @return the maximum delay */ public Duration getMaxDelay() { return this.maxDelay; } /** * Specify the maximum delay for any retry attempt, limiting how far * {@linkplain #getJitter() jitter} and the {@linkplain #getMultiplier() multiplier} * can increase the {@linkplain #getDelay() delay}. * <p> * The default is unlimited. * @param maxDelay the maximum delay (must be positive) * @see #DEFAULT_MAX_DELAY */ public void setMaxDelay(Duration maxDelay) { this.maxDelay = maxDelay; } /** * Set the factory to use to create the {@link RetryPolicy}, or {@code null} to use * the default. The function takes a {@link Builder RetryPolicy.Builder} initialized * with the state of this instance that can be further configured, or ignored to * restart from scratch. * @param factory a factory to customize the retry policy. */ public void setFactory(@Nullable Function<RetryPolicy.Builder, RetryPolicy> factory) { this.factory = factory; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\retry\RetryPolicySettings.java
1
请完成以下Java代码
public class DefaultLazyEncryptor implements StringEncryptor { private final Singleton<StringEncryptor> singleton; /** * <p>Constructor for DefaultLazyEncryptor.</p> * * @param e a {@link org.springframework.core.env.ConfigurableEnvironment} object * @param customEncryptorBeanName a {@link java.lang.String} object * @param isCustom a boolean * @param bf a {@link org.springframework.beans.factory.BeanFactory} object */ public DefaultLazyEncryptor(final ConfigurableEnvironment e, final String customEncryptorBeanName, boolean isCustom, final BeanFactory bf) { singleton = new Singleton<>(() -> Optional.of(customEncryptorBeanName) .filter(bf::containsBean) .map(name -> (StringEncryptor) bf.getBean(name)) .map(tap(bean -> log.info("Found Custom Encryptor Bean {} with name: {}", bean, customEncryptorBeanName))) .orElseGet(() -> { if (isCustom) { throw new IllegalStateException(String.format("String Encryptor custom Bean not found with name '%s'", customEncryptorBeanName)); } log.info("String Encryptor custom Bean not found with name '{}'. Initializing Default String Encryptor", customEncryptorBeanName); return createDefault(e); })); } /**
* <p>Constructor for DefaultLazyEncryptor.</p> * * @param e a {@link org.springframework.core.env.ConfigurableEnvironment} object */ public DefaultLazyEncryptor(final ConfigurableEnvironment e) { singleton = new Singleton<>(() -> createDefault(e)); } private StringEncryptor createDefault(ConfigurableEnvironment e) { return new StringEncryptorBuilder(JasyptEncryptorConfigurationProperties.bindConfigProps(e), "jasypt.encryptor").build(); } /** {@inheritDoc} */ @Override public String encrypt(final String message) { return singleton.get().encrypt(message); } /** {@inheritDoc} */ @Override public String decrypt(final String encryptedMessage) { return singleton.get().decrypt(encryptedMessage); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\DefaultLazyEncryptor.java
1
请在Spring Boot框架中完成以下Java代码
public Result<SysAnnouncementSend> readAll() { Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>(); LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal(); String userId = sysUser.getId(); LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda(); updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG); updateWrapper.set(SysAnnouncementSend::getReadTime, new Date()); updateWrapper.eq(SysAnnouncementSend::getUserId,userId); //updateWrapper.last("where user_id ='"+userId+"'"); SysAnnouncementSend announcementSend = new SysAnnouncementSend(); sysAnnouncementSendService.update(announcementSend, updateWrapper); JSONObject socketParams = new JSONObject(); socketParams.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC); webSocket.sendMessage(socketParams.toJSONString()); result.setSuccess(true); result.setMessage("全部已读"); return result; } /** * 根据消息发送记录ID获取消息内容 * @param sendId * @return */ @GetMapping(value = "/getOne") public Result<AnnouncementSendModel> getOne(@RequestParam(name="sendId",required=true) String sendId) { AnnouncementSendModel model = sysAnnouncementSendService.getOne(sendId); return Result.ok(model); } /** * 根据业务类型和ID修改阅读状态 * @param busType * @return
*/ @GetMapping(value = "/updateSysAnnounReadFlag") public Result<AnnouncementSendModel> updateSysAnnounReadFlag( @RequestParam(name="busId",required=true) String busId, @RequestParam(name="busType",required=false) String busType) { //更新阅读状态 sysAnnouncementSendService.updateReadFlagByBusId(busId,busType); //刷新未读数量 JSONObject obj = new JSONObject(); obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); webSocket.sendMessage(sysUser.getId(), obj.toJSONString()); return Result.ok(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysAnnouncementSendController.java
2
请完成以下Java代码
protected void persistDecisions(ParsedDeployment parsedDeployment) { DmnEngineConfiguration dmnEngineConfiguration = CommandContextUtil.getDmnEngineConfiguration(); DecisionEntityManager decisionEntityManager = dmnEngineConfiguration.getDecisionEntityManager(); for (DecisionEntity decision : parsedDeployment.getAllDecisions()) { decisionEntityManager.insert(decision); } } /** * Loads the persisted version of each decision and set values on the in-memory version to be consistent. */ protected void makeDecisionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) { for (DecisionEntity decision : parsedDeployment.getAllDecisions()) { DecisionEntity persistedDecision = dmnDeploymentHelper.getPersistedInstanceOfDecision(decision); if (persistedDecision != null) { decision.setId(persistedDecision.getId()); decision.setVersion(persistedDecision.getVersion()); } } } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() { return parsedDeploymentBuilderFactory; } public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) { this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory; } public DmnDeploymentHelper getDmnDeploymentHelper() { return dmnDeploymentHelper; } public void setDmnDeploymentHelper(DmnDeploymentHelper dmnDeploymentHelper) {
this.dmnDeploymentHelper = dmnDeploymentHelper; } public CachingAndArtifactsManager getCachingAndArtifcatsManager() { return cachingAndArtifactsManager; } public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) { this.cachingAndArtifactsManager = manager; } public boolean isUsePrefixId() { return usePrefixId; } public void setUsePrefixId(boolean usePrefixId) { this.usePrefixId = usePrefixId; } public DecisionRequirementsDiagramHelper getDecisionRequirementsDiagramHelper() { return decisionRequirementsDiagramHelper; } public void setDecisionRequirementsDiagramHelper(DecisionRequirementsDiagramHelper decisionRequirementsDiagramHelper) { this.decisionRequirementsDiagramHelper = decisionRequirementsDiagramHelper; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\DmnDeployer.java
1
请在Spring Boot框架中完成以下Java代码
public Set<ItemMetric> getIncomes() { return incomes; } public void setIncomes(Set<ItemMetric> incomes) { this.incomes = incomes; } public Set<ItemMetric> getExpenses() { return expenses; } public void setExpenses(Set<ItemMetric> expenses) { this.expenses = expenses; } public Map<StatisticMetric, BigDecimal> getStatistics() {
return statistics; } public void setStatistics(Map<StatisticMetric, BigDecimal> statistics) { this.statistics = statistics; } public Map<Currency, BigDecimal> getRates() { return rates; } public void setRates(Map<Currency, BigDecimal> rates) { this.rates = rates; } }
repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\domain\timeseries\DataPoint.java
2
请完成以下Java代码
public void returnOrderItems(Order order) { log.info("returnOrderItems: order={}", order); for (OrderItem item : order.items()) { inventoryService.addInventory(item.sku(), item.quantity()); } } @Override public void dispatchOrderItems(Order order) { log.info("deliverOrderItems: order={}", order); for(OrderItem item : order.items()) { inventoryService.addInventory(item.sku(), -item.quantity()); } } @Override public PaymentAuthorization createPaymentRequest(Order order, BillingInfo billingInfo) { log.info("createPaymentRequest: order={}, billingInfo={}", order, billingInfo); var request = new PaymentAuthorization( billingInfo, PaymentStatus.PENDING, order.orderId().toString(), UUID.randomUUID().toString(), null,
null); return paymentService.processPaymentRequest(request); } @Override public RefundRequest createRefundRequest(PaymentAuthorization payment) { log.info("createRefundRequest: payment={}", payment); return paymentService.createRefundRequest(payment); } @Override public Shipping createShipping(Order order) { return shippingService.createShipping(order); } @Override public Shipping updateShipping(Shipping shipping, ShippingStatus status) { return shippingService.updateStatus(shipping,status); } }
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\activities\OrderActivitiesImpl.java
1
请完成以下Java代码
public class OAuth2Error implements Serializable { private static final long serialVersionUID = 620L; private final String errorCode; private final String description; private final String uri; /** * Constructs an {@code OAuth2Error} using the provided parameters. * @param errorCode the error code */ public OAuth2Error(String errorCode) { this(errorCode, null, null); } /** * Constructs an {@code OAuth2Error} using the provided parameters. * @param errorCode the error code * @param description the error description * @param uri the error uri */ public OAuth2Error(String errorCode, String description, String uri) { Assert.hasText(errorCode, "errorCode cannot be empty"); this.errorCode = errorCode; this.description = description; this.uri = uri; } /** * Returns the error code. * @return the error code */ public final String getErrorCode() { return this.errorCode; } /** * Returns the error description.
* @return the error description */ public final String getDescription() { return this.description; } /** * Returns the error uri. * @return the error uri */ public final String getUri() { return this.uri; } @Override public String toString() { return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2Error.java
1
请完成以下Java代码
private void importDiscountSchemaBreak(@NonNull final I_I_DiscountSchema importRecord) { I_M_DiscountSchemaBreak schemaBreak = importRecord.getM_DiscountSchemaBreak(); if (schemaBreak == null) { schemaBreak = InterfaceWrapperHelper.create(getCtx(), I_M_DiscountSchemaBreak.class, ITrx.TRXNAME_ThreadInherited); schemaBreak.setM_DiscountSchema_ID(importRecord.getM_DiscountSchema_ID()); } setDiscountSchemaBreakFields(importRecord, schemaBreak); ModelValidationEngine.get().fireImportValidate(this, importRecord, schemaBreak, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(schemaBreak); importRecord.setM_DiscountSchemaBreak_ID(schemaBreak.getM_DiscountSchemaBreak_ID()); } private void setDiscountSchemaBreakFields(@NonNull final I_I_DiscountSchema importRecord, @NonNull final I_M_DiscountSchemaBreak schemaBreak) { schemaBreak.setSeqNo(10); schemaBreak.setBreakDiscount(importRecord.getBreakDiscount()); schemaBreak.setBreakValue(importRecord.getBreakValue()); // if (importRecord.getDiscount() != null && importRecord.getDiscount().signum() > 0) {
schemaBreak.setPaymentDiscount(importRecord.getDiscount()); } schemaBreak.setM_Product_ID(importRecord.getM_Product_ID()); schemaBreak.setC_PaymentTerm_ID(importRecord.getC_PaymentTerm_ID()); // setPricingFields(importRecord, schemaBreak); } private void setPricingFields(@NonNull final I_I_DiscountSchema importRecord, @NonNull final I_M_DiscountSchemaBreak schemaBreak) { schemaBreak.setPriceBase(importRecord.getPriceBase()); schemaBreak.setBase_PricingSystem_ID(importRecord.getBase_PricingSystem_ID()); schemaBreak.setPriceStdFixed(importRecord.getPriceStdFixed()); schemaBreak.setPricingSystemSurchargeAmt(importRecord.getPricingSystemSurchargeAmt()); schemaBreak.setC_Currency_ID(importRecord.getC_Currency_ID()); } @Override protected void markImported(@NonNull final I_I_DiscountSchema importRecord) { importRecord.setI_IsImported(X_I_DiscountSchema.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\impexp\DiscountSchemaImportProcess.java
1
请完成以下Java代码
public class X_WEBUI_Board_CardField extends org.compiere.model.PO implements I_WEBUI_Board_CardField, org.compiere.model.I_Persistent { private static final long serialVersionUID = -51246966L; /** Standard Constructor */ public X_WEBUI_Board_CardField (final Properties ctx, final int WEBUI_Board_CardField_ID, @Nullable final String trxName) { super (ctx, WEBUI_Board_CardField_ID, trxName); } /** Load Constructor */ public X_WEBUI_Board_CardField (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Column getAD_Column() { return get_ValueAsPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class); } @Override public void setAD_Column(final org.compiere.model.I_AD_Column AD_Column) { set_ValueFromPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class, AD_Column); } @Override public void setAD_Column_ID (final int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID); } @Override public int getAD_Column_ID() { return get_ValueAsInt(COLUMNNAME_AD_Column_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); }
@Override public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID) { if (WEBUI_Board_CardField_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID); } @Override public int getWEBUI_Board_CardField_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
1
请完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM()
{ return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java
1
请完成以下Java代码
public class SignalEventListenerInstanceImpl implements SignalEventListenerInstance { protected PlanItemInstance innerPlanItemInstance; public SignalEventListenerInstanceImpl(PlanItemInstance planItemInstance) { this.innerPlanItemInstance = planItemInstance; } public static SignalEventListenerInstance fromPlanItemInstance(PlanItemInstance planItemInstance) { if (planItemInstance == null) { return null; } return new SignalEventListenerInstanceImpl(planItemInstance); } @Override public String getId() { return innerPlanItemInstance.getId(); } @Override public String getName() { return innerPlanItemInstance.getName(); } @Override public String getCaseInstanceId() { return innerPlanItemInstance.getCaseInstanceId(); } @Override public String getCaseDefinitionId() { return innerPlanItemInstance.getCaseDefinitionId(); } @Override public String getElementId() { return innerPlanItemInstance.getElementId(); } @Override public String getPlanItemDefinitionId() { return innerPlanItemInstance.getPlanItemDefinitionId(); } @Override public String getStageInstanceId() {
return innerPlanItemInstance.getStageInstanceId(); } @Override public String getState() { return innerPlanItemInstance.getState(); } @Override public String toString() { return "SignalEventListenerInstanceImpl{" + "id='" + getId() + '\'' + ", name='" + getName() + '\'' + ", caseInstanceId='" + getCaseInstanceId() + '\'' + ", caseDefinitionId='" + getCaseDefinitionId() + '\'' + ", elementId='" + getElementId() + '\'' + ", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' + ", stageInstanceId='" + getStageInstanceId() + '\'' + '}'; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceImpl.java
1
请完成以下Java代码
public Map<String, Object> deserializeUsingOrgJson(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); Map<String, Object> result = new HashMap<>(); for (String key : jsonObject.keySet()) { Object value = jsonObject.get(key); if (value instanceof JSONArray) { value = ((JSONArray) value).toList(); } else if (value instanceof JSONObject) { value = ((JSONObject) value).toMap(); } result.put(key, value); } return result; } catch (Exception e) { throw new RuntimeException("org.json deserialization failed: " + e.getMessage(), e); } } public Map<String, Object> deserializeUsingJsonP(String jsonString) { try (JsonReader reader = Json.createReader(new StringReader(jsonString))) { JsonObject jsonObject = reader.readObject(); return convertJsonToMap(jsonObject); } catch (Exception e) { throw new RuntimeException("JSON-P deserialization failed: " + e.getMessage(), e); } } private Map<String, Object> convertJsonToMap(JsonObject jsonObject) { Map<String, Object> result = new HashMap<>(); for (Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonValue value = entry.getValue(); result.put(key, convertJsonValue(value)); }
return result; } private Object convertJsonValue(JsonValue jsonValue) { switch (jsonValue.getValueType()) { case STRING: return ((JsonString) jsonValue).getString(); case NUMBER: JsonNumber num = (JsonNumber) jsonValue; return num.isIntegral() ? num.longValue() : num.doubleValue(); case TRUE: return true; case FALSE: return false; case NULL: return null; case ARRAY: return convertJsonArray(( jakarta.json.JsonArray) jsonValue); case OBJECT: return convertJsonToMap((JsonObject) jsonValue); default: return jsonValue.toString(); } } private List<Object> convertJsonArray( jakarta.json.JsonArray jsonArray) { List<Object> list = new ArrayList<>(); for (JsonValue value : jsonArray) { list.add(convertJsonValue(value)); } return list; } }
repos\tutorials-master\json-modules\json-3\src\main\java\com\baeldung\jsondeserialization\JsonDeserializerService.java
1
请在Spring Boot框架中完成以下Java代码
public List<User> findUserBatch(List<Long> ids) { log.info("批量获取用户信息,ids: " + ids); User[] users = restTemplate.getForObject("http://Server-Provider/user/users?ids={1}", User[].class, StringUtils.join(ids, ",")); return Arrays.asList(users); } public String getCacheKey(Long id) { return String.valueOf(id); } @CacheResult(cacheKeyMethod = "getCacheKey") @HystrixCommand(fallbackMethod = "getUserDefault", commandKey = "getUserById", groupKey = "userGroup", threadPoolKey = "getUserThread") public User getUser(Long id) { log.info("获取用户信息"); return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id); } @HystrixCommand(fallbackMethod = "getUserDefault2") public User getUserDefault(Long id) { String a = null; // 测试服务降级 a.toString(); User user = new User(); user.setId(-1L); user.setUsername("defaultUser"); user.setPassword("123456"); return user; } public User getUserDefault2(Long id, Throwable e) { System.out.println(e.getMessage()); User user = new User(); user.setId(-2L); user.setUsername("defaultUser2");
user.setPassword("123456"); return user; } public List<User> getUsers() { return this.restTemplate.getForObject("http://Server-Provider/user", List.class); } public String addUser() { User user = new User(1L, "mrbird", "123456"); HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); if (status.is2xxSuccessful()) { return "新增用户成功"; } else { return "新增用户失败"; } } @CacheRemove(commandKey = "getUserById") @HystrixCommand public void updateUser(@CacheKey("id") User user) { this.restTemplate.put("http://Server-Provider/user", user); } public void deleteUser(@PathVariable Long id) { this.restTemplate.delete("http://Server-Provider/user/{1}", id); } }
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
protected void validateDataImpl(TenantId requestTenantId, User user) { if (StringUtils.isEmpty(user.getEmail())) { throw new DataValidationException("User email should be specified!"); } validateEmail(user.getEmail()); Authority authority = user.getAuthority(); if (authority == null) { throw new DataValidationException("User authority isn't defined!"); } TenantId tenantId = user.getTenantId(); if (tenantId == null) { tenantId = TenantId.fromUUID(ModelConstants.NULL_UUID); user.setTenantId(tenantId); } CustomerId customerId = user.getCustomerId(); if (customerId == null) { customerId = new CustomerId(ModelConstants.NULL_UUID); user.setCustomerId(customerId); } switch (authority) { case SYS_ADMIN: if (!tenantId.getId().equals(ModelConstants.NULL_UUID) || !customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("System administrator can't be assigned neither to tenant nor to customer!"); } break; case TENANT_ADMIN: if (tenantId.getId().equals(ModelConstants.NULL_UUID)) {
throw new DataValidationException("Tenant administrator should be assigned to tenant!"); } else if (!customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Tenant administrator can't be assigned to customer!"); } break; case CUSTOMER_USER: if (tenantId.getId().equals(ModelConstants.NULL_UUID) || customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Customer user should be assigned to customer!"); } break; default: break; } if (!tenantId.getId().equals(ModelConstants.NULL_UUID)) { if (!tenantService.tenantExists(user.getTenantId())) { throw new DataValidationException("User is referencing to non-existent tenant!"); } } if (!customerId.getId().equals(ModelConstants.NULL_UUID)) { Customer customer = customerDao.findById(tenantId, user.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("User is referencing to non-existent customer!"); } else if (!customer.getTenantId().getId().equals(tenantId.getId())) { throw new DataValidationException("User can't be assigned to customer from different tenant!"); } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\UserDataValidator.java
2
请完成以下Java代码
private void init() { scheduler.scheduleAtFixedRate(this::reportMetrics, metricsReportIntervalSec, metricsReportIntervalSec, TimeUnit.SECONDS); } public void process(TransportProtos.SessionInfoProto sessionInfo, DeviceId gatewayId, List<GatewayMetadata> data, long serverReceiveTs) { states.computeIfAbsent(gatewayId, k -> new GatewayMetricsState(sessionInfo)).update(data, serverReceiveTs); } public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceId gatewayId) { var state = states.get(gatewayId); if (state != null) { state.updateSessionInfo(sessionInfo); } } public void onDeviceDelete(DeviceId deviceId) { states.remove(deviceId); } public void reportMetrics() { if (states.isEmpty()) { return; } Map<DeviceId, GatewayMetricsState> statesToReport = states; states = new ConcurrentHashMap<>(); long ts = System.currentTimeMillis(); statesToReport.forEach((gatewayId, state) -> { reportMetrics(state, ts); }); } private void reportMetrics(GatewayMetricsState state, long ts) {
if (state.isEmpty()) { return; } var result = state.getStateResult(); var kvProto = TransportProtos.KeyValueProto.newBuilder() .setKey(GATEWAY_METRICS) .setType(TransportProtos.KeyValueType.JSON_V) .setJsonV(JacksonUtil.toString(result)) .build(); TransportProtos.TsKvListProto tsKvList = TransportProtos.TsKvListProto.newBuilder() .setTs(ts) .addKv(kvProto) .build(); TransportProtos.PostTelemetryMsg telemetryMsg = TransportProtos.PostTelemetryMsg.newBuilder() .addTsKvList(tsKvList) .build(); transportService.process(state.getSessionInfo(), telemetryMsg, TransportServiceCallback.EMPTY); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\gateway\GatewayMetricsService.java
1
请在Spring Boot框架中完成以下Java代码
private SessionUserInfo getUserInfoFromCache(String token) { if (StringTools.isNullOrEmpty(token)) { throw new CommonJsonException(ErrorEnum.E_20011); } log.debug("根据token从缓存中查询用户信息,{}", token); SessionUserInfo info = cacheMap.getIfPresent(token); if (info == null) { log.info("没拿到缓存 token={}", token); throw new CommonJsonException(ErrorEnum.E_20011); } return info; } private void setCache(String token, String username) { SessionUserInfo info = getUserInfoByUsername(username); log.info("设置用户信息缓存:token={} , username={}, info={}", token, username, info); cacheMap.put(token, info); } /** * 退出登录时,将token置为无效 */ public void invalidateToken() { String token = MDC.get("token");
if (!StringTools.isNullOrEmpty(token)) { cacheMap.invalidate(token); } log.debug("退出登录,清除缓存:token={}", token); } private SessionUserInfo getUserInfoByUsername(String username) { SessionUserInfo userInfo = loginDao.getUserInfo(username); if (userInfo.getRoleIds().contains(1)) { //管理员,查出全部按钮和权限码 userInfo.setMenuList(loginDao.getAllMenu()); userInfo.setPermissionList(loginDao.getAllPermissionCode()); } return userInfo; } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\TokenService.java
2
请完成以下Java代码
private ProductId getProductId() { return externalIdentifierResolver.resolveProductExternalIdentifier(productIdentifier, orgId) .orElseThrow(() -> new InvalidIdentifierException("Fail to resolve product external identifier") .appendParametersToMessage() .setParameter("ExternalIdentifier", productIdentifier)); } @NonNull private ZonedDateTime getTargetDateAndTime() { final ZonedDateTime zonedDateTime = TimeUtil.asZonedDateTime(targetDate, orgDAO.getTimeZone(orgId)); Check.assumeNotNull(zonedDateTime, "zonedDateTime is not null!"); return zonedDateTime; } @NonNull private List<JsonResponsePrice> getJsonResponsePrices( @NonNull final ProductId productId, @NonNull final String productValue, @NonNull final PriceListVersionId priceListVersionId) {
return bpartnerPriceListServicesFacade.getProductPricesByPLVAndProduct(priceListVersionId, productId) .stream() .map(productPrice -> JsonResponsePrice.builder() .productId(JsonMetasfreshId.of(productId.getRepoId())) .productCode(productValue) .taxCategoryId(JsonMetasfreshId.of(productPrice.getC_TaxCategory_ID())) .price(productPrice.getPriceStd()) .build()) .collect(ImmutableList.toImmutableList()); } @NonNull private String getCurrencyCode(@NonNull final I_M_PriceList priceList) { return bpartnerPriceListServicesFacade .getCurrencyCodeById(CurrencyId.ofRepoId(priceList.getC_Currency_ID())) .toThreeLetterCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\command\SearchProductPricesCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserRepository userRepository; @RequestMapping(value = "/setSession") public Map<String, Object> setSession (HttpServletRequest request){ Map<String, Object> map = new HashMap<>(); request.getSession().setAttribute("message", request.getRequestURL()); map.put("request Url", request.getRequestURL()); return map; } @RequestMapping(value = "/getSession") public Object getSession (HttpServletRequest request){ Map<String, Object> map = new HashMap<>(); map.put("sessionId", request.getSession().getId()); map.put("message", request.getSession().getAttribute("message")); return map; } @RequestMapping(value = "/index") public String index (HttpServletRequest request){
String msg="index content"; Object user= request.getSession().getAttribute("user"); if (user==null){ msg="please login first!"; } return msg; } @RequestMapping(value = "/login") public String login (HttpServletRequest request,String userName,String password){ String msg="logon failure!"; User user= userRepository.findByUserName(userName); if (user!=null && user.getPassword().equals(password)){ request.getSession().setAttribute("user",user); msg="login successful!"; } return msg; } }
repos\spring-boot-leaning-master\1.x\第10课:Redis实现数据缓存和Session共享\spring-boot-redis-session\src\main\java\com\neo\web\UserController.java
2
请完成以下Java代码
public class MDunning extends X_C_Dunning { /** * */ private static final long serialVersionUID = -3844081441218291895L; /** * Standard Constructor * @param ctx context * @param C_Dunning_ID id * @param trxName transaction */ public MDunning (Properties ctx, int C_Dunning_ID, String trxName) { super (ctx, C_Dunning_ID, trxName); } // MDunning /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MDunning (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MDunning
/** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("MDunning[").append(get_ID()) .append("-").append(getName()); sb.append("]"); return sb.toString(); } // toString } // MDunning
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDunning.java
1
请完成以下Java代码
public boolean isLeaf() { return isLeaf; } public void setLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getCode() { return code; }
public void setCode(String code) { this.code = code; } private List<TreeSelectModel> children; public List<TreeSelectModel> getChildren() { return children; } public void setChildren(List<TreeSelectModel> children) { this.children = children; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeSelectModel.java
1
请完成以下Java代码
Authentication getAuthentication(String token) { Claims claims = getClaims(token); User principal = new User(claims.getSubject(), "******", new ArrayList<>()); return new UsernamePasswordAuthenticationToken(principal, token, new ArrayList<>()); } public Claims getClaims(String token) { return jwtParser .parseClaimsJws(token) .getBody(); } /** * @param token 需要检查的token */ public void checkRenewal(String token) { // 判断是否续期token,计算token的过期时间 String loginKey = loginKey(token); long time = redisUtils.getExpire(loginKey) * 1000; Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time); // 判断当前时间与过期时间的时间差 long differ = expireDate.getTime() - System.currentTimeMillis(); // 如果在续期检查的范围内,则续期 if (differ <= properties.getDetect()) { long renew = time + properties.getRenew(); redisUtils.expire(loginKey, renew, TimeUnit.MILLISECONDS); } } public String getToken(HttpServletRequest request) {
final String requestHeader = request.getHeader(properties.getHeader()); if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) { return requestHeader.substring(7); } return null; } /** * 获取登录用户RedisKey * @param token / * @return key */ public String loginKey(String token) { Claims claims = getClaims(token); return properties.getOnlineKey() + claims.getSubject() + ":" + getId(token); } /** * 获取登录用户TokenKey * @param token / * @return / */ public String getId(String token) { Claims claims = getClaims(token); return claims.get(AUTHORITIES_UUID_KEY).toString(); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\security\TokenProvider.java
1
请完成以下Java代码
public Map<String, SequenceFlow> getSequenceFlows() { return sequenceFlows; } public ProcessDefinitionEntity getCurrentProcessDefinition() { return currentProcessDefinition; } public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public Process getCurrentProcess() {
return currentProcess; } public void setCurrentProcess(Process currentProcess) { this.currentProcess = currentProcess; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek(); } public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
public boolean isForbidAggCUsForDifferentOrders() { return get_ValueAsBoolean(COLUMNNAME_IsForbidAggCUsForDifferentOrders); } @Override public void setM_Picking_Config_ID (final int M_Picking_Config_ID) { if (M_Picking_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID); } @Override public int getM_Picking_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID); } /** * WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772 * Reference name: WEBUI_PickingTerminal_ViewProfile
*/ public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772; /** groupByProduct = groupByProduct */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct"; /** Group by Order = groupByOrder */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder"; @Override public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile) { set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile); } @Override public java.lang.String getWEBUI_PickingTerminal_ViewProfile() { return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java
1
请完成以下Java代码
public void setMaxClick (int MaxClick) { set_Value (COLUMNNAME_MaxClick, Integer.valueOf(MaxClick)); } /** Get Max Click Count. @return Maximum Click Count until banner is deactivated */ public int getMaxClick () { Integer ii = (Integer)get_Value(COLUMNNAME_MaxClick); if (ii == null) return 0; return ii.intValue(); } /** Set Max Impression Count. @param MaxImpression Maximum Impression Count until banner is deactivated */ public void setMaxImpression (int MaxImpression) { set_Value (COLUMNNAME_MaxImpression, Integer.valueOf(MaxImpression)); } /** Get Max Impression Count. @return Maximum Impression Count until banner is deactivated */ public int getMaxImpression () { Integer ii = (Integer)get_Value(COLUMNNAME_MaxImpression); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Set Start Count Impression. @param StartImpression For rotation we need a start count */ public void setStartImpression (int StartImpression)
{ set_Value (COLUMNNAME_StartImpression, Integer.valueOf(StartImpression)); } /** Get Start Count Impression. @return For rotation we need a start count */ public int getStartImpression () { Integer ii = (Integer)get_Value(COLUMNNAME_StartImpression); if (ii == null) return 0; return ii.intValue(); } /** Set Target Frame. @param Target_Frame Which target should be used if user clicks? */ public void setTarget_Frame (String Target_Frame) { set_Value (COLUMNNAME_Target_Frame, Target_Frame); } /** Get Target Frame. @return Which target should be used if user clicks? */ public String getTarget_Frame () { return (String)get_Value(COLUMNNAME_Target_Frame); } /** Set Target URL. @param TargetURL URL for the Target */ public void setTargetURL (String TargetURL) { set_Value (COLUMNNAME_TargetURL, TargetURL); } /** Get Target URL. @return URL for the Target */ public String getTargetURL () { return (String)get_Value(COLUMNNAME_TargetURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad.java
1