instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions().sameOrigin() .and() .authorizeRequests() .antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .failureUrl("/login?error") .permitAll()
.and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("my-remember-me-cookie") .permitAll() .and() .rememberMe() //.key("my-secure-key") .rememberMeCookieName("my-remember-me-cookie") .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(24 * 60 * 60) .and() .exceptionHandling() ; } PersistentTokenRepository persistentTokenRepository(){ JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-thymeleaf-security-demo\src\main\java\net\alanbinu\springbootsecurity\config\WebSecurityConfig.java
2
请完成以下Java代码
public void setP_Number (final @Nullable BigDecimal P_Number) { set_ValueNoCheck (COLUMNNAME_P_Number, P_Number); } @Override public BigDecimal getP_Number() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_P_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); }
@Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setWarnings (final @Nullable java.lang.String Warnings) { set_Value (COLUMNNAME_Warnings, Warnings); } @Override public java.lang.String getWarnings() { return get_ValueAsString(COLUMNNAME_Warnings); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Log.java
1
请完成以下Java代码
public int getDataEntry_Field_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Field_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Eingabefeldwert. @param DataEntry_ListValue_ID Eingabefeldwert */ @Override public void setDataEntry_ListValue_ID (int DataEntry_ListValue_ID) { if (DataEntry_ListValue_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, Integer.valueOf(DataEntry_ListValue_ID)); } /** Get Eingabefeldwert. @return Eingabefeldwert */ @Override public int getDataEntry_ListValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_ListValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_ListValue.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(RepetitionRule.class, CMMN_ELEMENT_REPETITION_RULE) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<RepetitionRule>() { public RepetitionRule newInstance(ModelTypeInstanceContext instanceContext) { return new RepetitionRuleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF) .idAttributeReference(CaseFileItem.class) .build();
/** Camunda extensions */ camundaRepeatOnStandardEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_REPEAT_ON_STANDARD_EVENT) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RepetitionRuleImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected FailureAnalysis analyze(Throwable rootFailure, DataSourceBeanCreationException cause) { return getFailureAnalysis(cause); } private FailureAnalysis getFailureAnalysis(DataSourceBeanCreationException cause) { String description = getDescription(cause); String action = getAction(cause); return new FailureAnalysis(description, action, cause); } private String getDescription(DataSourceBeanCreationException cause) { StringBuilder description = new StringBuilder(); description.append("Failed to configure a DataSource: "); if (!StringUtils.hasText(cause.getProperties().getUrl())) { description.append("'url' attribute is not specified and "); } description.append(String.format("no embedded datasource could be configured.%n")); description.append(String.format("%nReason: %s%n", cause.getMessage())); return description.toString(); } private String getAction(DataSourceBeanCreationException cause) { StringBuilder action = new StringBuilder(); action.append(String.format("Consider the following:%n")); if (EmbeddedDatabaseConnection.NONE == cause.getConnection()) { action.append(String .format("\tIf you want an embedded database (H2, HSQL or Derby), please put it on the classpath.%n")); } else {
action.append(String.format("\tReview the configuration of %s%n.", cause.getConnection())); } action .append("\tIf you have database settings to be loaded from a particular " + "profile you may need to activate it") .append(getActiveProfiles()); return action.toString(); } private String getActiveProfiles() { StringBuilder message = new StringBuilder(); String[] profiles = this.environment.getActiveProfiles(); if (ObjectUtils.isEmpty(profiles)) { message.append(" (no profiles are currently active)."); } else { message.append(" (the profiles "); message.append(StringUtils.arrayToCommaDelimitedString(profiles)); message.append(" are currently active)."); } return message.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceBeanCreationFailureAnalyzer.java
2
请完成以下Java代码
public void start() throws InterruptedException { // 创建 Bootstrap 对象,用于 Netty Client 启动 Bootstrap bootstrap = new Bootstrap(); // 设置 Bootstrap 的各种属性。 bootstrap.group(eventGroup) // 设置一个 EventLoopGroup 对象 .channel(NioSocketChannel.class) // 指定 Channel 为客户端 NioSocketChannel .remoteAddress(serverHost, serverPort) // 指定链接服务器的地址 .option(ChannelOption.SO_KEEPALIVE, true) // TCP Keepalive 机制,实现 TCP 层级的心跳保活功能 .option(ChannelOption.TCP_NODELAY, true) // 允许较小的数据包的发送,降低延迟 .handler(nettyClientHandlerInitializer); // 链接服务器,并异步等待成功,即启动客户端 bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // 连接失败 if (!future.isSuccess()) { logger.error("[start][Netty Client 连接服务器({}:{}) 失败]", serverHost, serverPort); reconnect(); return; } // 连接成功 channel = future.channel(); logger.info("[start][Netty Client 连接服务器({}:{}) 成功]", serverHost, serverPort); } }); } public void reconnect() { eventGroup.schedule(new Runnable() { @Override public void run() { logger.info("[reconnect][开始重连]"); try { start(); } catch (InterruptedException e) { logger.error("[reconnect][重连失败]", e); } } }, RECONNECT_SECONDS, TimeUnit.SECONDS); logger.info("[reconnect][{} 秒后将发起重连]", RECONNECT_SECONDS); }
/** * 关闭 Netty Server */ @PreDestroy public void shutdown() { // 关闭 Netty Client if (channel != null) { channel.close(); } // 优雅关闭一个 EventLoopGroup 对象 eventGroup.shutdownGracefully(); } /** * 发送消息 * * @param invocation 消息体 */ public void send(Invocation invocation) { if (channel == null) { logger.error("[send][连接不存在]"); return; } if (!channel.isActive()) { logger.error("[send][连接({})未激活]", channel.id()); return; } // 发送消息 channel.writeAndFlush(invocation); } }
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-client\src\main\java\cn\iocoder\springboot\lab67\nettyclientdemo\client\NettyClient.java
1
请完成以下Java代码
public Quantity computeAssignableQuantity(@NonNull final RefundConfig refundCondig) { final Optional<RefundConfig> nextRefundConfig = getRefundContract() .getRefundConfigs() .stream() .filter(config -> config.getMinQty().compareTo(refundCondig.getMinQty()) > 0) .min(Comparator.comparing(RefundConfig::getMinQty)); final I_C_UOM uomRecord = assignedQuantity.getUOM(); if (!nextRefundConfig.isPresent()) { return Quantity.infinite(uomRecord); } return Quantity .of( nextRefundConfig.get().getMinQty(), uomRecord) .subtract(getAssignedQuantity()) .subtract(ONE) .max(Quantity.zero(uomRecord)); }
public RefundInvoiceCandidate subtractAssignment(@NonNull final AssignmentToRefundCandidate assignmentToRefundCandidate) { Check.assume(assignmentToRefundCandidate.getRefundInvoiceCandidate().getId().equals(getId()), "The given assignmentToRefundCandidate needs to be an assignment to this refund candidate; this={}, assignmentToRefundCandidate={}", this, assignmentToRefundCandidate); final RefundInvoiceCandidateBuilder builder = toBuilder(); final Money moneySubtrahent = assignmentToRefundCandidate.getMoneyAssignedToRefundCandidate(); final Money newMoneyAmount = getMoney().subtract(moneySubtrahent); builder.money(newMoneyAmount); if (assignmentToRefundCandidate.isUseAssignedQtyInSum()) { final Quantity assignedQuantitySubtrahent = assignmentToRefundCandidate.getQuantityAssigendToRefundCandidate(); final Quantity newQuantity = getAssignedQuantity().subtract(assignedQuantitySubtrahent); builder.assignedQuantity(newQuantity); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundInvoiceCandidate.java
1
请完成以下Java代码
public class MigratingTransitionInstanceValidationReportDto { protected MigrationInstructionDto migrationInstruction; protected String transitionInstanceId; protected String sourceScopeId; protected List<String> failures; public MigrationInstructionDto getMigrationInstruction() { return migrationInstruction; } public void setMigrationInstruction(MigrationInstructionDto migrationInstruction) { this.migrationInstruction = migrationInstruction; } public String getTransitionInstanceId() { return transitionInstanceId; } public void setTransitionInstanceId(String transitionInstanceId) { this.transitionInstanceId = transitionInstanceId; } public List<String> getFailures() { return failures; } public void setFailures(List<String> failures) { this.failures = failures; } public String getSourceScopeId() { return sourceScopeId; } public void setSourceScopeId(String sourceScopeId) { this.sourceScopeId = sourceScopeId; }
public static List<MigratingTransitionInstanceValidationReportDto> from(List<MigratingTransitionInstanceValidationReport> reports) { ArrayList<MigratingTransitionInstanceValidationReportDto> dtos = new ArrayList<MigratingTransitionInstanceValidationReportDto>(); for (MigratingTransitionInstanceValidationReport report : reports) { dtos.add(MigratingTransitionInstanceValidationReportDto.from(report)); } return dtos; } public static MigratingTransitionInstanceValidationReportDto from(MigratingTransitionInstanceValidationReport report) { MigratingTransitionInstanceValidationReportDto dto = new MigratingTransitionInstanceValidationReportDto(); dto.setMigrationInstruction(MigrationInstructionDto.from(report.getMigrationInstruction())); dto.setTransitionInstanceId(report.getTransitionInstanceId()); dto.setFailures(report.getFailures()); dto.setSourceScopeId(report.getSourceScopeId()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigratingTransitionInstanceValidationReportDto.java
1
请在Spring Boot框架中完成以下Java代码
public void setNumThreads(Integer numThreads) { this.numThreads = numThreads; } public Integer getBatchSize() { return this.batchSize; } public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } public Duration getMeterTimeToLive() { return this.meterTimeToLive; } public void setMeterTimeToLive(Duration meterTimeToLive) { this.meterTimeToLive = meterTimeToLive; } public boolean isLwcEnabled() { return this.lwcEnabled; } public void setLwcEnabled(boolean lwcEnabled) { this.lwcEnabled = lwcEnabled; } public Duration getLwcStep() { return this.lwcStep; } public void setLwcStep(Duration lwcStep) { this.lwcStep = lwcStep; } public boolean isLwcIgnorePublishStep() { return this.lwcIgnorePublishStep; } public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) { this.lwcIgnorePublishStep = lwcIgnorePublishStep; } public Duration getConfigRefreshFrequency() { return this.configRefreshFrequency; } public void setConfigRefreshFrequency(Duration configRefreshFrequency) { this.configRefreshFrequency = configRefreshFrequency; }
public Duration getConfigTimeToLive() { return this.configTimeToLive; } public void setConfigTimeToLive(Duration configTimeToLive) { this.configTimeToLive = configTimeToLive; } public String getConfigUri() { return this.configUri; } public void setConfigUri(String configUri) { this.configUri = configUri; } public String getEvalUri() { return this.evalUri; } public void setEvalUri(String evalUri) { this.evalUri = evalUri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
2
请完成以下Spring Boot application配置
server: port: 8088 spring: freemarker: cache: false charset: UTF-8 check-template-location: true content-type: text/html expose-request-attributes: true expose-session-attributes: true req
uest-context-attribute: request template-loader-path: classpath:/templates/ suffix: .ftl
repos\springboot-demo-master\Puppeteer\src\main\resources\application.yaml
2
请完成以下Java代码
public java.lang.String getLot () { return (java.lang.String)get_Value(COLUMNNAME_Lot); } @Override public org.compiere.model.I_M_AttributeSet getM_AttributeSet() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class); } @Override public void setM_AttributeSet(org.compiere.model.I_M_AttributeSet M_AttributeSet) { set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet); } /** Set Merkmals-Satz. @param M_AttributeSet_ID Product Attribute Set */ @Override public void setM_AttributeSet_ID (int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_Value (COLUMNNAME_M_AttributeSet_ID, null); else set_Value (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID)); } /** Get Merkmals-Satz. @return Product Attribute Set */ @Override public int getM_AttributeSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ausprägung Merkmals-Satz. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ @Override public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Ausprägung Merkmals-Satz. @return Product Attribute Set Instance */ @Override public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } @Override
public org.compiere.model.I_M_Lot getM_Lot() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class); } @Override public void setM_Lot(org.compiere.model.I_M_Lot M_Lot) { set_ValueFromPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class, M_Lot); } /** Set Los. @param M_Lot_ID Product Lot Definition */ @Override public void setM_Lot_ID (int M_Lot_ID) { if (M_Lot_ID < 1) set_Value (COLUMNNAME_M_Lot_ID, null); else set_Value (COLUMNNAME_M_Lot_ID, Integer.valueOf(M_Lot_ID)); } /** Get Los. @return Product Lot Definition */ @Override public int getM_Lot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Lot_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Serien-Nr.. @param SerNo Product Serial Number */ @Override public void setSerNo (java.lang.String SerNo) { set_Value (COLUMNNAME_SerNo, SerNo); } /** Get Serien-Nr.. @return Product Serial Number */ @Override public java.lang.String getSerNo () { return (java.lang.String)get_Value(COLUMNNAME_SerNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetInstance.java
1
请完成以下Java代码
public class VariableConflictActivityInstanceValidator implements MigratingActivityInstanceValidator { @Override public void validate(MigratingActivityInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingActivityInstanceValidationReportImpl instanceReport) { ScopeImpl sourceScope = migratingInstance.getSourceScope(); ScopeImpl targetScope = migratingInstance.getTargetScope(); if (migratingInstance.migrates()) { boolean becomesNonScope = sourceScope.isScope() && !targetScope.isScope(); if (becomesNonScope) { Map<String, List<MigratingVariableInstance>> dependentVariablesByName = getMigratingVariableInstancesByName(migratingInstance); for (String variableName : dependentVariablesByName.keySet()) { if (dependentVariablesByName.get(variableName).size() > 1) { instanceReport.addFailure("The variable '" + variableName + "' exists in both, this scope and " + "concurrent local in the parent scope. " + "Migrating to a non-scope activity would overwrite one of them."); } }
} } } protected Map<String, List<MigratingVariableInstance>> getMigratingVariableInstancesByName(MigratingActivityInstance activityInstance) { Map<String, List<MigratingVariableInstance>> result = new HashMap<String, List<MigratingVariableInstance>>(); for (MigratingInstance migratingInstance : activityInstance.getMigratingDependentInstances()) { if (migratingInstance instanceof MigratingVariableInstance) { MigratingVariableInstance migratingVariableInstance = (MigratingVariableInstance) migratingInstance; CollectionUtil.addToMapOfLists(result, migratingVariableInstance.getVariableName(), migratingVariableInstance); } } return result; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\VariableConflictActivityInstanceValidator.java
1
请完成以下Java代码
public String getServiceId() { if (properties.isLowerCaseServiceId()) { return delegate.getServiceId().toLowerCase(Locale.ROOT); } return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost(); } @Override public int getPort() { return delegate.getPort(); } @Override public boolean isSecure() { return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri(); } @Override
public @Nullable Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public @Nullable String getScheme() { return delegate.getScheme(); } @Override public String toString() { return new ToStringCreator(this).append("delegate", delegate).append("properties", properties).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryClientRouteDefinitionLocator.java
1
请完成以下Java代码
private static List<Word> seg(String sentence) { //分词 LOG.info("正在对短句进行分词:" + sentence); List<Word> wordList = new LinkedList<>(); List<Term> terms = HanLP.segment(sentence); StringBuffer sbLogInfo = new StringBuffer(); for (Term term : terms) { Word word = new Word(term.word); wordList.add(word); sbLogInfo.append(word); sbLogInfo.append(' '); } LOG.info("分词结果为:" + sbLogInfo); return wordList; } public static MainPart getMainPart(String sentence, String delimiter) { List<Word> wordList = new LinkedList<>(); for (String word : sentence.split(delimiter)) { wordList.add(new Word(word)); } return getMainPart(wordList); } /** * 调用演示 * @param args */ public static void main(String[] args) { /* String[] testCaseArray = { "我一直很喜欢你", "你被我喜欢", "美丽又善良的你被卑微的我深深的喜欢着……", "只有自信的程序员才能把握未来", "主干识别可以提高检索系统的智能", "这个项目的作者是hankcs", "hankcs是一个无门无派的浪人", "搜索hankcs可以找到我的博客", "静安区体育局2013年部门决算情况说明",
"这类算法在有限的一段时间内终止", }; for (String testCase : testCaseArray) { MainPart mp = MainPartExtractor.getMainPart(testCase); System.out.printf("%s\t%s\n", testCase, mp); }*/ mpTest(); } public static void mpTest(){ String[] testCaseArray = { "我一直很喜欢你", "你被我喜欢", "美丽又善良的你被卑微的我深深的喜欢着……", "小米公司主要生产智能手机", "他送给了我一份礼物", "这类算法在有限的一段时间内终止", "如果大海能够带走我的哀愁", "天青色等烟雨,而我在等你", "我昨天看见了一个非常可爱的小孩" }; for (String testCase : testCaseArray) { MainPart mp = MainPartExtractor.getMainPart(testCase); System.out.printf("%s %s %s \n", GraphUtil.getNodeValue(mp.getSubject()), GraphUtil.getNodeValue(mp.getPredicate()), GraphUtil.getNodeValue(mp.getObject())); } } }
repos\springboot-demo-master\neo4j\src\main\java\com\et\neo4j\hanlp\MainPartExtractor.java
1
请完成以下Java代码
public void setDescription (final @Nullable String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @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); } @Override public void setSEPA_Export_ID (final int SEPA_Export_ID) { if (SEPA_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, SEPA_Export_ID); } @Override public int getSEPA_Export_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_ID); } @Override public void setSEPA_Export_Line_ID (final int SEPA_Export_Line_ID) { if (SEPA_Export_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, SEPA_Export_Line_ID); } @Override public int getSEPA_Export_Line_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_ID); }
@Override public void setSEPA_Export_Line_Ref_ID (final int SEPA_Export_Line_Ref_ID) { if (SEPA_Export_Line_Ref_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, SEPA_Export_Line_Ref_ID); } @Override public int getSEPA_Export_Line_Ref_ID() { return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_Ref_ID); } @Override public void setStructuredRemittanceInfo (final @Nullable String StructuredRemittanceInfo) { set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo); } @Override public String getStructuredRemittanceInfo() { return get_ValueAsString(COLUMNNAME_StructuredRemittanceInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line_Ref.java
1
请完成以下Java代码
protected void createHUDocumentsFromTypedModel(final HUDocumentsCollector documentsCollector, final I_DD_Order ddOrder) { final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final IHUDocumentFactory huFactory = getHandlingUnitsHUDocumentFactory(); final Set<Integer> seenHuIds = new HashSet<>(); final DDOrderLowLevelDAO ddOrderLowLevelDAO = SpringContextHolder.instance.getBean(DDOrderLowLevelDAO.class); for (final I_DD_OrderLine line : ddOrderLowLevelDAO.retrieveLines(ddOrder)) { // // Create HUDocuments final LocatorId locatorId = warehouseDAO.getLocatorIdByRepoId(line.getM_Locator_ID()); final Iterator<I_M_HU> hus = handlingUnitsDAO.retrieveTopLevelHUsForLocator(locatorId); while (hus.hasNext()) { final I_M_HU hu = hus.next(); final int huId = hu.getM_HU_ID(); if (!seenHuIds.add(huId)) { // already added continue; } final List<IHUDocument> lineDocuments = huFactory.createHUDocumentsFromModel(hu);
documentsCollector.getHUDocuments().addAll(lineDocuments); } // // Create target Capacities final Quantity qtyToDeliver = Quantitys.of( line.getQtyOrdered().subtract(line.getQtyDelivered()), UomId.ofRepoId(line.getC_UOM_ID())); final Capacity targetCapacity = Capacity.createCapacity( qtyToDeliver.toBigDecimal(), // qty ProductId.ofRepoId(line.getM_Product_ID()), qtyToDeliver.getUOM(), false// allowNegativeCapacity ); documentsCollector.getTargetCapacities().add(targetCapacity); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\hu_spis\DDOrderHUDocumentFactory.java
1
请完成以下Java代码
public Message getReturnedMessage() { return this.returned.getMessage(); } public int getReplyCode() { return this.returned.getReplyCode(); } public String getReplyText() { return this.returned.getReplyText(); } public String getExchange() { return this.returned.getExchange(); }
public String getRoutingKey() { return this.returned.getRoutingKey(); } public ReturnedMessage getReturned() { return this.returned; } @Override public String toString() { return "AmqpMessageReturnedException: " + getMessage() + ", " + this.returned.toString(); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\AmqpMessageReturnedException.java
1
请完成以下Java代码
public void run(ApplicationArguments args) throws Exception { DataSource dataSourceMysql = applicationContext.getBean(DataSource.class); //模板引擎配置 生成文件配置 EngineConfig engineConfig = EngineConfig.builder() // 生成文件路径 .fileOutputDir("D://tmp/") // 打开目录 .openOutputDir(false) // 文件类型 .fileType(EngineFileType.WORD) // 生成模板实现 .produceType(EngineTemplateType.freemarker).build(); // 生成文档配置(包含以下自定义版本号、描述等配置连接),文档名称拼接:数据库名_描述_版本.扩展名 Configuration config = Configuration.builder() .title("数据库文档") // 版本号 .version("1.0.0") // 描述 .description("数据库设计文档") // 数据源 .dataSource(dataSourceMysql) // 模板引擎配置 .engineConfig(engineConfig) // 加载配置:想要生成的表、想要忽略的表 .produceConfig(getProcessConfig()) .build(); // 执行生成 new DocumentationExecute(config).execute(); } /** * 配置想要生成的表+ 配置想要忽略的表 *
* @return 生成表配置 */ public static ProcessConfig getProcessConfig() { // 忽略表名 List<String> ignoreTableName = Arrays.asList(""); return ProcessConfig.builder() //根据名称指定表生成 .designatedTableName(new ArrayList<>()) //根据表前缀生成 .designatedTablePrefix(new ArrayList<>()) //根据表后缀生成 .designatedTableSuffix(new ArrayList<>()) //忽略表名 .ignoreTableName(ignoreTableName) .build(); } }
repos\springboot-demo-master\Screw\src\main\java\com\et\screw\Application.java
1
请完成以下Java代码
public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) { this.sessionInfo = sessionInfo; this.deviceProfile = deviceProfile; this.deviceInfo.setDeviceType(deviceProfile.getName()); } @Override public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) { this.sessionInfo = sessionInfo; this.deviceInfo.setDeviceProfileId(device.getDeviceProfileId()); this.deviceInfo.setDeviceType(device.getType()); deviceProfileOpt.ifPresent(profile -> this.deviceProfile = profile); } public boolean isConnected() { return connected; }
public void setDisconnected() { this.connected = false; } public boolean isSparkplug() { DeviceProfileTransportConfiguration transportConfiguration = this.deviceProfile.getProfileData().getTransportConfiguration(); if (transportConfiguration instanceof MqttDeviceProfileTransportConfiguration) { return ((MqttDeviceProfileTransportConfiguration) transportConfiguration).isSparkplug(); } else { return false; } } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\session\DeviceAwareSessionContext.java
1
请完成以下Java代码
public static Map<String, List<PlanItemInstanceEntity>> findChildPlanItemInstancesMap(CaseInstanceEntity caseInstanceEntity, List<PlanItem> planItems) { Map<String, List<PlanItemInstanceEntity>> result = new HashMap<>(); List<String> planItemIds = planItems.stream().map(PlanItem::getId).collect(Collectors.toList()); List<PlanItemInstanceEntity> childPlanItemInstances = getAllChildPlanItemInstances(caseInstanceEntity); for (PlanItemInstanceEntity childPlanItemInstance : childPlanItemInstances) { PlanItem childPlanItem = childPlanItemInstance.getPlanItem(); if (childPlanItem != null && planItemIds.contains(childPlanItem.getId())) { if (!result.containsKey(childPlanItem.getId())) { result.put(childPlanItem.getId(), new ArrayList<>()); } result.get(childPlanItem.getId()).add(childPlanItemInstance); } } return result; } /** * Returns a list of {@link PlanItemInstanceEntity} instances for the given {@link CaseInstanceEntity}, without any filtering. */ public static List<PlanItemInstanceEntity> getAllChildPlanItemInstances(CaseInstanceEntity caseInstanceEntity) { if (caseInstanceEntity == null) { throw new FlowableException("Programmatic error: case instance entity is null"); } // Typically, this comes out of the cache as the child plan item instance are cached on case instance fetch List<PlanItemInstanceEntity> planItemInstances = new ArrayList<>();
internalCollectPlanItemInstances(caseInstanceEntity, planItemInstances); return planItemInstances; } protected static void internalCollectPlanItemInstances(PlanItemInstanceContainer planItemInstanceContainer, List<PlanItemInstanceEntity> planItemInstances) { List<PlanItemInstanceEntity> childPlanItemInstances = planItemInstanceContainer.getChildPlanItemInstances(); if (childPlanItemInstances != null && !childPlanItemInstances.isEmpty()) { for (PlanItemInstanceEntity childPlanItemInstanceEntity : childPlanItemInstances) { planItemInstances.add(childPlanItemInstanceEntity); internalCollectPlanItemInstances(childPlanItemInstanceEntity, planItemInstances); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\CaseInstanceUtil.java
1
请完成以下Java代码
public int runAndGetUpdatedCount() { run(); return getStaleWorkpackagesCount(); } public int getStaleWorkpackagesCount() { Check.assumeNotNull(staleWorkpackagesCount, "staleWorkpackagesCount not null"); return staleWorkpackagesCount; } public WorkpackageCleanupStaleEntries setContext(final Properties ctx) { this._ctx = ctx; return this; } private Properties getCtx() { Check.assumeNotNull(_ctx, "_ctx not null"); return _ctx; } /** * Sets Stale Date. * * Only "stale workpackages" which were last updated before this date will be considered. * * @param staleDateFrom * @return */ public WorkpackageCleanupStaleEntries setStaleDateFrom(final Date staleDateFrom) { this._staleDateFrom = staleDateFrom; return this; } private Date getStaleDateFrom() { if (_staleDateFrom != null) { return _staleDateFrom; } // // Get default stale date final int staleDays = sysConfigBL.getIntValue(SYSCONFIG_StaleDays, DEFAULT_StaleDays); if (staleDays <= 0) { throw new AdempiereException("Invalid stale days sysconfig value: " + SYSCONFIG_StaleDays); } final Date staleDateFromDefault = TimeUtil.addDays(now, -staleDays); return staleDateFromDefault; } public WorkpackageCleanupStaleEntries setStaleErrorMsg(final String staleErrorMsg) { this._staleErrorMsg = staleErrorMsg; return this; } private String buildFullStaleErrorMsg() { final StringBuilder errorMsg = new StringBuilder(); final String baseErrorMsg = getStaleErrorMsg(); errorMsg.append(baseErrorMsg); final PInstanceId adPInstanceId = getPinstanceId(); if (adPInstanceId != null) {
errorMsg.append("; Updated by AD_PInstance_ID=").append(adPInstanceId.getRepoId()); } return errorMsg.toString(); } private String getStaleErrorMsg() { if (!Check.isEmpty(_staleErrorMsg, true)) { return _staleErrorMsg; } // Get the default return sysConfigBL.getValue(SYSCONFIG_StaleErrorMsg, DEFAULT_StaleErrorMsg); } /** * Sets AD_PInstance_ID to be used and tag all those workpackages which were deactivated. * * This is optional. * * @param adPInstanceId */ public WorkpackageCleanupStaleEntries setAD_PInstance_ID(final PInstanceId adPInstanceId) { this._adPInstanceId = adPInstanceId; return this; } private PInstanceId getPinstanceId() { return _adPInstanceId; } public WorkpackageCleanupStaleEntries setLogger(final ILoggable logger) { Check.assumeNotNull(logger, "logger not null"); this.logger = logger; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkpackageCleanupStaleEntries.java
1
请在Spring Boot框架中完成以下Java代码
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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getResetKey() { return resetKey; } public void setResetKey(String resetKey) { this.resetKey = resetKey; } public Instant getResetDate() { return resetDate; } public void setResetDate(Instant resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities;
} @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } return id != null && id.equals(((User) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
2
请完成以下Java代码
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 Subject. @param Subject Email Message Subject */ public void setSubject (String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Subject. @return Email Message Subject */ public String getSubject () { return (String)get_Value(COLUMNNAME_Subject); } /** Set Mail Message. @param W_MailMsg_ID Web Store Mail Message Template */ public void setW_MailMsg_ID (int W_MailMsg_ID) { if (W_MailMsg_ID < 1) set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null); else set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID)); } /** Get Mail Message. @return Web Store Mail Message Template */ public int getW_MailMsg_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID); if (ii == null)
return 0; return ii.intValue(); } public I_W_Store getW_Store() throws RuntimeException { return (I_W_Store)MTable.get(getCtx(), I_W_Store.Table_Name) .getPO(getW_Store_ID(), get_TrxName()); } /** Set Web Store. @param W_Store_ID A Web Store of the Client */ public void setW_Store_ID (int W_Store_ID) { if (W_Store_ID < 1) set_Value (COLUMNNAME_W_Store_ID, null); else set_Value (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID)); } /** Get Web Store. @return A Web Store of the Client */ public int getW_Store_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_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_MailMsg.java
1
请在Spring Boot框架中完成以下Java代码
public void setSince(String since) { this.since = since; } public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemDeprecation other = (ItemDeprecation) o; return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement) && nullSafeEquals(this.level, other.level) && nullSafeEquals(this.since, other.since); } @Override public int hashCode() { int result = nullSafeHashCode(this.reason);
result = 31 * result + nullSafeHashCode(this.replacement); result = 31 * result + nullSafeHashCode(this.level); result = 31 * result + nullSafeHashCode(this.since); return result; } @Override public String toString() { return "ItemDeprecation{reason='" + this.reason + '\'' + ", replacement='" + this.replacement + '\'' + ", level='" + this.level + '\'' + ", since='" + this.since + '\'' + '}'; } private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } private int nullSafeHashCode(Object o) { return (o != null) ? o.hashCode() : 0; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemDeprecation.java
2
请完成以下Java代码
public Customer findPublicCustomer(TenantId tenantId) { log.trace("Executing findPublicCustomer, tenantId [{}]", tenantId); Validator.validateId(tenantId, id -> INCORRECT_TENANT_ID + id); Optional<Customer> publicCustomerOpt = customerDao.findPublicCustomerByTenantId(tenantId.getId()); return publicCustomerOpt.orElse(null); } @Override public PageData<Customer> findCustomersByTenantId(TenantId tenantId, PageLink pageLink) { log.trace("Executing findCustomersByTenantId, tenantId [{}], pageLink [{}]", tenantId, pageLink); Validator.validateId(tenantId, id -> "Incorrect tenantId " + id); Validator.validatePageLink(pageLink); return customerDao.findCustomersByTenantId(tenantId.getId(), pageLink); } @Override public void deleteCustomersByTenantId(TenantId tenantId) { log.trace("Executing deleteCustomersByTenantId, tenantId [{}]", tenantId); Validator.validateId(tenantId, id -> "Incorrect tenantId " + id); customersByTenantRemover.removeEntities(tenantId, tenantId); } @Override public List<Customer> findCustomersByTenantIdAndIds(TenantId tenantId, List<CustomerId> customerIds) { log.trace("Executing findCustomersByTenantIdAndIds, tenantId [{}], customerIds [{}]", tenantId, customerIds); return customerDao.findCustomersByTenantIdAndIds(tenantId.getId(), customerIds.stream().map(CustomerId::getId).collect(Collectors.toList())); } @Override public void deleteByTenantId(TenantId tenantId) { deleteCustomersByTenantId(tenantId); } private final PaginatedRemover<TenantId, Customer> customersByTenantRemover = new PaginatedRemover<>() { @Override protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return customerDao.findCustomersByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, Customer entity) {
deleteCustomer(tenantId, new CustomerId(entity.getUuidId())); } }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public long countByTenantId(TenantId tenantId) { return customerDao.countByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java
1
请完成以下Java代码
public static Object stripZerosAndLogIssueIfBigDecimalScaleTooBig( @Nullable final Object value, @NonNull PO po) { final boolean valueIsNotBigDecimal = !(value instanceof BigDecimal); if (valueIsNotBigDecimal) { return value; // nothing to do } final int maxAllowedScale = 15; final BigDecimal bdValue = (BigDecimal)value; if (bdValue.scale() <= maxAllowedScale) { return bdValue; // nothing to do
} final BigDecimal bpWithoutTrailingZeroes = NumberUtils.stripTrailingDecimalZeros(bdValue); final String firstMessagePart = StringUtils.formatMessage( "The given value has scale={}; going to proceed with a stripped down value with scale={};", bdValue.scale(), bpWithoutTrailingZeroes.scale()); final String lastMessagePart = StringUtils.formatMessage(" value={}; po={}", bdValue, po); final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(new AdempiereException(firstMessagePart + lastMessagePart)); logger.warn(firstMessagePart + " created AD_Issue_ID={}" + lastMessagePart, issueId); return bpWithoutTrailingZeroes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\POUtils.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId;
} public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请完成以下Java代码
public boolean isDebugClosedTransactions() { return getTrxManager().isDebugClosedTransactions(); } @Override public String[] getActiveTransactionInfos() { final List<ITrx> trxs = getTrxManager().getActiveTransactionsList(); return toStringArray(trxs); } @Override public String[] getDebugClosedTransactionInfos() { final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions(); return toStringArray(trxs); } private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; } @Override
public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); } final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
private static AvailabilityResponseItemBuilder prepareResponseItemBuilder( @NonNull final Map<PZN, AvailabilityRequestItem> requestItemsByPZN, @NonNull final StockAvailabilityResponseItem responseItem, @NonNull final StockAvailabilityResponseItemPart responseItemPart) { // get the data to pass to the response item's builder final AvailabilityRequestItem correspondingRequestItem = requestItemsByPZN.get(responseItem.getPzn()); final ZonedDateTime datePromised = responseItemPart.getDeliveryDate(); // if we can't get a datePromised, then we assume the item as not available // final Type type = VerfuegbarkeitRueckmeldungTyp.NICHT_LIEFERBAR.equals(singleAnteil.getTyp()) ? Type.NOT_AVAILABLE : Type.AVAILABLE; final Type type = datePromised == null ? Type.NOT_AVAILABLE : Type.AVAILABLE; final String availabilityText = createAvailabilityText(responseItemPart); // create & return the response item return AvailabilityResponseItem.builder() .correspondingRequestItem(correspondingRequestItem) .productIdentifier(responseItem.getPzn().getValueAsString()) .availableQuantity(responseItemPart.getQty().getValueAsBigDecimal()) .datePromised(datePromised) .type(type) .availabilityText(availabilityText); } private static String createAvailabilityText(@NonNull final StockAvailabilityResponseItemPart reponseItemPart) { final StringBuilder availabilityText = new StringBuilder(); availabilityText.append(reponseItemPart.getType());
final boolean hasTour = !Check.isEmpty(reponseItemPart.getTour(), true); final StockAvailabilitySubstitutionReason reason = reponseItemPart.getReason(); final boolean hasDefectReason = !StockAvailabilitySubstitutionReason.NO_INFO.equals(reason); if (hasTour || hasDefectReason) { availabilityText.append(" ( "); } if (hasTour) { availabilityText.append("Tour " + reponseItemPart.getTour()); } if (hasDefectReason) { availabilityText.append("Grund " + reason); } if (hasTour || hasDefectReason) { availabilityText.append(" )"); } return availabilityText.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\availability\MSV3AvailiabilityClientImpl.java
1
请完成以下Java代码
public void setIsDeferredConstraints (boolean IsDeferredConstraints) { set_Value (COLUMNNAME_IsDeferredConstraints, Boolean.valueOf(IsDeferredConstraints)); } /** Get Defer Constraints. @return Defer Constraints */ @Override public boolean isDeferredConstraints () { Object oo = get_Value(COLUMNNAME_IsDeferredConstraints); 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 */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Release No. @param ReleaseNo Internal Release Number */ @Override public void setReleaseNo (java.lang.String ReleaseNo) { set_Value (COLUMNNAME_ReleaseNo, ReleaseNo); } /** Get Release No. @return Internal Release Number */ @Override public java.lang.String getReleaseNo () { return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo)
{ set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @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(); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_Value (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
1
请完成以下Java代码
public int getMgr() { return mgr; } public void setMgr(int mgr) { this.mgr = mgr; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public int getComm() { return comm; } public void setComm(int comm) {
this.comm = comm; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } @Override public String toString() { return String.format("Employee [empNo=%d, ename=%s, job=%s, mgr=%d, hiredate=%s, sal=%d, comm=%d, deptno=%d]", empNo, ename, job, mgr, hiredate, sal, comm, deptno); } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\flexypool\Employee.java
1
请完成以下Java代码
public class SortingAndBinarySearch { public static int findClosestToZero(int[] arr) { if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Array must not be null or Empty"); } Arrays.sort(arr); int closestNumber = arr[0]; int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (Math.abs(arr[mid]) < Math.abs(closestNumber)) {
closestNumber = arr[mid]; } if (arr[mid] < 0) { left = mid + 1; } else if (arr[mid] > 0) { right = mid - 1; } else { return arr[mid]; } } return closestNumber; } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\closesttozero\SortingAndBinarySearch.java
1
请完成以下Java代码
public final IHUAttributesDAO getHUAttributesDAO() { // TODO tbp: this exception is false: this.huAttributesDAO is NOT NULL! throw new HUException("No IHUAttributesDAO found on " + this); } @Override public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; // // Update factory if is instantiated if (factory != null) { factory.setHUAttributesDAO(huAttributesDAO); } } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; // // Update factory if is instantiated if (factory != null) { factory.setHUStorageFactory(huStorageFactory); } }
@Override public IHUStorageFactory getHUStorageFactory() { return huStorageFactory; } @Override public void flush() { final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO; if (huAttributesDAO != null) { huAttributesDAO.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java
1
请完成以下Java代码
class ElasticCommonSchemaStructuredLogFormatter extends JsonWriterStructuredLogFormatter<LogEvent> { ElasticCommonSchemaStructuredLogFormatter(Environment environment, @Nullable StackTracePrinter stackTracePrinter, ContextPairs contextPairs, StructuredLoggingJsonMembersCustomizer.Builder<?> customizerBuilder) { super((members) -> jsonMembers(environment, stackTracePrinter, contextPairs, members), customizerBuilder.nested().build()); } private static void jsonMembers(Environment environment, @Nullable StackTracePrinter stackTracePrinter, ContextPairs contextPairs, JsonWriter.Members<LogEvent> members) { Extractor extractor = new Extractor(stackTracePrinter); members.add("@timestamp", LogEvent::getInstant).as(ElasticCommonSchemaStructuredLogFormatter::asTimestamp); members.add("log").usingMembers((log) -> { log.add("level", LogEvent::getLevel).as(Level::name); log.add("logger", LogEvent::getLoggerName); }); members.add("process").usingMembers((process) -> { process.add("pid", environment.getProperty("spring.application.pid", Long.class)).whenNotNull(); process.add("thread").usingMembers((thread) -> thread.add("name", LogEvent::getThreadName)); }); ElasticCommonSchemaProperties.get(environment).jsonMembers(members); members.add("message", LogEvent::getMessage).as(StructuredMessage::get); members.from(LogEvent::getContextData) .usingPairs(contextPairs.nested(ElasticCommonSchemaStructuredLogFormatter::addContextDataPairs)); members.from(LogEvent::getThrown) .whenNotNull() .usingMembers((thrownMembers) -> thrownMembers.add("error").usingMembers((error) -> { error.add("type", ObjectUtils::nullSafeClassName); error.add("message", Throwable::getMessage); error.add("stack_trace", extractor::stackTrace); })); members.add("tags", LogEvent::getMarker) .whenNotNull() .as(ElasticCommonSchemaStructuredLogFormatter::getMarkers) .whenNotEmpty(); members.add("ecs").usingMembers((ecs) -> ecs.add("version", "8.11")); } private static void addContextDataPairs(Pairs<ReadOnlyStringMap> contextPairs) { contextPairs.add((contextData, pairs) -> contextData.forEach(pairs::accept)); }
private static java.time.Instant asTimestamp(Instant instant) { return java.time.Instant.ofEpochMilli(instant.getEpochMillisecond()).plusNanos(instant.getNanoOfMillisecond()); } private static Set<String> getMarkers(Marker marker) { Set<String> result = new TreeSet<>(); addMarkers(result, marker); return result; } private static void addMarkers(Set<String> result, Marker marker) { result.add(marker.getName()); if (marker.hasParents()) { for (Marker parent : marker.getParents()) { addMarkers(result, parent); } } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\ElasticCommonSchemaStructuredLogFormatter.java
1
请完成以下Java代码
public String getName() { return "Start job acquisition '"+jobAcquisitionXml.getName()+"'"; } public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final AbstractProcessApplication processApplication = operationContext.getAttachment(PROCESS_APPLICATION); ClassLoader configurationClassloader = null; if(processApplication != null) { configurationClassloader = processApplication.getProcessApplicationClassloader(); } else { configurationClassloader = ProcessEngineConfiguration.class.getClassLoader(); } String configurationClassName = jobAcquisitionXml.getJobExecutorClassName(); if(configurationClassName == null || configurationClassName.isEmpty()) { configurationClassName = RuntimeContainerJobExecutor.class.getName(); } // create & instantiate the job executor class Class<? extends JobExecutor> jobExecutorClass = loadJobExecutorClass(configurationClassloader, configurationClassName); JobExecutor jobExecutor = instantiateJobExecutor(jobExecutorClass); // apply properties Map<String, String> properties = jobAcquisitionXml.getProperties(); PropertyHelper.applyProperties(jobExecutor, properties);
// construct service for job executor JmxManagedJobExecutor jmxManagedJobExecutor = new JmxManagedJobExecutor(jobExecutor); // deploy the job executor service into the container serviceContainer.startService(ServiceTypes.JOB_EXECUTOR, jobAcquisitionXml.getName(), jmxManagedJobExecutor); } protected JobExecutor instantiateJobExecutor(Class<? extends JobExecutor> configurationClass) { try { return configurationClass.newInstance(); } catch (Exception e) { throw LOG.couldNotInstantiateJobExecutorClass(e); } } @SuppressWarnings("unchecked") protected Class<? extends JobExecutor> loadJobExecutorClass(ClassLoader processApplicationClassloader, String jobExecutorClassname) { try { return (Class<? extends JobExecutor>) processApplicationClassloader.loadClass(jobExecutorClassname); } catch (ClassNotFoundException e) { throw LOG.couldNotLoadJobExecutorClass(e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartJobAcquisitionStep.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class); @Autowired private UserDetailsService userDetailsService; @Autowired private JwtTokenUtil jwtTokenUtil; @Value("${jwt.tokenHeader}") private String tokenHeader; @Value("${jwt.tokenHead}") private String tokenHead; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader(this.tokenHeader);
if (authHeader != null && authHeader.startsWith(this.tokenHead)) { String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer " String username = jwtTokenUtil.getUserNameFromToken(authToken); LOGGER.info("checking username:{}", username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); LOGGER.info("authenticated user:{}", username); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\JwtAuthenticationTokenFilter.java
2
请完成以下Java代码
public Mono<String> asyncMono() { logger.info("async method start"); Mono<String> result = Mono.fromSupplier(this::execute); logger.info("async method end"); return result; } // SSE(Server Sent Event) // https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events // http://www.ruanyifeng.com/blog/2017/05/server-sent_events.html @GetMapping(value = "async/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> asyncFlux() { logger.info("async method start"); Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace();
} return "int value:" + i; })); logger.info("async method end"); return result; } private String execute() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } return "hello"; } }
repos\SpringAll-master\57.Spring-Boot-WebFlux\webflux\src\main\java\com\example\webflux\TestController.java
1
请完成以下Java代码
public ILookupData call() { // Set thread name final Thread thread = Thread.currentThread(); final String threadNameOld = thread.getName(); thread.setName(threadNameOld + "-" + this.threadName); boolean success = false; try (final INamePairIterator values = lookupDAO.retrieveLookupValues(validationCtx, lookupInfo)) { final ILookupData data = call0(values); success = true; return data; } finally { if (!success) { this.wasInterrupted = true; } thread.setName(threadNameOld); } } private final ILookupData call0(final INamePairIterator data) { final Stopwatch duration = Stopwatch.createStarted(); if (!data.isValid()) { this.validationKey = null; values.clear(); return this; } this.validationKey = MLookup.createValidationKey(validationCtx, lookupInfo, data.getValidationKey()); // check if (Thread.interrupted()) { log.warn("{}: Loader interrupted", threadName); this.wasInterrupted = true; return this; } // Reset values.clear(); hasInactiveValues = false; allLoaded = true; final INamePairPredicate postQueryFilter = lookupInfo.getValidationRule().getPostQueryFilter(); for (NamePair item = data.next(); item != null; item = data.next()) { final int rows = values.size(); if (rows >= MLookup.MAX_ROWS) { final String errmsg = lookupInfo.getSqlQuery().getKeyColumn() + ": Loader - Too many records. Please consider changing it to Search reference or use a (better) validation rule." + "\n Fetched Rows: " + rows + "\n Max rows allowed: " + MLookup.MAX_ROWS; log.warn(errmsg); allLoaded = false; break; } // check for interrupted every 20 rows if (rows % 20 == 0 && Thread.interrupted()) { this.wasInterrupted = true; break; } if (!data.wasActive()) { hasInactiveValues = true;
} if (!postQueryFilter.accept(validationCtx, item)) { continue; } values.put(item.getID(), item); } duration.stop(); return this; } // run @Override public ArrayKey getValidationKey() { return validationKey; } @Override public boolean hasInactiveValues() { return this.hasInactiveValues; } @Override public boolean isAllLoaded() { return allLoaded; } @Override public boolean isDirty() { return wasInterrupted; } private final String normalizeKey(final Object key) { return key == null ? null : key.toString(); } @Override public boolean containsKey(Object key) { final String keyStr = normalizeKey(key); return values.containsKey(keyStr); } @Override public NamePair getByKey(Object key) { final String keyStr = normalizeKey(key); return values.get(keyStr); } @Override public Collection<NamePair> getValues() { return values.values(); } @Override public int size() { return values.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MLookupLoader.java
1
请在Spring Boot框架中完成以下Java代码
protected AuthorizeTokenFilter authorizeTokenFilter(OAuth2AuthorizedClientManager clientManager) { logger.debug("Registering AuthorizeTokenFilter"); return new AuthorizeTokenFilter(clientManager); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, AuthorizeTokenFilter authorizeTokenFilter, @Nullable SsoLogoutSuccessHandler ssoLogoutSuccessHandler) throws Exception { logger.info("Enabling Camunda Spring Security oauth2 integration"); // @formatter:off http.authorizeHttpRequests(c -> c .requestMatchers(webappPath + "/app/**").authenticated() .requestMatchers(webappPath + "/api/**").authenticated() .anyRequest().permitAll() ) .addFilterAfter(authorizeTokenFilter, OAuth2AuthorizationRequestRedirectFilter.class) .anonymous(AbstractHttpConfigurer::disable) .oidcLogout(c -> c.backChannel(Customizer.withDefaults())) .oauth2Login(Customizer.withDefaults()) .logout(c -> c .clearAuthentication(true)
.invalidateHttpSession(true) ) .oauth2Client(Customizer.withDefaults()) .cors(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable); // @formatter:on if (oAuth2Properties.getSsoLogout().isEnabled()) { http.logout(c -> c.logoutSuccessHandler(ssoLogoutSuccessHandler)); } return http.build(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\CamundaSpringSecurityOAuth2AutoConfiguration.java
2
请完成以下Java代码
public class UpdateSequenceNo extends JavaProcess { private String year; @Override protected void prepare() { final ProcessInfoParameter[] parameters = this.getParametersAsArray(); for (final ProcessInfoParameter p : parameters) { if (p.getParameterName().equals("CalendarYear")) { year = p.getParameter().toString(); return; } } year = SystemTime.asZonedDateTime().getYear() + ""; } @Override protected String doIt() throws Exception { PreparedStatement insertStmt = null; try { insertStmt = DB .prepareStatement( "INSERT INTO AD_Sequence_No(AD_SEQUENCE_ID, CALENDARYEAR,CALENDARMONTH,CALENDARDAY, " + "AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, " + "UPDATED, UPDATEDBY, CURRENTNEXT) " + "(SELECT AD_Sequence_ID, ?, ?, ?, " + "AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, " + "Updated, UpdatedBy, StartNo " + "FROM AD_Sequence a " + "WHERE RestartFrequency IS NOT NULL AND NOT EXISTS ( " + "SELECT AD_Sequence_ID " + "FROM AD_Sequence_No b " + "WHERE a.AD_Sequence_ID = b.AD_Sequence_ID " + " AND CalendarYear = ?"
+ " AND CalendarMonth = ?" + " AND CalendarDay = ?)) ", get_TrxName()); insertStmt.setString(1, year); insertStmt.setString(4, year); final Year selectedYear = Year.of(Integer.parseInt(year)); for (int month = 1; month <= 12; month++) { final String monthAsString = month + ""; final int days = selectedYear.atMonth(month).lengthOfMonth(); for (int day = 1; day <= days; day++) { final String dayAsString = day + ""; insertStmt.setString(2, monthAsString); insertStmt.setString(3, dayAsString); insertStmt.setString(5, monthAsString); insertStmt.setString(6, dayAsString); insertStmt.executeUpdate(); } } } finally { DB.close(insertStmt); } return "Sequence No updated successfully"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\UpdateSequenceNo.java
1
请完成以下Java代码
protected List<IFacet<I_C_Invoice_Candidate>> collectFacets(final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder) { // FRESH-560: Add default filter final IQueryBuilder<I_C_Invoice_Candidate> queryBuilderWithDefaultFilters = Services.get(IInvoiceCandDAO.class).applyDefaultFilter(queryBuilder); final List<Map<String, Object>> orders = queryBuilderWithDefaultFilters .andCollect(I_C_Invoice_Candidate.COLUMN_C_Order_ID) .create() .listDistinct(I_C_Order.COLUMNNAME_C_Order_ID, I_C_Order.COLUMNNAME_DocumentNo); final List<IFacet<I_C_Invoice_Candidate>> facets = new ArrayList<>(orders.size()); for (final Map<String, Object> row : orders) { final IFacet<I_C_Invoice_Candidate> facet = createFacet(row); facets.add(facet); }
return facets; } private IFacet<I_C_Invoice_Candidate> createFacet(final Map<String, Object> row) { final IFacetCategory facetCategoryOrders = getFacetCategory(); final int orderId = (int)row.get(I_C_Order.COLUMNNAME_C_Order_ID); final String documentNo = (String)row.get(I_C_Order.COLUMNNAME_DocumentNo); return Facet.<I_C_Invoice_Candidate> builder() .setFacetCategory(facetCategoryOrders) .setDisplayName(documentNo) .setFilter(TypedSqlQueryFilter.of(I_C_Invoice_Candidate.COLUMNNAME_C_Order_ID + "=" + orderId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\facet\impl\C_Invoice_Candidate_Order_FacetCollector.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password;
} @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } @Override public int compareTo(Object o) { User u= (User) o; return this.id.compareTo(u.id); } }
repos\SpringBootLearning-master\sharding-jdbc-example\sharding-jdbc-db-ms-tbl\src\main\java\com\forezp\shardingjdbcdbmstbl\entity\User.java
1
请完成以下Java代码
public class TrackLog4jLoggerFactory implements ILoggerFactory { /** * key: name (String), value: a Log4jLoggerAdapter; */ Map loggerMap = new ConcurrentHashMap(); /* * (non-Javadoc) * * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) */ @Override public Logger getLogger(String name) { try { Logger slf4jLogger = null; // protect against concurrent access of loggerMap slf4jLogger = (Logger) loggerMap.get(name); if (slf4jLogger == null) { synchronized (this) { slf4jLogger = (Logger) loggerMap.get(name); if (slf4jLogger == null) {
Logger logger = LoggerFactory.getLogger(name); if (logger instanceof LocationAwareLogger) { slf4jLogger = new TrackLogger((LocationAwareLogger) logger); } else { slf4jLogger = logger; } loggerMap.put(name, slf4jLogger); } } } return slf4jLogger; } catch (Exception e) { return LoggerFactory.getLogger(name); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\core\TrackLog4jLoggerFactory.java
1
请完成以下Java代码
protected void validateParams(String appDefinitionId, String identityId, int identityIdType, String identityType) { if (appDefinitionId == null) { throw new FlowableIllegalArgumentException("appDefinitionId is null"); } if (identityType == null) { throw new FlowableIllegalArgumentException("type is required when adding a new task identity link"); } if (identityId == null) { throw new FlowableIllegalArgumentException("identityId is null"); } if (identityIdType != IDENTITY_USER && identityIdType != IDENTITY_GROUP) { throw new FlowableIllegalArgumentException("identityIdType allowed values are 1 and 2"); } } @Override
protected Void execute(CommandContext commandContext, AppDefinition appDefinition) { if (IDENTITY_USER == identityIdType) { CommandContextUtil.getIdentityLinkService().createScopeIdentityLink(appDefinition.getId(), null, ScopeTypes.APP, identityId, null, identityType); } else if (IDENTITY_GROUP == identityIdType) { CommandContextUtil.getIdentityLinkService().createScopeIdentityLink(appDefinition.getId(), null, ScopeTypes.APP, null, identityId, identityType); } return null; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\cmd\AddIdentityLinkCmd.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(Boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public Integer getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters;
} public Boolean getRemoveAbandoned() { return removeAbandoned; } public void setRemoveAbandoned(Boolean removeAbandoned) { this.removeAbandoned = removeAbandoned; } public Integer getRemoveAbandonedTimeout() { return removeAbandonedTimeout; } public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) { this.removeAbandonedTimeout = removeAbandonedTimeout; } }
repos\SpringBootBucket-master\springboot-transaction\src\main\java\com\xncoding\trans\config\DruidProperties.java
2
请完成以下Java代码
public class PrintTriangleExamples { public static String printARightTriangle(int N) { StringBuilder result = new StringBuilder(); for (int r = 1; r <= N; r++) { for (int j = 1; j <= r; j++) { result.append("*"); } result.append(System.lineSeparator()); } return result.toString(); } public static String printAnIsoscelesTriangle(int N) { StringBuilder result = new StringBuilder(); for (int r = 1; r <= N; r++) { for (int sp = 1; sp <= N - r; sp++) { result.append(" "); } for (int c = 1; c <= (r * 2) - 1; c++) { result.append("*"); } result.append(System.lineSeparator()); } return result.toString(); } public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
StringBuilder result = new StringBuilder(); for (int r = 1; r <= N; r++) { result.append(StringUtils.repeat(' ', N - r)); result.append(StringUtils.repeat('*', 2 * r - 1)); result.append(System.lineSeparator()); } return result.toString(); } public static String printAnIsoscelesTriangleUsingSubstring(int N) { StringBuilder result = new StringBuilder(); String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1); for (int r = 0; r < N; r++) { result.append(helperString.substring(r, N + 2 * r)); result.append(System.lineSeparator()); } return result.toString(); } public static void main(String[] args) { System.out.println(printARightTriangle(5)); System.out.println(printAnIsoscelesTriangle(5)); System.out.println(printAnIsoscelesTriangleUsingStringUtils(5)); System.out.println(printAnIsoscelesTriangleUsingSubstring(5)); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\printtriangles\PrintTriangleExamples.java
1
请完成以下Java代码
public void addInvolvedExecution(ExecutionEntity executionEntity) { if (executionEntity.getId() != null) { involvedExecutions.put(executionEntity.getId(), executionEntity); } } public boolean hasInvolvedExecutions() { return involvedExecutions.size() > 0; } public Collection<ExecutionEntity> getInvolvedExecutions() { return involvedExecutions.values(); } // getters and setters // ////////////////////////////////////////////////////// public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public ActivitiEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); }
public ActivitiEngineAgenda getAgenda() { return agenda; } public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public boolean isReused() { return reused; } public void setReused(boolean reused) { this.reused = reused; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
public void setReceiveInquiryReply (boolean ReceiveInquiryReply) { set_Value (COLUMNNAME_ReceiveInquiryReply, Boolean.valueOf(ReceiveInquiryReply)); } /** Get Received Inquiry Reply. @return Received Inquiry Reply */ public boolean isReceiveInquiryReply () { Object oo = get_Value(COLUMNNAME_ReceiveInquiryReply); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Receive Order Reply. @param ReceiveOrderReply Receive Order Reply */ public void setReceiveOrderReply (boolean ReceiveOrderReply) { set_Value (COLUMNNAME_ReceiveOrderReply, Boolean.valueOf(ReceiveOrderReply)); } /** Get Receive Order Reply. @return Receive Order Reply */ public boolean isReceiveOrderReply () { Object oo = get_Value(COLUMNNAME_ReceiveOrderReply); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send Inquiry. @param SendInquiry Quantity Availability Inquiry */ public void setSendInquiry (boolean SendInquiry) { set_Value (COLUMNNAME_SendInquiry, Boolean.valueOf(SendInquiry)); } /** Get Send Inquiry. @return Quantity Availability Inquiry */ public boolean isSendInquiry () { Object oo = get_Value(COLUMNNAME_SendInquiry);
if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send Order. @param SendOrder Send Order */ public void setSendOrder (boolean SendOrder) { set_Value (COLUMNNAME_SendOrder, Boolean.valueOf(SendOrder)); } /** Get Send Order. @return Send Order */ public boolean isSendOrder () { Object oo = get_Value(COLUMNNAME_SendOrder); 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_BP_EDI.java
1
请在Spring Boot框架中完成以下Java代码
public class C_ProjectLine { public C_ProjectLine() { // register ourselves final IProgramaticCalloutProvider programmaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programmaticCalloutProvider.registerAnnotatedCallout(this); CopyRecordFactory.enableForTableName(I_C_Project.Table_Name); } @CalloutMethod(columnNames = I_C_ProjectLine.COLUMNNAME_PlannedQty) public void onPlannedQty(final I_C_ProjectLine projectLine) { updatePlannedAmt(projectLine); }
@CalloutMethod(columnNames = I_C_ProjectLine.COLUMNNAME_PlannedQty) public void onPlannedPrice(final I_C_ProjectLine projectLine) { updatePlannedAmt(projectLine); } private void updatePlannedAmt(final I_C_ProjectLine projectLine) { final BigDecimal plannedQty = projectLine.getPlannedQty(); final BigDecimal plannedPrice = projectLine.getPlannedPrice(); final BigDecimal plannedAmt = plannedQty.multiply(plannedPrice); projectLine.setPlannedAmt(plannedAmt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\callout\C_ProjectLine.java
2
请完成以下Java代码
private static ArrayList<String> retrieveActiveProfilesFromSysConfig() { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); return new ArrayList<>(sysConfigBL .getValuesForPrefix(SYSCONFIG_PREFIX_APP_SPRING_PROFILES_ACTIVE, ClientAndOrgId.SYSTEM) .values()); } @Bean @Primary public ObjectMapper jsonObjectMapper() { return JsonObjectMapperHolder.sharedJsonObjectMapper(); } @Bean(Adempiere.BEAN_NAME) public Adempiere adempiere() { // when this is done, Adempiere.getBean(...) is ready to use return Env.getSingleAdempiereInstance(applicationContext); } @Override public void afterPropertiesSet() { if (clearQuerySelectionsRateInSeconds > 0) { final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(
1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix("cleanup-" + I_T_Query_Selection.Table_Name) .build()); // note: "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute." scheduledExecutor.scheduleAtFixedRate( QuerySelectionToDeleteHelper::deleteScheduledSelectionsNoFail, // command, don't fail because on failure the task won't be re-scheduled so it's game over clearQuerySelectionsRateInSeconds, // initialDelay clearQuerySelectionsRateInSeconds, // period TimeUnit.SECONDS // timeUnit ); logger.info("Clearing query selection tables each {} seconds", clearQuerySelectionsRateInSeconds); } } private static void setDefaultProperties() { if (Check.isBlank(System.getProperty(SYSTEM_PROPERTY_APP_NAME))) { System.setProperty(SYSTEM_PROPERTY_APP_NAME, ServerBoot.class.getSimpleName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\ServerBoot.java
1
请完成以下Java代码
public void setHelp (java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Kommentar/Hilfe. @return Comment or Hint */ @Override public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Kostenkategorie. @param M_CostType_ID Type of Cost (e.g. Current, Plan, Future) */ @Override public void setM_CostType_ID (int M_CostType_ID) { if (M_CostType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID)); } /** Get Kostenkategorie. @return Type of Cost (e.g. Current, Plan, Future) */ @Override public int getM_CostType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostType.java
1
请完成以下Java代码
public class GoodResponse { private Long goodId; private String name; private BigDecimal price; private Long retailer; private Long retailerId; private String city; private byte[] image; private String ingredients; private Boolean isOutdated;
private String internalCode; private Boolean isAddToBucket; public GoodResponse(Good good) { this.goodId = good.getId(); this.name = good.getName(); this.price = good.getCurrentPrice(); this.retailer = good.getRetailer().getInternalCode(); this.internalCode = good.getInternalCode(); this.isAddToBucket = good.getAddToBucket(); this.retailerId = good.getRetailer().getId(); this.city = good.getRetailer().getCity(); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\payload\good\GoodResponse.java
1
请完成以下Java代码
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode()); final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode); final HUInfo pickFromHU = HUInfo.builder() .id(huId) .qrCode(qrCode) .build();
return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU) ); } private HUQRCode parseHUQRCode(final String scannedCode) { final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode); if (huQRCode instanceof HUQRCode) { return (HUQRCode)huQRCode; } else { throw new AdempiereException("Invalid HU QR code: " + scannedCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java
1
请完成以下Java代码
public void setAD_PInstance_ID (final int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, AD_PInstance_ID); } @Override public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem_Service_Instance getExternalSystem_Service_Instance() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Service_Instance_ID, de.metas.externalsystem.model.I_ExternalSystem_Service_Instance.class); } @Override public void setExternalSystem_Service_Instance(final de.metas.externalsystem.model.I_ExternalSystem_Service_Instance ExternalSystem_Service_Instance) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Service_Instance_ID, de.metas.externalsystem.model.I_ExternalSystem_Service_Instance.class, ExternalSystem_Service_Instance); } @Override public void setExternalSystem_Service_Instance_ID (final int ExternalSystem_Service_Instance_ID) { if (ExternalSystem_Service_Instance_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, ExternalSystem_Service_Instance_ID); } @Override public int getExternalSystem_Service_Instance_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_Instance_ID); } @Override public void setExternalSystem_Status_ID (final int ExternalSystem_Status_ID) { if (ExternalSystem_Status_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, ExternalSystem_Status_ID); } @Override
public int getExternalSystem_Status_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Status_ID); } @Override public void setExternalSystemMessage (final @Nullable java.lang.String ExternalSystemMessage) { set_Value (COLUMNNAME_ExternalSystemMessage, ExternalSystemMessage); } @Override public java.lang.String getExternalSystemMessage() { return get_ValueAsString(COLUMNNAME_ExternalSystemMessage); } /** * ExternalSystemStatus AD_Reference_ID=541502 * Reference name: ExpectedStatus */ public static final int EXTERNALSYSTEMSTATUS_AD_Reference_ID=541502; /** Active = Active */ public static final String EXTERNALSYSTEMSTATUS_Active = "Active"; /** Inactive = Inactive */ public static final String EXTERNALSYSTEMSTATUS_Inactive = "Inactive"; /** Error = Error */ public static final String EXTERNALSYSTEMSTATUS_Error = "Error "; /** Down = Down */ public static final String EXTERNALSYSTEMSTATUS_Down = "Down"; @Override public void setExternalSystemStatus (final java.lang.String ExternalSystemStatus) { set_Value (COLUMNNAME_ExternalSystemStatus, ExternalSystemStatus); } @Override public java.lang.String getExternalSystemStatus() { return get_ValueAsString(COLUMNNAME_ExternalSystemStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Status.java
1
请完成以下Java代码
private void completeSalesOrder(@NonNull final OrderId salesOrderId) { final IOrderDAO ordersRepo = Services.get(IOrderDAO.class); final I_C_Order order = ordersRepo.getById(salesOrderId); final DocStatus orderDocStatus = DocStatus.ofCode(order.getDocStatus()); if (orderDocStatus.isWaitingForPayment()) { Services.get(IDocumentBL.class).processEx(order, IDocument.ACTION_WaitComplete); ordersRepo.save(order); } } public void processCapture( @NonNull final PaymentReservation reservation, @NonNull final PaymentReservationCapture capture) { reservation.getStatus().assertCompleted(); PayPalOrder paypalOrder = paypalOrderService.getByReservationId(capture.getReservationId()); final Boolean finalCapture = null;
final Capture apiCapture = paypalClient.captureOrder( paypalOrder.getAuthorizationId(), moneyService.toAmount(capture.getAmount()), finalCapture, createPayPalClientExecutionContext(capture, paypalOrder)); paypalOrder = updatePayPalOrderFromAPI(paypalOrder.getExternalId()); updateReservationFromPayPalOrderNoSave(reservation, paypalOrder); } private static void updateReservationFromPayPalOrderNoSave( @NonNull final PaymentReservation reservation, @NonNull final PayPalOrder payPalOrder) { reservation.changeStatusTo(payPalOrder.getStatus().toPaymentReservationStatus()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPal.java
1
请在Spring Boot框架中完成以下Java代码
public class MicrometerEventBusStatsCollector { Counter eventsEnqueued; Counter eventsDequeued; AtomicLong queueLength; Timer eventProcessingTimer; public void incrementEventsEnqueued() { eventsEnqueued.increment(); updateQueueLength(); } public void incrementEventsDequeued() {
eventsDequeued.increment(); updateQueueLength(); } private void updateQueueLength() { // not sure why but when i did just queueLength.getAndIncrement() / getAndDecrement(), the length wasn't correct queueLength.set(Math.round(eventsEnqueued.count() - Math.round(eventsDequeued.count()))); } public EventBusStats snapshot() { return EventBusStats.builder() .eventsEnqueued(Math.round(eventsEnqueued.count())) .eventsDequeued(Math.round(eventsDequeued.count())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\MicrometerEventBusStatsCollector.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_K_EntryRelated[") .append(get_ID()).append("]"); return sb.toString(); } public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Related Entry. @param K_EntryRelated_ID Related Entry for this Enntry */ public void setK_EntryRelated_ID (int K_EntryRelated_ID) { if (K_EntryRelated_ID < 1) set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, null);
else set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, Integer.valueOf(K_EntryRelated_ID)); } /** Get Related Entry. @return Related Entry for this Enntry */ public int getK_EntryRelated_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getK_EntryRelated_ID())); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryRelated.java
1
请完成以下Java代码
public class QuartzConfig { /** * 解决Job中注入Spring Bean为null的问题 */ @Component("quartzJobFactory") public static class QuartzJobFactory extends AdaptableJobFactory { private final AutowireCapableBeanFactory capableBeanFactory; @Autowired public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) { this.capableBeanFactory = capableBeanFactory; }
@NonNull @Override protected Object createJobInstance(@NonNull TriggerFiredBundle bundle) throws Exception { try { // 调用父类的方法,把Job注入到spring中 Object jobInstance = super.createJobInstance(bundle); capableBeanFactory.autowireBean(jobInstance); log.debug("Job instance created and autowired: {}", jobInstance.getClass().getName()); return jobInstance; } catch (Exception e) { log.error("Error creating job instance for bundle: {}", bundle, e); throw e; } } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\config\QuartzConfig.java
1
请完成以下Java代码
public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) { HistoricJobLogDto result = new HistoricJobLogDto(); result.id = historicJobLog.getId(); result.timestamp = historicJobLog.getTimestamp(); result.removalTime = historicJobLog.getRemovalTime(); result.jobId = historicJobLog.getJobId(); result.jobDueDate = historicJobLog.getJobDueDate(); result.jobRetries = historicJobLog.getJobRetries(); result.jobPriority = historicJobLog.getJobPriority(); result.jobExceptionMessage = historicJobLog.getJobExceptionMessage(); result.jobDefinitionId = historicJobLog.getJobDefinitionId(); result.jobDefinitionType = historicJobLog.getJobDefinitionType(); result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration(); result.activityId = historicJobLog.getActivityId(); result.failedActivityId = historicJobLog.getFailedActivityId(); result.executionId = historicJobLog.getExecutionId(); result.processInstanceId = historicJobLog.getProcessInstanceId(); result.processDefinitionId = historicJobLog.getProcessDefinitionId();
result.processDefinitionKey = historicJobLog.getProcessDefinitionKey(); result.deploymentId = historicJobLog.getDeploymentId(); result.tenantId = historicJobLog.getTenantId(); result.hostname = historicJobLog.getHostname(); result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId(); result.batchId = historicJobLog.getBatchId(); result.creationLog = historicJobLog.isCreationLog(); result.failureLog = historicJobLog.isFailureLog(); result.successLog = historicJobLog.isSuccessLog(); result.deletionLog = historicJobLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogDto.java
1
请完成以下Java代码
public static String encodeBase64String(String str) { BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(str.getBytes()); } /** * 用base64算法进行解密 * * @param str * 需要解密的字符串 * @return base64解密后的结果 * @throws IOException */ public static String decodeBase64String(String str) throws IOException { BASE64Decoder encoder = new BASE64Decoder(); return new String(encoder.decodeBuffer(str)); } private static String encode(String str, String method) { MessageDigest mdInst = null; // 把密文转换成十六进制的字符串形式 // 单线程用StringBuilder,速度快 多线程用stringbuffer,安全 StringBuilder dstr = new StringBuilder(); try { // 获得MD5摘要算法的 MessageDigest对象 mdInst = MessageDigest.getInstance(method); // 使用指定的字节更新摘要 mdInst.update(str.getBytes()); // 获得密文
byte[] md = mdInst.digest(); for (int i = 0; i < md.length; i++) { int tmp = md[i]; if (tmp < 0) { tmp += 256; } if (tmp < 16) { dstr.append("0"); } dstr.append(Integer.toHexString(tmp)); } } catch (NoSuchAlgorithmException e) { LOG.error(e); } return dstr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\EncryptUtil.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean isTHM() { return thm; } /** * Sets the value of the thm property. * * @param value * allowed object is * {@link Boolean } * */ public void setTHM(Boolean value) { this.thm = value; } /** * Gets the value of the nonReturnableContainer property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNonReturnableContainer() { return nonReturnableContainer; } /** * Sets the value of the nonReturnableContainer property. * * @param value * allowed object is * {@link Boolean } * */ public void setNonReturnableContainer(Boolean value) { this.nonReturnableContainer = value; } /** * Gets the value of the specialConditionCode property. * * @return * possible object is
* {@link String } * */ public String getSpecialConditionCode() { return specialConditionCode; } /** * Sets the value of the specialConditionCode property. * * @param value * allowed object is * {@link String } * */ public void setSpecialConditionCode(String value) { this.specialConditionCode = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICListLineItemExtensionType.java
2
请完成以下Java代码
public synchronized void onSubscribe(Subscription subscription) { log.info("Subscriber is subscribed."); this.subscription = subscription; subscription.request(1); } @Override public synchronized void onNext(Row row) { String jsonString = row.asObject().toJsonString(); log.info("Row JSON: {}", jsonString); try { T item = OBJECT_MAPPER.readValue(jsonString, this.clazz); log.info("Item: {}", item); consumedItems.add(item); } catch (JsonProcessingException e) { log.error("Unable to parse json", e); }
// Request the next row subscription.request(1); } @Override public synchronized void onError(Throwable t) { log.error("Received an error", t); } @Override public synchronized void onComplete() { log.info("Query has ended."); } }
repos\tutorials-master\ksqldb\src\main\java\com\baeldung\ksqldb\RowSubscriber.java
1
请完成以下Java代码
public String getStringValue() { return stringValue; } public void setStringValue(final String stringValue) { this.stringValue = stringValue; } public int getIntValue() { return intValue; } public void setIntValue(final int intValue) { this.intValue = intValue; } public boolean isBooleanValue() { return booleanValue;
} public void setBooleanValue(final boolean booleanValue) { this.booleanValue = booleanValue; } public Distance getType() { return type; } public void setType(final Distance type) { this.type = type; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\enums\withEnum\MyDtoWithEnumCustom.java
1
请完成以下Java代码
protected String retrieveHeader(Headers headers, String headerName) { String classId = retrieveHeaderAsString(headers, headerName); if (classId == null) { throw new MessageConversionException( "failed to convert Message content. Could not resolve " + headerName + " in header"); } return classId; } protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) { Header header = headers.lastHeader(headerName); if (header != null) { String classId = null; if (header.value() != null) { classId = new String(header.value(), StandardCharsets.UTF_8); } return classId; } return null; } private void createReverseMap() { this.classIdMapping.clear(); for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) { String id = entry.getKey(); Class<?> clazz = entry.getValue(); this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8));
} } public Map<String, Class<?>> getIdClassMapping() { return Collections.unmodifiableMap(this.idClassMapping); } /** * Configure the TypeMapper to use default key type class. * @param isKey Use key type headers if true * @since 2.1.3 */ public void setUseForKey(boolean isKey) { if (isKey) { setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME); setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME); setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java
1
请完成以下Java代码
public void upload(String bucketName, File file) { upload(bucketName, file, null); } public void upload(String bucketName, File file, Map<String, String> metadata) { s3Client .putObject(request -> request .bucket(bucketName) .key(file.getName()) .metadata(metadata) .ifNoneMatch("*"), file.toPath()); } public void download(String bucketName, String key, Path downloadPath) { s3Client.getObject(request -> request .bucket(bucketName) .key(key), ResponseTransformer.toFile(downloadPath)); } public void copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey) { s3Client.copyObject(request -> request .sourceBucket(sourceBucketName) .sourceKey(sourceKey) .destinationBucket(destinationBucketName) .destinationKey(destinationKey)); }
public void delete(String bucketName, String key) { s3Client.deleteObject(request -> request .bucket(bucketName) .key(key)); } public void delete(String bucketName, List<String> keys) { List<ObjectIdentifier> objectsToDelete = keys .stream() .map(key -> ObjectIdentifier .builder() .key(key) .build()) .toList(); s3Client.deleteObjects(request -> request .bucket(bucketName) .delete(deleteRequest -> deleteRequest .objects(objectsToDelete))); } }
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3ObjectOperationService.java
1
请完成以下Java代码
public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { final PricingConditionsView view = views.getIfPresent(viewId); if (view == null || !view.isAllowClosingPerUserRequest()) { return; } if (closeAction.isDone()) { onViewClosedByUser(view); } views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } @Override public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final PricingConditionsView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PricingConditionsView createView(@NonNull final CreateViewRequest request) { final PricingConditionsRowData rowsData = createPricingConditionsRowData(request); return createView(rowsData); } protected abstract PricingConditionsRowData createPricingConditionsRowData(CreateViewRequest request); private PricingConditionsView createView(final PricingConditionsRowData rowsData) { return PricingConditionsView.builder() .viewId(ViewId.random(windowId)) .rowsData(rowsData) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_CopyRowToEditable.class)) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_SaveEditableRow.class)) .filterDescriptors(filtersFactory.getFilterDescriptorsProvider()) .build(); } protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData() { return PricingConditionsRowsLoader.builder() .lookups(lookups); } @Override public PricingConditionsView filterView(
@NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo_IGNORED) { return PricingConditionsView.cast(view) .filter(filtersFactory.extractFilters(filterViewRequest)); } private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable() .anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } protected final DocumentFilterList extractFilters(final CreateViewRequest request) { return filtersFactory.extractFilters(request); } @lombok.Value(staticConstructor = "of") private static final class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
1
请完成以下Java代码
public String getDValue() { return " m0 1.5 l0 13 l17 0 l0 -13 z M1.5 3 L6 7.5 L1.5 12 z M3.5 3 L13.5 3 L8.5 8 z m12 0 l0 9 l-4.5 -4.5 z M7 8.5 L8.5 10 L10 8.5 L14.5 13 L2.5 13 z"; } public void drawIcon( final int imageX, final int imageY, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 1) + "," + (imageY - 2) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); pathTag.setAttributeNS(null, "stroke-widthh", this.getStrokeWidth()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag);
} @Override public String getAnchorValue() { return null; } @Override public String getStyleValue() { return null; } @Override public Integer getWidth() { return 17; } @Override public Integer getHeight() { return 13; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\MessageIconType.java
1
请在Spring Boot框架中完成以下Java代码
public List<UserVO> list() { // 查询列表 List<UserVO> result = new ArrayList<>(); result.add(new UserVO().setId(1).setUsername("yudaoyuanma")); result.add(new UserVO().setId(2).setUsername("woshiyutou")); result.add(new UserVO().setId(3).setUsername("chifanshuijiao")); // 返回列表 return result; } @GetMapping("/get") @ApiOperation("获得指定用户编号的用户") @ApiImplicitParam(name = "id", value = "用户编号", paramType = "query", dataTypeClass = Integer.class, required = true, example = "1024") public UserVO get(@RequestParam("id") Integer id) { // 查询并返回用户 return new UserVO().setId(id).setUsername(UUID.randomUUID().toString()); } @PostMapping("add") @ApiOperation("添加用户") public Integer add(UserAddDTO addDTO) { // 插入用户记录,返回编号 Integer returnId = UUID.randomUUID().hashCode(); // 返回用户编号 return returnId; }
@PostMapping("/update") @ApiOperation("更新指定用户编号的用户") public Boolean update(UserUpdateDTO updateDTO) { // 更新用户记录 Boolean success = true; // 返回更新是否成功 return success; } @PostMapping("/delete") @ApiOperation(value = "删除指定用户编号的用户") @ApiImplicitParam(name = "id", value = "用户编号", paramType = "query", dataTypeClass = Integer.class, required = true, example = "1024") public Boolean delete(@RequestParam("id") Integer id) { // 删除用户记录 Boolean success = false; // 返回是否更新成功 return success; } }
repos\SpringBoot-Labs-master\lab-24\lab-24-apidoc-swagger\src\main\java\cn\iocoder\springboot\lab24\apidoc\controller\UserController.java
2
请完成以下Java代码
public void setupIfIsWholeTax(final I_C_Tax tax) { if (!tax.isWholeTax()) { return; } tax.setRate(BigDecimal.valueOf(100)); tax.setIsTaxExempt(false); tax.setIsDocumentLevel(true); // tax.setIsSalesTax(false); // does not matter } @Override public TaxCategoryId retrieveRegularTaxCategoryId() { final TaxCategoryId taxCategoryId = Services.get(IQueryBL.class) .createQueryBuilder(I_C_TaxCategory.class) .addEqualsFilter(I_C_TaxCategory.COLUMN_VATType, X_C_TaxCategory.VATTYPE_RegularVAT) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .orderBy(I_C_TaxCategory.COLUMN_Name) .create() .firstId(TaxCategoryId::ofRepoIdOrNull); if (taxCategoryId == null) { throw new AdempiereException("No tax category found for Regular VATType"); } return taxCategoryId; } @NonNull public Optional<TaxCategoryId> getTaxCategoryIdByInternalName(@NonNull final String internalName)
{ return Services.get(IQueryBL.class) .createQueryBuilder(I_C_TaxCategory.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_TaxCategory.COLUMNNAME_InternalName, internalName) .create() .firstOnlyOptional(I_C_TaxCategory.class) .map(I_C_TaxCategory::getC_TaxCategory_ID) .map(TaxCategoryId::ofRepoId); } @Override public Tax getDefaultTax(final TaxCategoryId taxCategoryId) { return taxDAO.getDefaultTax(taxCategoryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\impl\TaxBL.java
1
请完成以下Java代码
public Optional<String> getTextMessageIfApplies(ITableRecordReference referencedRecord) { if (referencedRecord.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Print_Job_Instructions.class)) { return Optional.absent(); } final IContextAware context = PlainContextAware.newOutOfTrxAllowThreadInherited(Env.getCtx()); // the reference record must be a I_C_PrintJobInstructions entry final I_C_Print_Job_Instructions printJobInstructions = referencedRecord.getModel(context, I_C_Print_Job_Instructions.class); final I_C_Print_Job_Instructions_v printingInfo = InterfaceWrapperHelper.create( Services.get(IPrintJobDAO.class).retrieveC_Print_Job_Instructions_Info(printJobInstructions), I_C_Print_Job_Instructions_v.class); if (printingInfo == null) { return Optional.absent(); } // an archive must exist in the C_Print_Job_Instructions_v view linked with this C_Print_Job_Instructions entry final I_AD_Archive archive = printingInfo.getAD_Archive(); if (archive == null) { return Optional.absent(); } // the archive must point to the C_Order_MFGWarehouse_Report table if (archive.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Order_MFGWarehouse_Report.class)) { return Optional.absent();
} final I_C_Order_MFGWarehouse_Report mfgWarehouseReport = printingInfo.getC_Order_MFGWarehouse_Report(); // in case there is no I_C_Order_MFGWarehouse_Report with the ID given by AD_Archive's Record_ID ( shall never happen), // just display the original error message from the print job instructions if (mfgWarehouseReport == null) { return DefaultPrintingRecordTextProvider.instance.getTextMessage(printJobInstructions); } final Properties ctx = InterfaceWrapperHelper.getCtx(printJobInstructions); final I_C_Order order = printingInfo.getC_Order(); final String orderDocNo = order == null ? "" : order.getDocumentNo(); final StringBuilder mfgWarehouseReportID = new StringBuilder(); mfgWarehouseReportID.append(mfgWarehouseReport.getC_Order_MFGWarehouse_Report_ID()); final String textMessge = Services.get(IMsgBL.class).getMsg(ctx, MSG_PrintingInfo_MFGWarehouse_Report, new Object[] { orderDocNo, mfgWarehouseReportID.toString() }); return Optional.of(CoalesceUtil.coalesce(textMessge, "")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\printing\spi\impl\C_Order_MFGWarehouse_Report_RecordTextProvider.java
1
请完成以下Java代码
public int countNotNulls(@Nullable final Object... values) { if (values == null || values.length == 0) { return 0; } int count = 0; for (final Object value : values) { if (value != null) { count++; } } return count; }
@NonNull public BigDecimal firstPositiveOrZero(final BigDecimal... values) { if (values == null) { return BigDecimal.ZERO; } for (final BigDecimal value : values) { if (value != null && value.signum() > 0) { return value; } } return BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\CoalesceUtil.java
1
请在Spring Boot框架中完成以下Java代码
public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public Date getLockTime() { return lockTime; } @Override public void setLockTime(Date lockTime) { this.lockTime = lockTime; } @Override public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName().replace("EntityImpl", "")).append("[")
.append("id=").append(id) .append(", eventType=").append(eventType); if (activityId != null) { sb.append(", activityId=").append(activityId); } if (executionId != null) { sb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId); } else if (scopeId != null) { sb.append(", scopeId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeType=").append(scopeType) .append(", scopeDefinitionId=").append(scopeDefinitionId); } if (processDefinitionId != null) { sb.append(", processDefinitionId=").append(processDefinitionId); } else if (scopeDefinitionId != null) { if (scopeId == null) { sb.append(", scopeType=").append(scopeType); } sb.append(", scopeDefinitionId=").append(scopeDefinitionId); } if (scopeDefinitionKey != null) { sb.append(", scopeDefinitionKey=").append(scopeDefinitionKey); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\EventSubscriptionEntityImpl.java
2
请完成以下Java代码
public Builder expiresIn(long expiresIn) { this.expiresIn = expiresIn; return this; } /** * Sets the minimum amount of time (in seconds) that the client should wait * between polling requests to the token endpoint. * @param interval the minimum amount of time between polling requests * @return the {@link Builder} */ public Builder interval(long interval) { this.interval = interval; return this; } /** * Sets the additional parameters returned in the response. * @param additionalParameters the additional parameters returned in the response * @return the {@link Builder} */ public Builder additionalParameters(Map<String, Object> additionalParameters) { this.additionalParameters = additionalParameters; return this; } /** * Builds a new {@link OAuth2DeviceAuthorizationResponse}. * @return a {@link OAuth2DeviceAuthorizationResponse} */
public OAuth2DeviceAuthorizationResponse build() { Assert.hasText(this.verificationUri, "verificationUri cannot be empty"); Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero"); Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(this.expiresIn); OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt); OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt); OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse(); deviceAuthorizationResponse.deviceCode = deviceCode; deviceAuthorizationResponse.userCode = userCode; deviceAuthorizationResponse.verificationUri = this.verificationUri; deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete; deviceAuthorizationResponse.interval = this.interval; deviceAuthorizationResponse.additionalParameters = Collections .unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap() : this.additionalParameters); return deviceAuthorizationResponse; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2DeviceAuthorizationResponse.java
1
请完成以下Java代码
public class SecuritiesAccount13 { @XmlElement(name = "Id", required = true) protected String id; @XmlElement(name = "Tp") protected GenericIdentification20 tp; @XmlElement(name = "Nm") protected String nm; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link GenericIdentification20 } * */ public GenericIdentification20 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link GenericIdentification20 } * */ public void setTp(GenericIdentification20 value) {
this.tp = value; } /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\SecuritiesAccount13.java
1
请完成以下Java代码
public class FileManager { public static String getFirstLine(String fileName) throws IncorrectFileNameException { try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) { return file.nextLine(); } else { throw new IllegalArgumentException("Non readable file"); } } catch (FileNotFoundException err) { if (!isCorrectFileName(fileName)) { throw new IncorrectFileNameException("Incorrect filename : " + fileName, err); } // Logging etc } catch (IllegalArgumentException err) { if (!containsExtension(fileName)) { throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err); } // Other error cases and logging } return "Default First Line"; }
private static boolean containsExtension(String fileName) { if (fileName.contains(".txt") || fileName.contains(".doc")) return true; return false; } private static boolean isCorrectFileName(String fileName) { if (fileName.equals("wrongFileName.txt")) return false; else return true; } }
repos\tutorials-master\core-java-modules\core-java-exceptions\src\main\java\com\baeldung\exceptions\customexception\FileManager.java
1
请完成以下Java代码
public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public double getRt() { return rt; } public void setRt(double rt) { this.rt = rt; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getResourceCode() { return resourceCode; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) {
this.successQps = successQps; } @Override public String toString() { return "MetricEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", timestamp=" + timestamp + ", resource='" + resource + '\'' + ", passQps=" + passQps + ", blockQps=" + blockQps + ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + rt + ", count=" + count + ", resourceCode=" + resourceCode + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java
1
请完成以下Java代码
public class HistoricCaseInstanceDto { protected String id; protected String businessKey; protected String caseDefinitionId; protected String caseDefinitionKey; protected String caseDefinitionName; protected Date createTime; protected Date closeTime; protected Long durationInMillis; protected String createUserId; protected String superCaseInstanceId; protected String superProcessInstanceId; protected String tenantId; protected Boolean active; protected Boolean completed; protected Boolean terminated; protected Boolean closed; public String getId() { return id; } public String getBusinessKey() { return businessKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public Date getCreateTime() { return createTime; } public Date getCloseTime() { return closeTime; } public Long getDurationInMillis() { return durationInMillis; } public String getCreateUserId() { return createUserId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getTenantId() { return tenantId; } public Boolean getActive() { return active; } public Boolean getCompleted() { return completed;
} public Boolean getTerminated() { return terminated; } public Boolean getClosed() { return closed; } public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) { HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto(); dto.id = historicCaseInstance.getId(); dto.businessKey = historicCaseInstance.getBusinessKey(); dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId(); dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey(); dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName(); dto.createTime = historicCaseInstance.getCreateTime(); dto.closeTime = historicCaseInstance.getCloseTime(); dto.durationInMillis = historicCaseInstance.getDurationInMillis(); dto.createUserId = historicCaseInstance.getCreateUserId(); dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId(); dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId(); dto.tenantId = historicCaseInstance.getTenantId(); dto.active = historicCaseInstance.isActive(); dto.completed = historicCaseInstance.isCompleted(); dto.terminated = historicCaseInstance.isTerminated(); dto.closed = historicCaseInstance.isClosed(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseInstanceDto.java
1
请在Spring Boot框架中完成以下Java代码
public List<DeptVO> tree(String tenantId) { return ForestNodeMerger.merge(baseMapper.tree(tenantId)); } @Override public String getDeptIds(String tenantId, String deptNames) { List<Dept> deptList = baseMapper.selectList(Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId).in(Dept::getDeptName, Func.toStrList(deptNames))); if (deptList != null && deptList.size() > 0) { return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(",")); } return null; } @Override public List<String> getDeptNames(String deptIds) { return baseMapper.getDeptNames(Func.toLongArray(deptIds)); } @Override public boolean submit(Dept dept) { CacheUtil.clear(CacheUtil.SYS_CACHE);
if (Func.isEmpty(dept.getParentId())) { dept.setTenantId(SecureUtil.getTenantId()); dept.setParentId(BladeConstant.TOP_PARENT_ID); dept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID)); } if (dept.getParentId() > 0) { Dept parent = getById(dept.getParentId()); if (Func.toLong(dept.getParentId()) == Func.toLong(dept.getId())) { throw new ServiceException("父节点不可选择自身!"); } dept.setTenantId(parent.getTenantId()); String ancestors = parent.getAncestors() + StringPool.COMMA + dept.getParentId(); dept.setAncestors(ancestors); } dept.setIsDeleted(BladeConstant.DB_NOT_DELETED); return saveOrUpdate(dept); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\DeptServiceImpl.java
2
请完成以下Java代码
public class IdentificationSource3Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; }
/** * Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\IdentificationSource3Choice.java
1
请完成以下Java代码
/* package */final class NullParams implements IParams { public static final NullParams instance = new NullParams(); private NullParams() { } @Override public boolean hasParameter(final String parameterName) { return false; } @Override public Object getParameterAsObject(final String parameterName) { return null; } @Override public String getParameterAsString(final String parameterName) { return null; } @Override public int getParameterAsInt(final String parameterName, final int defaultValue) { return defaultValue; } @Override public <T extends RepoIdAware> T getParameterAsId(String parameterName, Class<T> type) { return null; } @Override public boolean getParameterAsBool(final String parameterName) { return false; } @Nullable @Override public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue) { return defaultValue; } @Override public Timestamp getParameterAsTimestamp(final String parameterName)
{ return null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { return null; } @Override public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { return null; } @Nullable @Override public Instant getParameterAsInstant(final String parameterName) { return null; } @Override public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice) { return null; } /** * Returns an empty list. */ @Override public Collection<String> getParameterNames() { return ImmutableList.of(); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java
1
请完成以下Java代码
public int getHR_ListBase_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListBase_ID); if (ii == null) return 0; return ii.intValue(); } public org.eevolution.model.I_HR_List getHR_List() throws RuntimeException { return (org.eevolution.model.I_HR_List)MTable.get(getCtx(), org.eevolution.model.I_HR_List.Table_Name) .getPO(getHR_List_ID(), get_TrxName()); } /** Set Payroll List. @param HR_List_ID Payroll List */ public void setHR_List_ID (int HR_List_ID) { if (HR_List_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_List_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_List_ID, Integer.valueOf(HR_List_ID)); } /** Get Payroll List. @return Payroll List */ public int getHR_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_List_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Payroll List Version. @param HR_ListVersion_ID Payroll List Version */ public void setHR_ListVersion_ID (int HR_ListVersion_ID) { if (HR_ListVersion_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID)); } /** Get Payroll List Version. @return Payroll List Version */ public int getHR_ListVersion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name);
} /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListVersion.java
1
请在Spring Boot框架中完成以下Java代码
public R<IPage<PostVO>> list(Post post, Query query) { IPage<Post> pages = postService.page(Condition.getPage(query), Condition.getQueryWrapper(post)); return R.data(PostWrapper.build().pageVO(pages)); } /** * 自定义分页 岗位表 */ @GetMapping("/page") @ApiOperationSupport(order = 3) @Operation(summary = "分页", description = "传入post") public R<IPage<PostVO>> page(PostVO post, Query query) { IPage<PostVO> pages = postService.selectPostPage(Condition.getPage(query), post); return R.data(pages); } /** * 新增 岗位表 */ @PostMapping("/save") @ApiOperationSupport(order = 4) @Operation(summary = "新增", description = "传入post") public R save(@Valid @RequestBody Post post) { return R.status(postService.save(post)); } /** * 修改 岗位表 */ @PostMapping("/update") @ApiOperationSupport(order = 5) @Operation(summary = "修改", description = "传入post") public R update(@Valid @RequestBody Post post) { return R.status(postService.updateById(post)); }
/** * 新增或修改 岗位表 */ @PostMapping("/submit") @ApiOperationSupport(order = 6) @Operation(summary = "新增或修改", description = "传入post") public R submit(@Valid @RequestBody Post post) { post.setTenantId(SecureUtil.getTenantId()); return R.status(postService.saveOrUpdate(post)); } /** * 删除 岗位表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(postService.deleteLogic(Func.toLongList(ids))); } /** * 下拉数据源 */ @GetMapping("/select") @ApiOperationSupport(order = 8) @Operation(summary = "下拉数据源", description = "传入post") public R<List<Post>> select(String tenantId, BladeUser bladeUser) { List<Post> list = postService.list(Wrappers.<Post>query().lambda().eq(Post::getTenantId, Func.toStr(tenantId, bladeUser.getTenantId()))); return R.data(list); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\PostController.java
2
请完成以下Java代码
private String getNonceHash(String requestNonce) { try { return createHash(requestNonce); } catch (NoSuchAlgorithmException ex) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } } /** * Sets the {@link JwtDecoderFactory} used for {@link OidcIdToken} signature * verification. The factory returns a {@link JwtDecoder} associated to the provided * {@link ClientRegistration}. * @param jwtDecoderFactory the {@link JwtDecoderFactory} used for {@link OidcIdToken} * signature verification * @since 5.2 */ public final void setJwtDecoderFactory(JwtDecoderFactory<ClientRegistration> jwtDecoderFactory) { Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null"); this.jwtDecoderFactory = jwtDecoderFactory; } /** * Sets the {@link GrantedAuthoritiesMapper} used for mapping * {@link OidcUser#getAuthorities()}} to a new set of authorities which will be * associated to the {@link OAuth2LoginAuthenticationToken}. * @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the * user's authorities */ public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null"); this.authoritiesMapper = authoritiesMapper; } @Override public boolean supports(Class<?> authentication) { return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication); } private OidcIdToken createOidcToken(ClientRegistration clientRegistration, OAuth2AccessTokenResponse accessTokenResponse) { JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
Jwt jwt = getJwt(accessTokenResponse, jwtDecoder); OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims()); return idToken; } private Jwt getJwt(OAuth2AccessTokenResponse accessTokenResponse, JwtDecoder jwtDecoder) { try { Map<String, Object> parameters = accessTokenResponse.getAdditionalParameters(); return jwtDecoder.decode((String) parameters.get(OidcParameterNames.ID_TOKEN)); } catch (JwtException ex) { OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(), null); throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex); } } static String createHash(String nonce) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProvider.java
1
请完成以下Java代码
public class PMMPurchaseCandidateBL implements IPMMPurchaseCandidateBL { @Override public void setQtyPromised(final I_PMM_PurchaseCandidate candidate, final BigDecimal qtyPromised, final BigDecimal qtyPromisedTU) { candidate.setQtyPromised(qtyPromised); candidate.setQtyPromised_TU(qtyPromisedTU); } @Override public void addQtyOrderedAndResetQtyToOrder(final I_PMM_PurchaseCandidate candidate, final BigDecimal qtyOrdered, final BigDecimal qtyOrderedTU) { candidate.setQtyOrdered(candidate.getQtyOrdered().add(qtyOrdered)); candidate.setQtyOrdered_TU(candidate.getQtyOrdered_TU().add(qtyOrderedTU)); resetQtyToOrder(candidate); } @Override public void subtractQtyOrdered(final I_PMM_PurchaseCandidate candidate, final BigDecimal qtyOrdered, final BigDecimal qtyOrderedTU) { candidate.setQtyOrdered(candidate.getQtyOrdered().subtract(qtyOrdered)); candidate.setQtyOrdered_TU(candidate.getQtyOrdered_TU().subtract(qtyOrderedTU)); } @Override public void updateQtyToOrderFromQtyToOrderTU(final I_PMM_PurchaseCandidate candidate) { final I_M_HU_PI_Item_Product huPIItemProduct = getM_HU_PI_Item_Product_Effective(candidate); if (huPIItemProduct != null) { final BigDecimal qtyToOrderTU = candidate.getQtyToOrder_TU(); final BigDecimal tuCapacity = huPIItemProduct.getQty(); final BigDecimal qtyToOrder = qtyToOrderTU.multiply(tuCapacity); candidate.setQtyToOrder(qtyToOrder); } else { candidate.setQtyToOrder(candidate.getQtyToOrder_TU()); } } @Override public void resetQtyToOrder(I_PMM_PurchaseCandidate candidate) { candidate.setQtyToOrder(BigDecimal.ZERO); candidate.setQtyToOrder_TU(BigDecimal.ZERO); } @Override
public IPMMPricingAware asPMMPricingAware(final I_PMM_PurchaseCandidate candidate) { return PMMPricingAware_PurchaseCandidate.of(candidate); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product_Effective(final I_PMM_PurchaseCandidate candidate) { final I_M_HU_PI_Item_Product hupipOverride = candidate.getM_HU_PI_Item_Product_Override(); if (hupipOverride != null) { // return M_HU_PI_Item_Product_Override if set return hupipOverride; } // return M_HU_PI_Item_Product return candidate.getM_HU_PI_Item_Product(); } @Override public int getM_HU_PI_Item_Product_Effective_ID(final I_PMM_PurchaseCandidate candidate) { final int hupipOverrideID = candidate.getM_HU_PI_Item_Product_Override_ID(); if (hupipOverrideID > 0) { // return M_HU_PI_Item_Product_Override if set return hupipOverrideID; } // return M_HU_PI_Item_Product return candidate.getM_HU_PI_Item_Product_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPurchaseCandidateBL.java
1
请完成以下Java代码
public void fireBeforePost(final Object document) { for (final IFactAcctListener listener : listeners) { listener.onBeforePost(document); } } @Override public void fireAfterPost(final Object document) { for (final IFactAcctListener listener : listeners) { listener.onAfterPost(document); } } // @Override // public void fireAfterUnpost(final Object document) // { // for (final IFactAcctListener listener : listeners) // { // listener.onAfterUnpost(document); // } // } /** * Listens Fact_Acct events and forward them to {@link ModelValidationEngine}. */ private static final class FactAcctListener2ModelValidationEngineAdapter implements IFactAcctListener { public static final transient FactAcctListener2ModelValidationEngineAdapter instance = new FactAcctListener2ModelValidationEngineAdapter(); private FactAcctListener2ModelValidationEngineAdapter() { } private final void fireDocValidate(final Object document, final int timing) { final Object model; if (document instanceof IDocument) { model = ((IDocument)document).getDocumentModel(); } else {
model = document; } ModelValidationEngine.get().fireDocValidate(model, timing); } @Override public void onBeforePost(final Object document) { fireDocValidate(document, ModelValidator.TIMING_BEFORE_POST); } @Override public void onAfterPost(final Object document) { fireDocValidate(document, ModelValidator.TIMING_AFTER_POST); } // @Override // public void onAfterUnpost(final Object document) // { // fireDocValidate(document, ModelValidator.TIMING_AFTER_UNPOST); // } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\FactAcctListenersService.java
1
请在Spring Boot框架中完成以下Java代码
private Instant getNewDatePromisedForQty( @NonNull final BigDecimal recomputedQtyBasedOnDemand, @NonNull final PPOrderCandidateAdvisedEvent ppOrderCandidateAdvisedEvent) { final ProductPlanningId productPlanningId = ProductPlanningId.ofRepoIdOrNull(ppOrderCandidateAdvisedEvent.getPpOrderCandidate().getPpOrderData().getProductPlanningId()); Check.assumeNotNull(productPlanningId, "There should be a ProductPlanningId on event at this stage!"); final ProductPlanning productPlanningRecord = productPlanningDAO.getById(productPlanningId); final int durationDays = productPlanningService.calculateDurationDays(productPlanningRecord, recomputedQtyBasedOnDemand); return ppOrderCandidateAdvisedEvent.getPpOrderCandidate().getPpOrderData().getDateStartSchedule().plus(durationDays, ChronoUnit.DAYS); } private boolean validateThereWillBeEnoughStockAtGivenDate( @NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor, @NonNull final BigDecimal requiredQtyInStock, @NonNull final Instant givenTime) { final Optional<Candidate> latestStockAtGivenTime = getLatestStockAtGivenTime(supplyRequiredDescriptor, givenTime, DateAndSeqNo.Operator.INCLUSIVE); return latestStockAtGivenTime .map(Candidate::getQuantity) .map(availableStock -> availableStock.compareTo(requiredQtyInStock) >= 0) .orElse(false); } private boolean isStockForSupplyCandidate(@NonNull final Candidate stock, @NonNull final Candidate supplyCandidate) { Check.assume(CandidateId.isRegularNonNull(supplyCandidate.getParentId()), "Supply Candidates have the stock candidate as parent!"); return stock.getId().equals(supplyCandidate.getParentId()); } @NonNull private Candidate getUnspecifiedSupplyCandidate(@NonNull final CandidateId supplyCandidateId) { return candidateRepositoryRetrieval.retrieveLatestMatch(CandidatesQuery.fromId(supplyCandidateId)) .orElseThrow(() -> new AdempiereException("Missing Candidate for Id:" + supplyCandidateId)); } @NonNull private static PPOrderCandidateAdvisedEvent buildWithPPOrderData(@NonNull final PPOrderCandidateAdvisedEvent event, @NonNull final PPOrderData ppOrderData)
{ return event.toBuilder() .ppOrderCandidate(event.getPpOrderCandidate().withPpOrderData(ppOrderData)) .build(); } @Value @Builder private static class ProductionTimingResult { @NonNull Instant datePromised; @NonNull BigDecimal qtyRequired; @NonNull Instant missingQtySolvedTime; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ppordercandidate\PPOrderCandidateAdvisedHandler.java
2
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getEventDefinitionKey() { return eventDefinitionKey; }
public String getEventDefinitionKeyLike() { return eventDefinitionKeyLike; } public String getParentDeploymentId() { return parentDeploymentId; } public String getParentDeploymentIdLike() { return parentDeploymentIdLike; } public String getChannelDefinitionKey() { return channelDefinitionKey; } public String getChannelDefinitionKeyLike() { return channelDefinitionKeyLike; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDeploymentQueryImpl.java
1
请完成以下Java代码
public void setDATEV_ExportFormat_ID (int DATEV_ExportFormat_ID) { if (DATEV_ExportFormat_ID < 1) set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, null); else set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, Integer.valueOf(DATEV_ExportFormat_ID)); } /** Get DATEV Export Format. @return DATEV Export Format */ @Override public int getDATEV_ExportFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DATEV_ExportFormat_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Decimal Separator. @param DecimalSeparator Decimal Separator */ @Override public void setDecimalSeparator (java.lang.String DecimalSeparator) { set_Value (COLUMNNAME_DecimalSeparator, DecimalSeparator); } /** Get Decimal Separator. @return Decimal Separator */ @Override public java.lang.String getDecimalSeparator () { return (java.lang.String)get_Value(COLUMNNAME_DecimalSeparator); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung.
@return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Number Grouping Separator. @param NumberGroupingSeparator Number Grouping Separator */ @Override public void setNumberGroupingSeparator (java.lang.String NumberGroupingSeparator) { set_Value (COLUMNNAME_NumberGroupingSeparator, NumberGroupingSeparator); } /** Get Number Grouping Separator. @return Number Grouping Separator */ @Override public java.lang.String getNumberGroupingSeparator () { return (java.lang.String)get_Value(COLUMNNAME_NumberGroupingSeparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormat.java
1
请完成以下Java代码
public Optional<MetasfreshId> resolveExternalReference( @Nullable final OrgId orgId, @NonNull final ExternalIdentifier externalIdentifier, @NonNull final IExternalReferenceType externalReferenceType) { final Optional<JsonMetasfreshId> jsonMetasfreshId = getJsonMetasfreshIdFromExternalReference(orgId, externalIdentifier, externalReferenceType); return jsonMetasfreshId.map(metasfreshId -> MetasfreshId.of(metasfreshId.getValue())); } @NonNull private ExternalReference mapJsonToExternalReference(@NonNull final JsonRequestExternalReferenceUpsert request, @NonNull final OrgId orgId) { Check.assumeNotNull(request.getExternalReferenceItem().getMetasfreshId(), "MetasfreshId cannot be null at this stage!"); final IExternalReferenceType externalReferenceType = externalReferenceTypes.ofCode(request.getExternalReferenceItem().getLookupItem().getType()) .orElseThrow(() -> new InvalidIdentifierException("type", request.getExternalReferenceItem().getLookupItem().getType())); final ExternalSystem externalSystem = externalSystemRepository.getOptionalByType(ExternalSystemType.ofValue(request.getSystemName().getName())) .orElseThrow(() -> new InvalidIdentifierException("externalSystem", request.getSystemName().getName())); return ExternalReference.builder() .orgId(orgId) .externalSystem(externalSystem) .externalReferenceType(externalReferenceType) .externalReference(request.getExternalReferenceItem().getLookupItem().getId()) .recordId(request.getExternalReferenceItem().getMetasfreshId().getValue()) .version(request.getExternalReferenceItem().getVersion()) .externalReferenceUrl(request.getExternalReferenceItem().getExternalReferenceUrl()) .build(); }
@NonNull private ExternalReference syncCandidateWithExisting( @NonNull final ExternalReference candidate, @NonNull final ExternalReference existingReference) { return ExternalReference.builder() //existing .externalReferenceId(existingReference.getExternalReferenceId()) //candidate .orgId(candidate.getOrgId()) .externalSystem(candidate.getExternalSystem()) .externalReferenceType(candidate.getExternalReferenceType()) .externalReference(candidate.getExternalReference()) .recordId(candidate.getRecordId()) .version(candidate.getVersion()) .externalReferenceUrl(candidate.getExternalReferenceUrl()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v1\ExternalReferenceRestControllerService.java
1
请完成以下Java代码
public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } @Override protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed) { // Forward all key events on this component to the text field. // We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component. // Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here. if (m_text != null && condition == WHEN_FOCUSED) { // Usually the text component does not have focus yet but it was requested, so, considering that: // * we are requesting the focus just to make sure // * we select all text (once) => as an effect, on first key pressed the editor content (which is selected) will be deleted and replaced with the new typing // * make sure that in the focus event which will come, the text is not selected again, else, if user is typing fast, the editor content will be only what he typed last. if(!m_text.hasFocus()) {
skipNextSelectAllOnFocusGained = true; m_text.requestFocus(); if (m_text.getDocument().getLength() > 0) { m_text.selectAll(); } } if (m_text.processKeyBinding(ks, e, condition, pressed)) { return true; } } // // Fallback to super return super.processKeyBinding(ks, e, condition, pressed); } } // VNumber
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VNumber.java
1
请完成以下Java代码
public void setIgnoredInstancesMetadata(Map<String, String> ignoredInstancesMetadata) { this.ignoredInstancesMetadata = ignoredInstancesMetadata; } private boolean isInstanceAllowedBasedOnMetadata(ServiceInstance instance) { if (instancesMetadata.isEmpty()) { return true; } for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) { if (isMapContainsEntry(instancesMetadata, metadata)) { return true; } } return false; } private boolean isInstanceIgnoredBasedOnMetadata(ServiceInstance instance) {
if (ignoredInstancesMetadata.isEmpty()) { return false; } for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) { if (isMapContainsEntry(ignoredInstancesMetadata, metadata)) { return true; } } return false; } private boolean isMapContainsEntry(Map<String, String> map, Map.Entry<String, String> entry) { String value = map.get(entry.getKey()); return value != null && value.equals(entry.getValue()); } }
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\InstanceDiscoveryListener.java
1
请在Spring Boot框架中完成以下Java代码
public String query(String outTradeNo, String tradeNo) { AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); //******必传参数****** JSONObject bizContent = new JSONObject(); //设置查询参数,out_trade_no和trade_no至少传一个 if(StrUtil.isNotEmpty(outTradeNo)){ bizContent.put("out_trade_no",outTradeNo); } if(StrUtil.isNotEmpty(tradeNo)){ bizContent.put("trade_no",tradeNo); } //交易结算信息: trade_settle_info String[] queryOptions = {"trade_settle_info"}; bizContent.put("query_options", queryOptions); request.setBizContent(bizContent.toString()); AlipayTradeQueryResponse response = null; try { response = alipayClient.execute(request); } catch (AlipayApiException e) { log.error("查询支付宝账单异常!",e); } if(response.isSuccess()){ log.info("查询支付宝账单成功!"); if("TRADE_SUCCESS".equals(response.getTradeStatus())){ portalOrderService.paySuccessByOrderSn(outTradeNo,1); } } else { log.error("查询支付宝账单失败!"); } //交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款) return response.getTradeStatus(); } @Override public String webPay(AliPayParam aliPayParam) { AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest ();
if(StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())){ //异步接收地址,公网可访问 request.setNotifyUrl(alipayConfig.getNotifyUrl()); } if(StrUtil.isNotEmpty(alipayConfig.getReturnUrl())){ //同步跳转地址 request.setReturnUrl(alipayConfig.getReturnUrl()); } //******必传参数****** JSONObject bizContent = new JSONObject(); //商户订单号,商家自定义,保持唯一性 bizContent.put("out_trade_no", aliPayParam.getOutTradeNo()); //支付金额,最小值0.01元 bizContent.put("total_amount", aliPayParam.getTotalAmount()); //订单标题,不可使用特殊符号 bizContent.put("subject", aliPayParam.getSubject()); //手机网站支付默认传值FAST_INSTANT_TRADE_PAY bizContent.put("product_code", "QUICK_WAP_WAY"); request.setBizContent(bizContent.toString()); String formHtml = null; try { formHtml = alipayClient.pageExecute(request).getBody(); } catch (AlipayApiException e) { e.printStackTrace(); } return formHtml; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\AlipayServiceImpl.java
2
请完成以下Java代码
private static byte[] getDoFinalData(byte[] data, Cipher cipher, int maxBlock) throws BadPaddingException, IllegalBlockSizeException, IOException { int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; for (int i = 0; inputLen - offSet > 0; offSet = i * maxBlock) { byte[] cache; if (inputLen - offSet > maxBlock) { cache = cipher.doFinal(data, offSet, maxBlock); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); ++i; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } public static void main(String args[]) throws UnsupportedEncodingException, NoSuchFieldException, NoSuchFileException { String testPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCE7vuntatVmQVp6xGlBa/U/cEkKtFjyhsTtn1inlYtw5KSasTfa/HMPwJKp1QchsGEt0usOkHHC9HuD8o1gKx/Dgjo6b/XGu6xhinyRjCJWLSHXGOq9VLryaThwZsRB4Bb5DU9NXkl8WE2ih8QEKO1143KeJ5SE38awi74im0dzQIDAQAB"; String testPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAITu+6e1q1WZBWnrEaUFr9T9wSQq0WPKGxO2fWKeVi3DkpJqxN9r8cw/AkqnVByGwYS3S6w6QccL0e4PyjWArH8OCOjpv9ca7rGGKfJGMIlYtIdcY6r1UuvJpOHBmxEHgFvkNT01eSXxYTaKHxAQo7XXjcp4nlITfxrCLviKbR3NAgMBAAECgYAHUgXHuYhi4Vdb+tbw6HxDVWoCbN01CpctIbqL6L5ELOXwbDLFPvOE1N9ybv6Bx6X2ggWHyXl/1ZXM70+qXJijHZNcDWPocbJDrOOHwePyNreSU0UGNRcBJ7RVnH2YDWut9GZFv88lUp6/xNUJ8QG7a4kOcLsb5L1YrkV+aEeiXQJBAO0rkR0a/ZHUcKgIzF+OaGnwMqiZHIPIZe7xkTTaEk5Qw6HWNOWR6jbwF9bomVBSAM78IFRrD8yUAR6CsAbhUWsCQQCPfNQX1ikUlDutvPGXxqbzUmiBDH2x7xbvPIySfCaWTjYm+YQDzHtfW5lx96HyWcNp/4ryFP8vNZ8p8DCN5kOnAkBqxIUkRCVIxAkfLC7NCa/pmQ9FJQBYNxvkUG1dDJrXFLatIWBYxLJanwUsYzO5m+DvTUNEnZnUMAC8+npB7qcXAkAmfoiv9GaE/Ned3qi53TOA58TdiipWiBwRBp931RLNFCJ3Bk2ib0NR69MYviSWTfqc/0+ZboSfd7VBnQyJpRLVAkB1sskxSIKMt3vGws0vyfY1B2GwosRtRRl+h9uQxcvM6is39OpKFwAmurL9n0SjtvSdIT/XltoP69hcgz83hem0"; String data = "hello,中国"; String enData = RSAUtil.encryptByPublicKey(data, testPublicKey); String sign = RSAUtil.sign(data, testPrivateKey);
boolean verify = RSAUtil.verify(data, sign, testPublicKey); String deData = RSAUtil.decryptByPrivateKey(enData, testPrivateKey); System.out.println(String.format("data:%s", data)); System.out.println(String.format("enData:%s", enData)); System.out.println(String.format("sign:%s", sign)); System.out.println(String.format("verify:%s", verify)); System.out.println(String.format("deData:%s", deData)); } }
repos\spring-boot-student-master\spring-boot-student-jvm\src\main\java\com\xiaolyuh\utils\RSAUtil.java
1
请完成以下Java代码
public void setExecutionDate(String executionDate) { this.executionDate = executionDate; } public void setIncludeJobs(boolean includeJobs) { this.includeJobs = includeJobs; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public void setProcessDefinitionTenantId(String processDefinitionTenantId) { this.processDefinitionTenantId = processDefinitionTenantId; } public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) { this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId; } @Override public void updateSuspensionState(ProcessEngine engine) { int params = (jobDefinitionId != null ? 1 : 0) + (processDefinitionId != null ? 1 : 0) + (processDefinitionKey != null ? 1 : 0); if (params > 1) { String message = "Only one of jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } else if (params == 0) { String message = "Either jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } UpdateJobDefinitionSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine); if (executionDate != null && !executionDate.equals("")) { Date delayedExecutionDate = DateTimeUtil.parseDate(executionDate);
updateSuspensionStateBuilder.executionDate(delayedExecutionDate); } updateSuspensionStateBuilder.includeJobs(includeJobs); if (getSuspended()) { updateSuspensionStateBuilder.suspend(); } else { updateSuspensionStateBuilder.activate(); } } protected UpdateJobDefinitionSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { UpdateJobDefinitionSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobDefinitionSuspensionState(); if (jobDefinitionId != null) { return selectBuilder.byJobDefinitionId(jobDefinitionId); } else if (processDefinitionId != null) { return selectBuilder.byProcessDefinitionId(processDefinitionId); } else { UpdateJobDefinitionSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); if (processDefinitionTenantId != null) { tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); } else if (processDefinitionWithoutTenantId) { tenantBuilder.processDefinitionWithoutTenantId(); } return tenantBuilder; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionSuspensionStateDto.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "title") private String title; @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) @JoinTable(name = "post_category", joinColumns = @JoinColumn(name = "post_id"), inverseJoinColumns = @JoinColumn(name = "category_id") ) private Set<Category> categories = new HashSet<>(); // getters and setters public Post(String title) { this.title = title; } public Post() { }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Set<Category> getCategories() { return categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } }
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\manytomanyremoval\Post.java
2
请在Spring Boot框架中完成以下Java代码
private static class BasePaymentTermIdAndDiscount { @NonNull PaymentTermId basePaymentTermId; @NonNull Percent discount; } private PaymentTermId getOrCreateDerivedPaymentTerm0(@NonNull BasePaymentTermIdAndDiscount basePaymentTermIdAndDiscount) { final PaymentTermId basePaymentTermId = basePaymentTermIdAndDiscount.getBasePaymentTermId(); final Percent discount = basePaymentTermIdAndDiscount.getDiscount(); final I_C_PaymentTerm basePaymentTermRecord = newLoaderAndSaver().getRecordById(basePaymentTermId); // see if the designed payment term already exists final I_C_PaymentTerm existingDerivedPaymentTermRecord = queryBL.createQueryBuilderOutOfTrx(I_C_PaymentTerm.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsValid, true) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_Discount, discount.toBigDecimal()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AD_Client_ID, basePaymentTermRecord.getAD_Client_ID()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AD_Org_ID, basePaymentTermRecord.getAD_Org_ID()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_Discount2, basePaymentTermRecord.getDiscount2()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_DiscountDays2, basePaymentTermRecord.getDiscountDays2()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_AfterDelivery, basePaymentTermRecord.isAfterDelivery()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthCutoff, basePaymentTermRecord.getFixMonthCutoff()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthDay, basePaymentTermRecord.getFixMonthDay()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_FixMonthOffset, basePaymentTermRecord.getFixMonthOffset()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_GraceDays, basePaymentTermRecord.getGraceDays()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsDueFixed, basePaymentTermRecord.isDueFixed()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_IsNextBusinessDay, basePaymentTermRecord.isNextBusinessDay())
.addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_NetDay, basePaymentTermRecord.getNetDay()) .addEqualsFilter(I_C_PaymentTerm.COLUMNNAME_NetDays, basePaymentTermRecord.getNetDays()) .orderBy(I_C_PaymentTerm.COLUMNNAME_C_PaymentTerm_ID) .create() .first(); if (existingDerivedPaymentTermRecord != null) { return PaymentTermId.ofRepoId(existingDerivedPaymentTermRecord.getC_PaymentTerm_ID()); } final I_C_PaymentTerm newPaymentTerm = newInstance(I_C_PaymentTerm.class); InterfaceWrapperHelper.copyValues(basePaymentTermRecord, newPaymentTerm); newPaymentTerm.setDiscount(discount.toBigDecimal()); final String newName = basePaymentTermRecord.getName() + " (=>" + discount.toBigDecimal() + " %)"; newPaymentTerm.setName(newName); saveRecord(newPaymentTerm); return PaymentTermId.ofRepoId(newPaymentTerm.getC_PaymentTerm_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermRepository.java
2
请完成以下Java代码
public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Gang. @param X X-Dimension, z.B. Gang */ @Override public void setX (java.lang.String X) { set_Value (COLUMNNAME_X, X); } /** Get Gang. @return X-Dimension, z.B. Gang */ @Override public java.lang.String getX () { return (java.lang.String)get_Value(COLUMNNAME_X); } /** Set Regal. @param X1 Regal */ @Override public void setX1 (java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } /** Get Regal. @return Regal */ @Override public java.lang.String getX1 () { return (java.lang.String)get_Value(COLUMNNAME_X1); } /** Set Fach. @param Y Y-Dimension, z.B. Fach */ @Override public void setY (java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); }
/** Get Fach. @return Y-Dimension, z.B. Fach */ @Override public java.lang.String getY () { return (java.lang.String)get_Value(COLUMNNAME_Y); } /** Set Ebene. @param Z Z-Dimension, z.B. Ebene */ @Override public void setZ (java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } /** Get Ebene. @return Z-Dimension, z.B. Ebene */ @Override public java.lang.String getZ () { return (java.lang.String)get_Value(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java
1
请完成以下Java代码
public String getWStoreEMail () { return (String)get_Value(COLUMNNAME_WStoreEMail); } /** Set Web Store. @param W_Store_ID A Web Store of the Client */ public void setW_Store_ID (int W_Store_ID) { if (W_Store_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Store_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID)); } /** Get Web Store. @return A Web Store of the Client */ public int getW_Store_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID); if (ii == null) return 0; return ii.intValue(); } /** Set WebStore User. @param WStoreUser User ID of the Web Store EMail address */ public void setWStoreUser (String WStoreUser) { set_Value (COLUMNNAME_WStoreUser, WStoreUser); }
/** Get WebStore User. @return User ID of the Web Store EMail address */ public String getWStoreUser () { return (String)get_Value(COLUMNNAME_WStoreUser); } /** Set WebStore Password. @param WStoreUserPW Password of the Web Store EMail address */ public void setWStoreUserPW (String WStoreUserPW) { set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW); } /** Get WebStore Password. @return Password of the Web Store EMail address */ public String getWStoreUserPW () { return (String)get_Value(COLUMNNAME_WStoreUserPW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java
1
请完成以下Java代码
abstract class PaymentsViewBasedProcess extends ViewBasedProcessTemplate { private transient ImmutableList<PaymentRow> _paymentRowsSelectedForAllocation; private transient ImmutableList<InvoiceRow> _invoiceRowsSelectedForAllocation; @Override protected final PaymentsView getView() { return PaymentsView.cast(super.getView()); } protected final PaymentsView getPaymentsView() { return getView(); } protected final DocumentIdsSelection getSelectedPaymentRowIdsIncludingDefaultRow() { return getSelectedRowIds(); } protected final InvoicesView getInvoicesView() { return getPaymentsView().getInvoicesView(); } private DocumentIdsSelection getSelectedInvoiceRowIds() { return getChildViewSelectedRowIds(); } // // // protected final ImmutableList<PaymentRow> getPaymentRowsSelectedForAllocation() { ImmutableList<PaymentRow> paymentRowsSelectedForAllocation = this._paymentRowsSelectedForAllocation; if (paymentRowsSelectedForAllocation == null) { paymentRowsSelectedForAllocation = this._paymentRowsSelectedForAllocation = computePaymentRowsSelectedForAllocation(); } return paymentRowsSelectedForAllocation; } private ImmutableList<PaymentRow> computePaymentRowsSelectedForAllocation() { final DocumentIdsSelection selectedPaymentRowIds = getSelectedPaymentRowIdsIncludingDefaultRow(); return getPaymentsView().streamByIds(selectedPaymentRowIds) .filter(row -> !row.equals(PaymentRow.DEFAULT_PAYMENT_ROW)) .collect(ImmutableList.toImmutableList()); } protected final ImmutableList<InvoiceRow> getInvoiceRowsSelectedForAllocation() { ImmutableList<InvoiceRow> invoiceRowsSelectedForAllocation = this._invoiceRowsSelectedForAllocation;
if (invoiceRowsSelectedForAllocation == null) { invoiceRowsSelectedForAllocation = this._invoiceRowsSelectedForAllocation = computeInvoiceRowsSelectedForAllocation(); } return invoiceRowsSelectedForAllocation; } private ImmutableList<InvoiceRow> computeInvoiceRowsSelectedForAllocation() { final InvoicesView invoicesView = getInvoicesView(); if (InvoicesViewFactory.isEnablePreparedForAllocationFlag()) { return invoicesView .streamByIds(DocumentIdsSelection.ALL) .filter(InvoiceRow::isPreparedForAllocation) .collect(ImmutableList.toImmutableList()); } else { return invoicesView .streamByIds(getSelectedInvoiceRowIds()) .collect(ImmutableList.toImmutableList()); } } protected final void invalidatePaymentsAndInvoicesViews() { final InvoicesView invoicesView = getInvoicesView(); invoicesView.unmarkPreparedForAllocation(DocumentIdsSelection.ALL); invalidateView(invoicesView); invalidateView(getPaymentsView()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsViewBasedProcess.java
1
请完成以下Java代码
public int getLoginTimeout() throws SQLException { return 0; // Default } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName()); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } public Map<Object, DataSource> getDataSources() { return dataSources; }
public void setDataSources(Map<Object, DataSource> dataSources) { this.dataSources = dataSources; } // Unsupported ////////////////////////////////////////////////////////// public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } public void setLogWriter(PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } public void setLoginTimeout(int seconds) throws SQLException { throw new UnsupportedOperationException(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\multitenant\TenantAwareDataSource.java
1