instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void updateSuspensionState(SuspensionStateDto dto) { dto.updateSuspensionState(engine, processInstanceId); } @Override public void modifyProcessInstance(ProcessInstanceModificationDto dto) { if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) { ProcessInstanceModificationBuilder modificationBuilder = engine.getRuntimeService().createProcessInstanceModification(processInstanceId); dto.applyTo(modificationBuilder, engine, objectMapper); if (dto.getAnnotation() != null) { modificationBuilder.setAnnotation(dto.getAnnotation()); } modificationBuilder.cancellationSourceExternal(true); modificationBuilder.execute(dto.isSkipCustomListeners(), dto.isSkipIoMappings()); } } @Override public BatchDto modifyProcessInstanceAsync(ProcessInstanceModificationDto dto) { Batch batch = null; if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) { ProcessInstanceModificationBuilder modificationBuilder = engine.getRuntimeService().createProcessInstanceModification(processInstanceId);
dto.applyTo(modificationBuilder, engine, objectMapper); if (dto.getAnnotation() != null) { modificationBuilder.setAnnotation(dto.getAnnotation()); } modificationBuilder.cancellationSourceExternal(true); try { batch = modificationBuilder.executeAsync(dto.isSkipCustomListeners(), dto.isSkipIoMappings()); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } return BatchDto.fromBatch(batch); } throw new InvalidRequestException(Status.BAD_REQUEST, "The provided instuctions are invalid."); } @Override public ProcessInstanceCommentResource getProcessInstanceCommentResource() { return new ProcessInstanceCommentResourceImpl(engine, processInstanceId); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ProcessInstanceResourceImpl.java
1
请完成以下Java代码
public AssignableInvoiceCandidate ofRecord(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return assignableInvoiceCandidateFactory.ofRecord(invoiceCandidateRecord); } public Iterator<AssignableInvoiceCandidate> getAllAssigned( @NonNull final RefundInvoiceCandidate refundInvoiceCandidate) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Candidate_Assignment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, refundInvoiceCandidate.getId().getRepoId()) .andCollect( I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Assigned_ID, I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(assignableInvoiceCandidateFactory::ofRecord) .iterator();
} /** * In production, assignable invoice candidates are created elsewhere and are only loaded if they are relevant for refund contracts. * That's why this method is intended only for (unit-)testing. */ @VisibleForTesting public AssignableInvoiceCandidate saveNew(@NonNull final AssignableInvoiceCandidate assignableCandidate) { final I_C_Invoice_Candidate assignableCandidateRecord = newInstance(I_C_Invoice_Candidate.class); saveRecord(assignableCandidateRecord); return assignableCandidate .toBuilder() .id(InvoiceCandidateId.ofRepoId(assignableCandidateRecord.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidateRepository.java
1
请完成以下Java代码
public List<U> listPage(int firstResult, int maxResults) { this.firstResult = firstResult; this.maxResults = maxResults; if (this.maxResults >= 0) { if (this.firstResult < 0) { this.firstResult = 0; } } else { if (this.firstResult >= 0) { this.maxResults = Integer.MAX_VALUE; } } this.resultType = ResultType.LIST_PAGE; if (commandExecutor != null) { return (List<U>) commandExecutor.execute(this); } // The execute has a checkQueryOk() call as well, so no need to do the call earlier checkQueryOk(); return executeList(Context.getCommandContext()); } @Override public long count() { this.resultType = ResultType.COUNT; if (commandExecutor != null) { return (Long) commandExecutor.execute(this); } // The execute has a checkQueryOk() call as well, so no need to do the call earlier checkQueryOk(); return executeCount(Context.getCommandContext()); } @Override public Object execute(CommandContext commandContext) { checkQueryOk(); if (resultType == ResultType.LIST) { return executeList(commandContext); } else if (resultType == ResultType.SINGLE_RESULT) { return executeSingleResult(commandContext); } else if (resultType == ResultType.LIST_PAGE) {
return executeList(commandContext); } else { return executeCount(commandContext); } } public abstract long executeCount(CommandContext commandContext); /** * Executes the actual query to retrieve the list of results. */ public abstract List<U> executeList(CommandContext commandContext); public U executeSingleResult(CommandContext commandContext) { List<U> results = executeList(commandContext); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new FlowableException("Query return " + results.size() + " results instead of max 1"); } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\AbstractQuery.java
1
请完成以下Java代码
public String listUploadedFiles(Model model) throws IOException { model.addAttribute("files", storageService .loadAll() .map(path -> MvcUriComponentsBuilder .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString()) .build().toString()) .collect(Collectors.toList())); return "uploadForm"; } @GetMapping("/files/{filename:.+}") @ResponseBody public ResponseEntity<Resource> serveFile(@PathVariable String filename) { Resource file = storageService.loadAsResource(filename); return ResponseEntity .ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"") .body(file);
} @PostMapping("/") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { storageService.store(file); redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!"); return "redirect:/"; } @ExceptionHandler(StorageFileNotFoundException.class) public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) { return ResponseEntity.notFound().build(); } }
repos\SpringBootLearning-master\springboot-upload-file\src\main\java\com\forezp\web\FileUploadController.java
1
请完成以下Java代码
public String getType() { return TYPE; } @Override protected void postExecute(CommandContext commandContext) { LOG.debugJobExecuted(this); init(commandContext); commandContext.getHistoricJobLogManager().fireJobSuccessfulEvent(this); } @Override public void init(CommandContext commandContext) { init(commandContext, false, true); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", duedate=" + duedate
+ ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EverLivingJobEntity.java
1
请完成以下Java代码
protected String getObjectTypeName(ObjectValue value) { String objectTypeName = value.getObjectTypeName(); if (objectTypeName == null && !value.isDeserialized() && value.getValueSerialized() != null) { throw LOG.valueMapperExceptionDueToNoObjectTypeName(); } // update type name if the object is deserialized if (value.isDeserialized() && value.getValue() != null) { objectTypeName = dataFormat.getCanonicalTypeName(value.getValue()); } return objectTypeName; } @Override protected boolean canWriteValue(TypedValue typedValue) { if (!(typedValue instanceof SerializableValue) && !(typedValue instanceof UntypedValueImpl)) { return false; } if (typedValue instanceof SerializableValue) { SerializableValue serializableValue = (SerializableValue) typedValue; String requestedDataFormat = serializableValue.getSerializationDataFormat(); if (!serializableValue.isDeserialized()) { // serialized object => dataformat must match return serializationDataFormat.equals(requestedDataFormat); } else { final boolean canSerialize = typedValue.getValue() == null || dataFormat.canMap(typedValue.getValue()); return canSerialize && (requestedDataFormat == null || serializationDataFormat.equals(requestedDataFormat)); } } else {
return typedValue.getValue() == null || dataFormat.canMap(typedValue.getValue()); } } @Override protected boolean canReadValue(TypedValueField typedValueField) { Map<String, Object> valueInfo = typedValueField.getValueInfo(); String serializationDataformat = (String) valueInfo.get(VALUE_INFO_SERIALIZATION_DATA_FORMAT); Object value = typedValueField.getValue(); return (value == null || value instanceof String) && getSerializationDataformat().equals(serializationDataformat); } protected ObjectValue createDeserializedValue(Object deserializedObject, String serializedValue, TypedValueField typedValueField) { String objectTypeName = readObjectNameFromFields(typedValueField); return new ObjectValueImpl(deserializedObject, serializedValue, serializationDataFormat, objectTypeName, true); } protected ObjectValue createSerializedValue(String serializedValue, TypedValueField typedValueField) { String objectTypeName = readObjectNameFromFields(typedValueField); return new ObjectValueImpl(null, serializedValue, serializationDataFormat, objectTypeName, false); } protected String readObjectNameFromFields(TypedValueField typedValueField) { Map<String, Object> valueInfo = typedValueField.getValueInfo(); return (String) valueInfo.get(VALUE_INFO_OBJECT_TYPE_NAME); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\ObjectValueMapper.java
1
请完成以下Java代码
public Set<Window> updateUI() { final Set<Window> updated = new HashSet<>(); for (final Container c : windowsByWindowNo.values()) { final Window w = SwingUtils.getFrame(c); if (w == null) { continue; } if (updated.contains(w)) { continue; } SwingUtilities.updateComponentTreeUI(w); w.validate(); final RepaintManager mgr = RepaintManager.currentManager(w); final Component childs[] = w.getComponents(); for (final Component child : childs) { if (child instanceof JComponent) { mgr.markCompletelyDirty((JComponent)child); } } w.repaint(); updated.add(w); } for (final Window w : hiddenWindows) { if (updated.contains(w)) { continue; }
SwingUtilities.updateComponentTreeUI(w); w.validate(); final RepaintManager mgr = RepaintManager.currentManager(w); final Component childs[] = w.getComponents(); for (final Component child : childs) { if (child instanceof JComponent) { mgr.markCompletelyDirty((JComponent)child); } } w.repaint(); updated.add(w); } return updated; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WindowsIndex.java
1
请完成以下Java代码
public MapSession findById(String id) { Session saved = this.sessions.get(id); if (saved == null) { return null; } if (saved.isExpired()) { deleteById(saved.getId()); return null; } MapSession result = new MapSession(saved); result.setSessionIdGenerator(this.sessionIdGenerator); return result; } @Override public void deleteById(String id) { this.sessions.remove(id);
} @Override public MapSession createSession() { MapSession result = new MapSession(this.sessionIdGenerator); result.setMaxInactiveInterval(this.defaultMaxInactiveInterval); return result; } public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null"); this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSessionRepository.java
1
请完成以下Java代码
public static Optional<DefaultPackingItemCriteria> of(final I_C_Order order, final ProductId productId) { final BPartnerLocationAndCaptureId bpartnerLocationId = OrderDocumentLocationAdapterFactory.locationAdapter(order).getBPartnerLocationAndCaptureId(); final PricingSystemId pricingSystemId = PricingSystemId.ofRepoIdOrNull(order.getM_PricingSystem_ID()); final ZonedDateTime date = TimeUtil.asZonedDateTime(order.getDatePromised()); final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx()); final ClientId clientId = ClientId.ofRepoId(order.getAD_Client_ID()); final boolean anyNull = Stream.of(bpartnerLocationId, pricingSystemId, date, productId).anyMatch(Objects::isNull); if (anyNull) { return Optional.empty(); } return Optional.of( builder() .bPartnerLocationId(bpartnerLocationId) .productId(productId) .pricingSystemId(pricingSystemId) .date(date) .soTrx(soTrx) .clientId(clientId) .build() ); } public static Optional<DefaultPackingItemCriteria> of(@NonNull final I_C_Invoice invoice, @NonNull final ProductId productId) { final BPartnerLocationAndCaptureId bpartnerLocationId = InvoiceDocumentLocationAdapterFactory.locationAdapter(invoice).getBPartnerLocationAndCaptureId();
final PriceListId priceListId = PriceListId.ofRepoIdOrNull(invoice.getM_PriceList_ID()); final ZonedDateTime date = TimeUtil.asZonedDateTime(invoice.getDateInvoiced()); final ClientId clientId = ClientId.ofRepoId(invoice.getAD_Client_ID()); final boolean anyNull = Stream.of(bpartnerLocationId,priceListId,date, productId).anyMatch(Objects::isNull); if (anyNull) { return Optional.empty(); } return Optional.of( builder() .productId(productId) .priceListId(priceListId) .date(date) .bPartnerLocationId(bpartnerLocationId) .clientId(clientId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\field\DefaultPackingItemCriteria.java
1
请完成以下Java代码
public String qty(final Properties ctx, final int WindowNo, final GridTab mTab, final GridField mField, final Object value) { if (isCalloutActive() || value == null) { return ""; } final int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID"); checkQtyAvailable(ctx, mTab, WindowNo, M_Product_ID, (BigDecimal)value); // return ""; } // qty /** * Movement Line - Locator modified * * @param ctx Context * @param WindowNo current Window No * @param GridTab Model Tab * @param GridField Model Field * @param value The new value * @return Error message or "" */ public String locator(final Properties ctx, final int WindowNo, final GridTab mTab, final GridField mField, final Object value) { if (value == null) { return ""; } final int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID"); checkQtyAvailable(ctx, mTab, WindowNo, M_Product_ID, null); return ""; } /** * Check available qty * * @param ctx context * @param mTab Model Tab * @param WindowNo current Window No * @param M_Product_ID product ID * @param MovementQty movement qty (if null will be get from context "MovementQty") */ private void checkQtyAvailable(final Properties ctx, final GridTab mTab, final int WindowNo, final int M_Product_ID, BigDecimal MovementQty) { // Begin Armen 2006/10/01 if (M_Product_ID != 0
&& Services.get(IProductBL.class).isStocked(ProductId.ofRepoIdOrNull(M_Product_ID))) { if (MovementQty == null) { MovementQty = (BigDecimal)mTab.getValue("MovementQty"); } final int M_Locator_ID = Env.getContextAsInt(ctx, WindowNo, "M_Locator_ID"); // If no locator, don't check anything and assume is ok if (M_Locator_ID <= 0) { return; } final int M_AttributeSetInstance_ID = Env.getContextAsInt(ctx, WindowNo, "M_AttributeSetInstance_ID"); BigDecimal available = MStorage.getQtyAvailable(0, M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID, null); if (available == null) { available = ZERO; } if (available.signum() == 0) { mTab.fireDataStatusEEvent("NoQtyAvailable", "0", false); } else if (available.compareTo(MovementQty) < 0) { mTab.fireDataStatusEEvent("InsufficientQtyAvailable", available.toString(), false); } } // End Armen } } // CalloutMove
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutMovement.java
1
请完成以下Java代码
public void setUseEquals(boolean useEquals) { this.useEquals = useEquals; } /** * Set the {@link MediaType} to ignore from the {@link ContentNegotiationStrategy}. * This is useful if for example, you want to match on * {@link MediaType#APPLICATION_JSON} but want to ignore {@link MediaType#ALL}. * @param ignoredMediaTypes the {@link MediaType}'s to ignore from the * {@link ContentNegotiationStrategy} */ public void setIgnoredMediaTypes(Set<MediaType> ignoredMediaTypes) { this.ignoredMediaTypes = ignoredMediaTypes; } private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException { try { List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
MimeTypeUtils.sortBySpecificity(mediaTypes); return mediaTypes; } catch (InvalidMediaTypeException ex) { String value = exchange.getRequest().getHeaders().getFirst("Accept"); throw new NotAcceptableStatusException( "Could not parse 'Accept' header [" + value + "]: " + ex.getMessage()); } } @Override public String toString() { return "MediaTypeRequestMatcher [matchingMediaTypes=" + this.matchingMediaTypes + ", useEquals=" + this.useEquals + ", ignoredMediaTypes=" + this.ignoredMediaTypes + "]"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\MediaTypeServerWebExchangeMatcher.java
1
请完成以下Java代码
private void formWindowOpened(java.awt.event.WindowEvent evt) { if (m_maximize == true) { super.setVisible(true); super.setExtendedState(JFrame.MAXIMIZED_BOTH); } } // formWindowOpened // Add window and tab no called from public void setProcessInfo(ProcessInfo pi) { m_pi = pi; } public ProcessInfo getProcessInfo() { return m_pi; } // End /** * Start Batch * @param process * @return running thread */ public Thread startBatch (final Runnable process) { Thread worker = new Thread() { @Override public void run() { setBusy(true); process.run(); setBusy(false); } }; worker.start(); return worker;
} // startBatch /** * @return Returns the AD_Form_ID. */ public int getAD_Form_ID () { return p_AD_Form_ID; } // getAD_Window_ID public int getWindowNo() { return m_WindowNo; } /** * @return Returns the manuBar */ public JMenuBar getMenu() { return menuBar; } public void showFormWindow() { if (m_panel instanceof FormPanel2) { ((FormPanel2)m_panel).showFormWindow(m_WindowNo, this); } else { AEnv.showCenterScreenOrMaximized(this); } } } // FormFrame
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java
1
请完成以下Java代码
private void setAmountToFactLine( @NonNull final GLDistributionResultLine glDistributionLine, @NonNull final FactLine factLine) { final Money amount = Money.of(glDistributionLine.getAmount(), glDistributionLine.getCurrencyId()); switch (glDistributionLine.getAmountSign()) { case CREDIT: factLine.setAmtSource(null, amount); break; case DEBIT: factLine.setAmtSource(amount, null); break;
case DETECT: if (amount.signum() < 0) { factLine.setAmtSource(null, amount.negate()); } else { factLine.setAmtSource(amount, null); } break; } factLine.convert(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactGLDistributor.java
1
请在Spring Boot框架中完成以下Java代码
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationSucessHandler authenticationSucessHandler; @Autowired private MyAuthenticationFailureHandler authenticationFailureHandler; @Autowired private ValidateCodeFilter validateCodeFilter; @Autowired private UserDetailService userDetailService; @Autowired private DataSource dataSource; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl(); jdbcTokenRepository.setDataSource(dataSource); jdbcTokenRepository.setCreateTableOnStartup(false); return jdbcTokenRepository; } @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器 .formLogin() // 表单登录 // http.httpBasic() // HTTP Basic .loginPage("/authentication/require") // 登录跳转 URL
.loginProcessingUrl("/login") // 处理表单登录 URL .successHandler(authenticationSucessHandler) // 处理登录成功 .failureHandler(authenticationFailureHandler) // 处理登录失败 .and() .rememberMe() .tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库 .tokenValiditySeconds(3600) // remember 过期时间,单为秒 .userDetailsService(userDetailService) // 处理自动登录逻辑 .and() .authorizeRequests() // 授权配置 .antMatchers("/authentication/require", "/login.html", "/code/image").permitAll() // 无需认证的请求路径 .anyRequest() // 所有请求 .authenticated() // 都需要认证 .and() .csrf().disable(); } }
repos\SpringAll-master\37.Spring-Security-RememberMe\src\main\java\cc\mrbird\security\browser\BrowserSecurityConfig.java
2
请完成以下Java代码
class InMemoryIdentityStore4Authorization implements IdentityStore { private Map<String, List<String>> userRoles = new HashMap<>(); public InMemoryIdentityStore4Authorization() { //Init users // from a file or hardcoded init(); } private void init() { //user1 List<String> roles = new ArrayList<>(); roles.add("USER_ROLE"); userRoles.put("user", roles); //user2 roles = new ArrayList<>(); roles.add("USER_ROLE"); roles.add("ADMIN_ROLE"); userRoles.put("admin", roles);
} @Override public int priority() { return 80; } @Override public Set<ValidationType> validationTypes() { return EnumSet.of(ValidationType.PROVIDE_GROUPS); } @Override public Set<String> getCallerGroups(CredentialValidationResult validationResult) { List<String> roles = userRoles.get(validationResult.getCallerPrincipal().getName()); return new HashSet<>(roles); } }
repos\tutorials-master\security-modules\java-ee-8-security-api\app-auth-custom-form-store-custom\src\main\java\com\baeldung\javaee\security\InMemoryIdentityStore4Authorization.java
1
请在Spring Boot框架中完成以下Java代码
public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } @ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "2") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2") public String getDeploymentUrl() { return deploymentUrl; } public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "oneChannel.channel") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneChannel.channel", value = "Contains the actual deployed channel definition JSON.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a channel definition for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResponse.java
2
请完成以下Spring Boot application配置
spring.kafka: bootstrap-servers: localhost:9092 producer: key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.springframework.kafka.support.serializer.JsonSerializer type-mapping: com.baeldung.annotation.events.externalization.producer.ArticlePublished consumer: key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer auto-offset-reset: earliest spring.modulith: republish-outstanding-events-on-restart: true events.jdbc.schema-initialization.enabled: true logging.level.org.springframework.o
rm.jpa: TRACE spring: datasource: username: test_user password: test_pass jpa: properties: hibernate: dialect: org.hibernate.dialect.PostgreSQLDialect hbm2ddl.auto: create management: endpoints: web: exposure: include: jolokia
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\resources\application-modulith.yml
2
请完成以下Java代码
public void setQtyDemand_QtySupply_V_ID (final int QtyDemand_QtySupply_V_ID) { if (QtyDemand_QtySupply_V_ID < 1) set_ValueNoCheck (COLUMNNAME_QtyDemand_QtySupply_V_ID, null); else set_ValueNoCheck (COLUMNNAME_QtyDemand_QtySupply_V_ID, QtyDemand_QtySupply_V_ID); } @Override public int getQtyDemand_QtySupply_V_ID() { return get_ValueAsInt(COLUMNNAME_QtyDemand_QtySupply_V_ID); } @Override public void setQtyForecasted (final @Nullable BigDecimal QtyForecasted) { set_ValueNoCheck (COLUMNNAME_QtyForecasted, QtyForecasted); } @Override public BigDecimal getQtyForecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyForecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyStock (final @Nullable BigDecimal QtyStock) { set_ValueNoCheck (COLUMNNAME_QtyStock, QtyStock); } @Override public BigDecimal getQtyStock() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyStock); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setQtyToMove (final @Nullable BigDecimal QtyToMove) { set_ValueNoCheck (COLUMNNAME_QtyToMove, QtyToMove); } @Override public BigDecimal getQtyToMove() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToMove); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToProduce (final @Nullable BigDecimal QtyToProduce) { set_ValueNoCheck (COLUMNNAME_QtyToProduce, QtyToProduce); } @Override public BigDecimal getQtyToProduce() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProduce); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyUnconfirmedBySupplier (final @Nullable BigDecimal QtyUnconfirmedBySupplier) { set_ValueNoCheck (COLUMNNAME_QtyUnconfirmedBySupplier, QtyUnconfirmedBySupplier); } @Override public BigDecimal getQtyUnconfirmedBySupplier() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUnconfirmedBySupplier); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_QtyDemand_QtySupply_V.java
1
请在Spring Boot框架中完成以下Java代码
public void afterSingletonsInstantiated() { SimpleUrlHandlerMapping mapping = getBeanOrNull(SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME, SimpleUrlHandlerMapping.class); if (mapping == null) { return; } configureCsrf(mapping); } private <T> T getBeanOrNull(String name, Class<T> type) { Map<String, T> beans = this.context.getBeansOfType(type); return beans.get(name); } private void configureCsrf(SimpleUrlHandlerMapping mapping) { Map<String, Object> mappings = mapping.getHandlerMap(); for (Object object : mappings.values()) { if (object instanceof SockJsHttpRequestHandler) { setHandshakeInterceptors((SockJsHttpRequestHandler) object); } else if (object instanceof WebSocketHttpRequestHandler) { setHandshakeInterceptors((WebSocketHttpRequestHandler) object); } else { throw new IllegalStateException( "Bean " + SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME + " is expected to contain mappings to either a " + "SockJsHttpRequestHandler or a WebSocketHttpRequestHandler but got " + object); } } } private void setHandshakeInterceptors(SockJsHttpRequestHandler handler) { SockJsService sockJsService = handler.getSockJsService(); Assert.state(sockJsService instanceof TransportHandlingSockJsService, () -> "sockJsService must be instance of TransportHandlingSockJsService got " + sockJsService);
TransportHandlingSockJsService transportHandlingSockJsService = (TransportHandlingSockJsService) sockJsService; List<HandshakeInterceptor> handshakeInterceptors = transportHandlingSockJsService.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); transportHandlingSockJsService.setHandshakeInterceptors(interceptorsToSet); } private void setHandshakeInterceptors(WebSocketHttpRequestHandler handler) { List<HandshakeInterceptor> handshakeInterceptors = handler.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); handler.setHandshakeInterceptors(interceptorsToSet); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\socket\WebSocketMessageBrokerSecurityConfiguration.java
2
请完成以下Java代码
public void unacquireExternalWorkerJob(String jobId, String workerId) { commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration())); } @Override public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) { return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager()); } public <T> T executeCommand(Command<T> command) { if (command == null) { throw new FlowableIllegalArgumentException("The command is null"); } return commandExecutor.execute(command); }
public <T> T executeCommand(CommandConfig config, Command<T> command) { if (config == null) { throw new FlowableIllegalArgumentException("The config is null"); } if (command == null) { throw new FlowableIllegalArgumentException("The command is null"); } return commandExecutor.execute(config, command); } @Override public LockManager getLockManager(String lockName) { return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnManagementServiceImpl.java
1
请完成以下Java代码
private AvailabilityCheckCommand newAvailabilityCheckCommand(final PurchaseCandidatesAvailabilityRequest request) { return AvailabilityCheckCommand.builder() .vendorGatewayRegistry(vendorGatewayRegistry) .requests(createAvailabilityRequests(request.getPurchaseCandidatesGroups())) .build(); } private static Set<AvailabilityRequest> createAvailabilityRequests(@NonNull final Map<TrackingId, PurchaseCandidatesGroup> purchaseCandidatesGroupsByTrackingId) { final ListMultimap<BPartnerId, AvailabilityRequestItem> requestItemsByVendorId = purchaseCandidatesGroupsByTrackingId .entrySet() .stream() .map(entry -> toVendorAndRequestItem(entry)) .collect(GuavaCollectors.toImmutableListMultimap()); final Set<BPartnerId> vendorIds = requestItemsByVendorId.keySet(); return vendorIds.stream() .map(vendorId -> createAvailabilityRequestOrNull(vendorId, requestItemsByVendorId.get(vendorId))) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private static Map.Entry<BPartnerId, AvailabilityRequestItem> toVendorAndRequestItem(final Map.Entry<TrackingId, PurchaseCandidatesGroup> entry) { final TrackingId trackingId = entry.getKey(); final PurchaseCandidatesGroup purchaseCandidatesGroup = entry.getValue(); final BPartnerId vendorId = purchaseCandidatesGroup.getVendorId(); final AvailabilityRequestItem requestItem = createAvailabilityRequestItem(trackingId, purchaseCandidatesGroup); return GuavaCollectors.entry(vendorId, requestItem); } private static AvailabilityRequestItem createAvailabilityRequestItem(final TrackingId trackingId, final PurchaseCandidatesGroup purchaseCandidatesGroup) { final Quantity qtyToPurchase = purchaseCandidatesGroup.getQtyToPurchase();
final ProductAndQuantity productAndQuantity = ProductAndQuantity.of( purchaseCandidatesGroup.getVendorProductNo(), qtyToPurchase.toBigDecimal().max(ONE), // check availability for at least one, even if qtyToPurchase is still zero qtyToPurchase.getUOMId()); return AvailabilityRequestItem.builder() .trackingId(trackingId) .productAndQuantity(productAndQuantity) .purchaseCandidateId(PurchaseCandidateId.getRepoIdOr(purchaseCandidatesGroup.getSinglePurchaseCandidateIdOrNull(), -1)) .salesOrderLineId(OrderAndLineId.getOrderLineRepoIdOr(purchaseCandidatesGroup.getSingleSalesOrderAndLineIdOrNull(), -1)) .build(); } private static AvailabilityRequest createAvailabilityRequestOrNull(final BPartnerId vendorId, final Collection<AvailabilityRequestItem> requestItems) { if (requestItems.isEmpty()) { return null; } return AvailabilityRequest.builder() .vendorId(vendorId.getRepoId()) .availabilityRequestItems(requestItems) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityCheckService.java
1
请完成以下Java代码
public Timestamp getModelUpdated (boolean recalc) { if (recalc || m_modelUpdated == null) { String sql = "SELECT MAX(w.Updated), MAX(t.Updated), MAX(tt.Updated), MAX(f.Updated), MAX(c.Updated) " + "FROM AD_Window w" + " INNER JOIN AD_Tab t ON (w.AD_Window_ID=t.AD_Window_ID)" + " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID)" + " INNER JOIN AD_Field f ON (t.AD_Tab_ID=f.AD_Tab_ID)" + " INNER JOIN AD_Column c ON (f.AD_Column_ID=c.AD_Column_ID) " + "WHERE w.AD_Window_ID=?"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, ITrx.TRXNAME_None); DB.setParameter(pstmt, 1, getAdWindowId()); rs = pstmt.executeQuery (); if (rs.next ()) { m_modelUpdated = rs.getTimestamp(1); // Window Timestamp ts = rs.getTimestamp(2); // Tab if (ts.after(m_modelUpdated)) { m_modelUpdated = ts; } ts = rs.getTimestamp(3); // Table if (ts.after(m_modelUpdated)) { m_modelUpdated = ts; } ts = rs.getTimestamp(4); // Field if (ts.after(m_modelUpdated))
{ m_modelUpdated = ts; } ts = rs.getTimestamp(5); // Column if (ts.after(m_modelUpdated)) { m_modelUpdated = ts; } } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } return m_modelUpdated; } // getModelUpdated // metas: begin: public GridWindowVO getVO() { return m_vo; } // metas: end } // MWindow
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindow.java
1
请完成以下Java代码
public WebEndpointResponse<Object> triggerQuartzJob(@Selector String jobs, @Selector String group, @Selector String name, String state) throws SchedulerException { if ("jobs".equals(jobs) && "running".equals(state)) { return handleNull(this.delegate.triggerQuartzJob(group, name)); } return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST); } private <T> WebEndpointResponse<T> handle(String jobsOrTriggers, ResponseSupplier<T> jobAction, ResponseSupplier<T> triggerAction) throws SchedulerException { if ("jobs".equals(jobsOrTriggers)) { return handleNull(jobAction.get()); } if ("triggers".equals(jobsOrTriggers)) { return handleNull(triggerAction.get()); } return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST); } private <T> WebEndpointResponse<T> handleNull(@Nullable T value) { return (value != null) ? new WebEndpointResponse<>(value) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } @FunctionalInterface private interface ResponseSupplier<T> { @Nullable T get() throws SchedulerException;
} static class QuartzEndpointWebExtensionRuntimeHints implements RuntimeHintsRegistrar { private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { this.bindingRegistrar.registerReflectionHints(hints.reflection(), QuartzGroupsDescriptor.class, QuartzJobDetailsDescriptor.class, QuartzJobGroupSummaryDescriptor.class, QuartzTriggerGroupSummaryDescriptor.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-quartz\src\main\java\org\springframework\boot\quartz\actuate\endpoint\QuartzEndpointWebExtension.java
1
请在Spring Boot框架中完成以下Java代码
protected void applyFilters(DeploymentQuery query) { if (withoutSource != null && withoutSource && source != null) { throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination."); } if (id != null) { query.deploymentId(id); } if (name != null) { query.deploymentName(name); } if (nameLike != null) { query.deploymentNameLike(nameLike); } if (TRUE.equals(withoutSource)) { query.deploymentSource(null); } if (source != null) { query.deploymentSource(source); } if (before != null) { query.deploymentBefore(before); } if (after != null) { query.deploymentAfter(after); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); }
if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDeploymentsWithoutTenantId)) { query.includeDeploymentsWithoutTenantId(); } } @Override protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByDeploymentName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) { query.orderByDeploymentTime(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentQueryDto.java
2
请完成以下Java代码
public void setProductCodeType (java.lang.String ProductCodeType) { set_ValueNoCheck (COLUMNNAME_ProductCodeType, ProductCodeType); } /** Get Kodierungskennzeichen. @return Kodierungskennzeichen */ @Override public java.lang.String getProductCodeType () { return (java.lang.String)get_Value(COLUMNNAME_ProductCodeType); } /** * SerialNumber AD_Reference_ID=110 * Reference name: AD_User */
public static final int SERIALNUMBER_AD_Reference_ID=110; /** Set Seriennummer. @param SerialNumber Seriennummer */ @Override public void setSerialNumber (java.lang.String SerialNumber) { set_ValueNoCheck (COLUMNNAME_SerialNumber, SerialNumber); } /** Get Seriennummer. @return Seriennummer */ @Override public java.lang.String getSerialNumber () { return (java.lang.String)get_Value(COLUMNNAME_SerialNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Productdata_Result.java
1
请完成以下Java代码
private ImmutableMap<UserDashboardItemId, UserDashboardItem> getItemsById(final DashboardWidgetType widgetType) { if (widgetType == DashboardWidgetType.TargetIndicator) { return _targetIndicatorItemsById; } else if (widgetType == DashboardWidgetType.KPI) { return _kpiItemsById; } else { throw new AdempiereException("Unknown widget type: " + widgetType); } } public ImmutableSet<UserDashboardItemId> getItemIds(final DashboardWidgetType dashboardWidgetType) { return getItemsById(dashboardWidgetType).keySet(); } public Collection<UserDashboardItem> getItems(final DashboardWidgetType dashboardWidgetType) {
return getItemsById(dashboardWidgetType).values(); } public UserDashboardItem getItemById( @NonNull final DashboardWidgetType dashboardWidgetType, @NonNull final UserDashboardItemId itemId) { final UserDashboardItem item = getItemsById(dashboardWidgetType).get(itemId); if (item == null) { throw new EntityNotFoundException("No " + dashboardWidgetType + " item found") .setParameter("itemId", itemId); } return item; } public void assertItemIdExists( @NonNull final DashboardWidgetType dashboardWidgetType, @NonNull final UserDashboardItemId itemId) { getItemById(dashboardWidgetType, itemId); // will fail if itemId does not exist } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboard.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { //pick up all TokenEnhancers incl. those defined in the application //this avoids changes to this class if an application wants to add its own to the chain Collection<TokenEnhancer> tokenEnhancers = applicationContext.getBeansOfType(TokenEnhancer.class).values(); TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(new ArrayList<>(tokenEnhancers)); endpoints .authenticationManager(authenticationManager) .tokenStore(tokenStore()) .tokenEnhancer(tokenEnhancerChain) .reuseRefreshTokens(false); //don't reuse or we will run into session inactivity timeouts } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; /** * Apply the token converter (and enhancer) for token store. * @return the JwtTokenStore managing the tokens. */ @Bean public JwtTokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); }
/** * This bean generates an token enhancer, which manages the exchange between JWT acces tokens and Authentication * in both directions. * * @return an access token converter configured with the authorization server's public/private keys */ @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); KeyPair keyPair = new KeyStoreKeyFactory( new ClassPathResource(uaaProperties.getKeyStore().getName()), uaaProperties.getKeyStore().getPassword().toCharArray()) .getKeyPair(uaaProperties.getKeyStore().getAlias()); converter.setKeyPair(keyPair); return converter; } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess( "isAuthenticated()"); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaConfiguration.java
2
请完成以下Java代码
public applet setVSpace (double vspace) { addAttribute ("vspace", Double.toString (vspace)); return (this); } /** * Set the horizontal or vertical alignment of this applet.<br> * Convience variables are in the AlignTypes interface. * * @param alignment * Set the horizontal or vertical alignment of this applet.<br> * Convience variables are in the AlignTypes interface. */ public applet setAlign (String alignment) { addAttribute ("align", alignment); return (this); } /** * Set the name of this applet. * * @param name * set the name of this applet. */ public applet setName (String name) { addAttribute ("name", name); return (this); } /** * Serialized applet file. * * @param object * Serialized applet file. */ // someone give me a better description of what this does. public applet setObject (String object) { addAttribute ("object", object); return (this); } /** * Breif description, alternate text for the applet. * * @param alt * alternat text. */ public applet setAlt (String alt) { addAttribute ("alt", alt); return (this); } /** * Sets the lang="" and xml:lang="" attributes * * @param lang * the lang="" and xml:lang="" attributes */ public Element setLang (String lang) { addAttribute ("lang", lang); addAttribute ("xml:lang", lang); return this; } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public applet addElement (String hashcode, Element element)
{ addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public applet addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this); } /** * Add an element to the element * * @param element * a string representation of the element */ public applet addElement (String element) { addElementToRegistry (element); return (this); } /** * Add an element to the element * * @param element * an element to add */ public applet addElement (Element element) { addElementToRegistry (element); return (this); } /** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public applet removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\applet.java
1
请完成以下Java代码
public boolean isRunning() { return isRunning.get(); } public void setBackoffStrategy(BackoffStrategy backOffStrategy) { this.backoffStrategy = backOffStrategy; } protected void runBackoffStrategy(FetchAndLockResponseDto fetchAndLockResponse) { try { List<ExternalTask> externalTasks = fetchAndLockResponse.getExternalTasks(); if (backoffStrategy instanceof ErrorAwareBackoffStrategy) { ErrorAwareBackoffStrategy errorAwareBackoffStrategy = ((ErrorAwareBackoffStrategy) backoffStrategy); ExternalTaskClientException exception = fetchAndLockResponse.getError(); errorAwareBackoffStrategy.reconfigure(externalTasks, exception); } else { backoffStrategy.reconfigure(externalTasks); } long waitTime = backoffStrategy.calculateBackoffTime(); suspend(waitTime); } catch (Throwable e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } } protected void suspend(long waitTime) { if (waitTime > 0 && isRunning.get()) { ACQUISITION_MONITOR.lock(); try { if (isRunning.get()) { IS_WAITING.await(waitTime, TimeUnit.MILLISECONDS);
} } catch (InterruptedException e) { LOG.exceptionWhileExecutingBackoffStrategyMethod(e); } finally { ACQUISITION_MONITOR.unlock(); } } } protected void resume() { ACQUISITION_MONITOR.lock(); try { IS_WAITING.signal(); } finally { ACQUISITION_MONITOR.unlock(); } } public void disableBackoffStrategy() { this.isBackoffStrategyDisabled.set(true); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionManager.java
1
请在Spring Boot框架中完成以下Java代码
public class WebServiceConfigV1 { private static final String SCHEMA_RESOURCE_PREFIX = "/de/metas/vertical/pharma/vendor/gateway/msv3/schema/v1"; @Bean public ObjectFactory jaxbObjectFactoryV1() { return new ObjectFactory(); } // e.g. http://localhost:8080/ws/Msv3VerbindungTestenService.wsdl @Bean(name = TestConnectionWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition testConnectionWebServiceV1() { return createWsdl(TestConnectionWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3VerfuegbarkeitAnfragenService.wsdl @Bean(name = StockAvailabilityWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition stockAvailabilityWebServiceV1() { return createWsdl(StockAvailabilityWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3BestellenService.wsdl @Bean(name = OrderWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition orderWebServiceV1() { return createWsdl(OrderWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3BestellstatusAbfragenService.wsdl @Bean(name = OrderStatusWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition orderStatusWebServiceV1() { return createWsdl(OrderStatusWebServiceV1.WSDL_BEAN_NAME); } @Bean("Msv3Service_schema1") public XsdSchema msv3serviceSchemaXsdV1() { return createXsdSchema("Msv3Service_schema1.xsd"); }
@Bean("Msv3FachlicheFunktionen") public XsdSchema msv3FachlicheFunktionenV1() { return createXsdSchema("Msv3FachlicheFunktionen.xsd"); } private static Wsdl11Definition createWsdl(@NonNull final String beanName) { return new SimpleWsdl11Definition(createSchemaResource(beanName + ".wsdl")); } private static XsdSchema createXsdSchema(@NonNull final String resourceName) { return new SimpleXsdSchema(createSchemaResource(resourceName)); } private static ClassPathResource createSchemaResource(@NonNull final String resourceName) { return new ClassPathResource(SCHEMA_RESOURCE_PREFIX + "/" + resourceName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\WebServiceConfigV1.java
2
请完成以下Java代码
public void setPhone (java.lang.String Phone) { set_ValueNoCheck (COLUMNNAME_Phone, Phone); } /** Get Telefon. @return Beschreibt eine Telefon Nummer */ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Steuer-ID. @param TaxID Tax Identification */ @Override public void setTaxID (java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } /** Get Steuer-ID. @return Tax Identification */ @Override
public java.lang.String getTaxID () { return (java.lang.String)get_Value(COLUMNNAME_TaxID); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java
1
请完成以下Java代码
public de.metas.payment.esr.model.I_ESR_Import getESR_Import() { return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class); } @Override public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import) { set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import); } @Override public void setESR_Import_ID (final int ESR_Import_ID) { if (ESR_Import_ID < 1) set_Value (COLUMNNAME_ESR_Import_ID, null); else set_Value (COLUMNNAME_ESR_Import_ID, ESR_Import_ID); } @Override public int getESR_Import_ID() { return get_ValueAsInt(COLUMNNAME_ESR_Import_ID); } @Override public void setFileName (final @Nullable java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setHash (final @Nullable java.lang.String Hash) { set_Value (COLUMNNAME_Hash, Hash); }
@Override public java.lang.String getHash() { return get_ValueAsString(COLUMNNAME_Hash); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportFile.java
1
请在Spring Boot框架中完成以下Java代码
public List<User> queryAll() { return userDao.findAllUsers(); } // 新增一条记录 @GetMapping("/users/mybatis/insert") public Boolean insert(String name, String password) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false; } User user = new User(); user.setName(name); user.setPassword(password); return userDao.insertUser(user) > 0; } // 修改一条记录 @GetMapping("/users/mybatis/update") public Boolean update(Integer id, String name, String password) { if (id == null || id < 1 || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false;
} User user = new User(); user.setId(id); user.setName(name); user.setPassword(password); return userDao.updUser(user) > 0; } // 删除一条记录 @GetMapping("/users/mybatis/delete") public Boolean delete(Integer id) { if (id == null || id < 1) { return false; } return userDao.delUser(id) > 0; } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-mybatis\src\main\java\cn\lanqiao\springboot3\controller\MyBatisController.java
2
请完成以下Java代码
public String getAuthorId() { return authorId; } public void setAuthorId(String authorId) { this.authorId = authorId; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; }
public Editor getEditor() { return editor; } public void setEditor(Editor editor) { this.editor = editor; } public Set<Article> getAuthoredArticles() { return authoredArticles; } public void setAuthoredArticles(Set<Article> authoredArticles) { this.authoredArticles = authoredArticles; } }
repos\tutorials-master\persistence-modules\hibernate-ogm\src\main\java\com\baeldung\hibernate\ogm\Author.java
1
请完成以下Java代码
default ValidationEntry addEntry(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description, ValidationEntry.Level level) { ValidationEntry entry = new ValidationEntry(); entry.setLevel(level); if (caze != null) { entry.setCaseDefinitionId(caze.getId()); entry.setCaseDefinitionName(caze.getName()); } if (baseElement != null) { entry.setXmlLineNumber(baseElement.getXmlRowNumber()); entry.setXmlColumnNumber(baseElement.getXmlColumnNumber()); } entry.setProblem(problem); entry.setDefaultDescription(description);
if (caseElement == null && baseElement instanceof CaseElement) { caseElement = (CaseElement) baseElement; } if (caseElement != null) { entry.setItemId(caseElement.getId()); entry.setItemName(caseElement.getName()); } return addEntry(entry); } ValidationEntry addEntry(ValidationEntry entry); }
repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\CaseValidationContext.java
1
请完成以下Java代码
public void deleteAllSpecAttributes(final I_DIM_Dimension_Spec spec) { Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec_Attribute.class, spec) .addEqualsFilter(I_DIM_Dimension_Spec_Attribute.COLUMN_DIM_Dimension_Spec_ID, spec.getDIM_Dimension_Spec_ID()) .create() .delete(); } @Override public List<DimensionSpec> retrieveForColumn(final I_AD_Column column) { final IQuery<I_DIM_Dimension_Spec_Assignment> assignmentQuery = createDimAssignmentQueryBuilderFor(column) .addOnlyActiveRecordsFilter() .create(); return Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec.class, column) .addInSubQueryFilter(I_DIM_Dimension_Spec.COLUMN_DIM_Dimension_Spec_ID, I_DIM_Dimension_Spec_Assignment.COLUMN_DIM_Dimension_Spec_ID, assignmentQuery) .create() .stream(I_DIM_Dimension_Spec.class) .map(DimensionSpec::ofRecord) .collect(ImmutableList.toImmutableList()); } @Override public DimensionSpec retrieveForInternalNameOrNull(final String internalName) { final I_DIM_Dimension_Spec record = Services.get(IQueryBL.class).createQueryBuilder(I_DIM_Dimension_Spec.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DIM_Dimension_Spec.COLUMN_InternalName, internalName) .create() .firstOnly(I_DIM_Dimension_Spec.class); if(record == null) { return null; } return DimensionSpec.ofRecord(record); } @Override
public List<String> retrieveAttributeValueForGroup(final String dimensionSpectInternalName, final String groupName, final IContextAware ctxAware) { final KeyNamePair[] keyNamePairs = DB.getKeyNamePairs("SELECT M_AttributeValue_ID, ValueName " + "FROM " + DimensionConstants.VIEW_DIM_Dimension_Spec_Attribute_AllValue + " WHERE InternalName=? AND GroupName=?", false, dimensionSpectInternalName, groupName); final List<String> result = new ArrayList<String>(keyNamePairs.length); for (final KeyNamePair keyNamePair : keyNamePairs) { result.add(keyNamePair.getName()); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\impl\DimensionspecDAO.java
1
请完成以下Java代码
public int getOptimizationLevel() { return optimizationLevel; } public void setOptimizationLevel(int optimizationLevel) { this.optimizationLevel = optimizationLevel; } public SecureScriptClassShutter getClassShutter() { return classShutter; } public void setClassShutter(SecureScriptClassShutter classShutter) { this.classShutter = classShutter; } public int getObserveInstructionCount() { return observeInstructionCount; } public void setObserveInstructionCount(int observeInstructionCount) { this.observeInstructionCount = observeInstructionCount; } public long getMaxScriptExecutionTime() { return maxScriptExecutionTime; } public void setMaxScriptExecutionTime(long maxScriptExecutionTime) { this.maxScriptExecutionTime = maxScriptExecutionTime; } public long getMaxMemoryUsed() { return maxMemoryUsed; } public void setMaxMemoryUsed(long maxMemoryUsed) { this.maxMemoryUsed = maxMemoryUsed; if (maxMemoryUsed > 0) { try { Class clazz = Class.forName("com.sun.management.ThreadMXBean"); if (clazz != null) { this.threadMxBeanWrapper = new SecureScriptThreadMxBeanWrapper(); } } catch (ClassNotFoundException cnfe) { LOGGER.warn("com.sun.management.ThreadMXBean was not found on the classpath. " +
"This means that the limiting the memory usage for a script will NOT work."); } } } public int getMaxStackDepth() { return maxStackDepth; } public void setMaxStackDepth(int maxStackDepth) { this.maxStackDepth = maxStackDepth; } public boolean isEnableAccessToBeans() { return enableAccessToBeans; } public void setEnableAccessToBeans(boolean enableAccessToBeans) { this.enableAccessToBeans = enableAccessToBeans; } }
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\impl\SecureScriptContextFactory.java
1
请完成以下Java代码
public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getParentActivityInstanceId() { return parentActivityInstanceId; } public void setParentActivityInstanceId(String parentActivityInstanceId) { this.parentActivityInstanceId = parentActivityInstanceId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public void setCalledCaseInstanceId(String calledCaseInstanceId) { this.calledCaseInstanceId = calledCaseInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskAssignee() { return taskAssignee; } public void setTaskAssignee(String taskAssignee) { this.taskAssignee = taskAssignee; } public void setActivityInstanceState(int activityInstanceState) { this.activityInstanceState = activityInstanceState; } public int getActivityInstanceState() { return activityInstanceState; } public boolean isCompleteScope() { return ActivityInstanceState.SCOPE_COMPLETE.getStateCode() == activityInstanceState; } public boolean isCanceled() {
return ActivityInstanceState.CANCELED.getStateCode() == activityInstanceState; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[activityId=" + activityId + ", activityName=" + activityName + ", activityType=" + activityType + ", activityInstanceId=" + activityInstanceId + ", activityInstanceState=" + activityInstanceState + ", parentActivityInstanceId=" + parentActivityInstanceId + ", calledProcessInstanceId=" + calledProcessInstanceId + ", calledCaseInstanceId=" + calledCaseInstanceId + ", taskId=" + taskId + ", taskAssignee=" + taskAssignee + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricActivityInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BpmnInterface getInterface() { return bpmnInterface; } public void setInterface(BpmnInterface bpmnInterface) { this.bpmnInterface = bpmnInterface; } public MessageDefinition getInMessage() { return inMessage; } public void setInMessage(MessageDefinition inMessage) { this.inMessage = inMessage;
} public MessageDefinition getOutMessage() { return outMessage; } public void setOutMessage(MessageDefinition outMessage) { this.outMessage = outMessage; } public OperationImplementation getImplementation() { return implementation; } public void setImplementation(OperationImplementation implementation) { this.implementation = implementation; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\webservice\Operation.java
2
请完成以下Java代码
private void registerRelatedProcessNoFail( @NonNull final String importTableName, @NonNull final AdProcessId processId) { try { final IADTableDAO tablesRepo = Services.get(IADTableDAO.class); final AdTableId importTableId = AdTableId.ofRepoId(tablesRepo.retrieveTableId(importTableName)); adProcessesRepo.registerTableProcess(RelatedProcessDescriptor.builder() .processId(processId) .tableId(importTableId) .displayPlace(DisplayPlace.ViewActionsMenu) .build()); } catch (final Exception ex) { logger.warn("Cannot register process {} to {}. Skip", processId, importTableName, ex); } } @ToString private static class ImportTableRelatedProcess { @Getter private final String name; @Getter private AdProcessId processId; private final HashSet<String> registeredOnTableNames = new HashSet<>();
public ImportTableRelatedProcess(@NonNull final String name) { this.name = name; } public void setProcessId(@NonNull final AdProcessId processId) { if (this.processId != null && !Objects.equals(this.processId, processId)) { throw new AdempiereException("Changing process from " + this.processId + " to " + processId + " is not allowed."); } this.processId = processId; } public boolean hasTableName(@NonNull final String tableName) { return registeredOnTableNames.contains(tableName); } public void addTableName(@NonNull final String tableName) { registeredOnTableNames.add(tableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportTablesRelatedProcessesRegistry.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String address; @OneToMany(cascade = CascadeType.ALL) private List<Book> books; // Default constructor for JPA deserialization public User() { } public User(String firstName, String lastName, String address, List<Book> books) { this.firstName = firstName; this.lastName = lastName; this.address = address; this.books = books; } public String getNameOfMostOwnedBook() { Map<String, Long> bookOwnershipCount = books.stream() .collect(Collectors.groupingBy(Book::getName, Collectors.counting())); return bookOwnershipCount.entrySet() .stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
repos\tutorials-master\spring-boot-modules\spring-boot-crud\src\main\java\com\baeldung\entitydtodifferences\entity\User.java
2
请完成以下Java代码
public class ReverseNumber { public static int reverseNumberWhileLoop(int number) { int reversedNumber = 0; int numberToReverse = Math.abs(number); while (numberToReverse > 0) { int mod = numberToReverse % 10; reversedNumber = reversedNumber * 10 + mod; numberToReverse /= 10; } return number < 0 ? reversedNumber * -1 : reversedNumber; } public static int reverseNumberForLoop(int number) { int reversedNumber = 0; int numberToReverse = Math.abs(number); for (; numberToReverse > 0; numberToReverse /= 10) { int mod = numberToReverse % 10; reversedNumber = reversedNumber * 10 + mod; } return number < 0 ? reversedNumber * -1 : reversedNumber; }
public static int reverseNumberRecWrapper(int number) { int output = reverseNumberRec(Math.abs(number), 0); return number < 0 ? output * -1 : output; } private static int reverseNumberRec(int numberToReverse, int recursiveReversedNumber) { if (numberToReverse > 0) { int mod = numberToReverse % 10; recursiveReversedNumber = recursiveReversedNumber * 10 + mod; numberToReverse /= 10; return reverseNumberRec(numberToReverse, recursiveReversedNumber); } return recursiveReversedNumber; } }
repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\reversenumber\ReverseNumber.java
1
请完成以下Java代码
public static void main(String[] args) { parseYAMLFile(); parseJSONFile(); parseString(); } private static void parseString() { SwaggerParseResult result = new OpenAPIParser().readContents(OPENAPI_SPECIFICATION_STRING, null, null); OpenAPI openAPI = result.getOpenAPI(); if (openAPI != null) { printData(openAPI); } } private static void parseJSONFile() { SwaggerParseResult result = new OpenAPIParser().readLocation("sample.yml", null, null); OpenAPI openAPI = result.getOpenAPI(); if (openAPI != null) { printData(openAPI); } } private static void parseYAMLFile() { SwaggerParseResult result = new OpenAPIParser().readLocation("sample.json", null, null); OpenAPI openAPI = result.getOpenAPI(); if (openAPI != null) { printData(openAPI); } } private static void printData(OpenAPI openAPI) { System.out.println(openAPI.getSpecVersion()); Info info = openAPI.getInfo(); System.out.println(info.getTitle()); System.out.println(info.getVersion()); List<Server> servers = openAPI.getServers(); for (Server server : servers) { System.out.println(server.getUrl()); System.out.println(server.getDescription()); } Paths paths = openAPI.getPaths();
paths.entrySet() .forEach(pathEntry -> { System.out.println(pathEntry.getKey()); PathItem path = pathEntry.getValue(); System.out.println(path.getGet() .getSummary()); System.out.println(path.getGet() .getDescription()); System.out.println(path.getGet() .getOperationId()); ApiResponses responses = path.getGet() .getResponses(); responses.entrySet() .forEach(responseEntry -> { System.out.println(responseEntry.getKey()); ApiResponse response = responseEntry.getValue(); System.out.println(response.getDescription()); }); }); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\swaggerparser\SwaggerParser.java
1
请完成以下Java代码
public boolean isCopy() { return m_isCopy; } // isCopy /** * Set Copy * * @param isCopy if true document is a copy */ public void setCopy(final boolean isCopy) { m_isCopy = isCopy; } // setCopy /************************************************************************** * Get the doc flavor (Doc Interface) * * @return SERVICE_FORMATTED.PAGEABLE */ @Override public DocFlavor getDocFlavor() { return DocFlavor.SERVICE_FORMATTED.PAGEABLE; } // getDocFlavor /** * Get Print Data (Doc Interface) * * @return this * @throws IOException */ @Override public Object getPrintData() throws IOException { return this; } // getPrintData /** * Get Document Attributes (Doc Interface) * * @return null to obtain all attribute values from the * job's attribute set. */ @Override public DocAttributeSet getAttributes() { return null; } // getAttributes /** * Obtains a reader for extracting character print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public Reader getReaderForText() throws IOException
{ return null; } // getReaderForText /** * Obtains an input stream for extracting byte print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public InputStream getStreamForBytes() throws IOException { return null; } // getStreamForBytes public void setPrintInfo(final ArchiveInfo info) { m_PrintInfo = info; } /** * @return PrintInfo */ public ArchiveInfo getPrintInfo() { return m_PrintInfo; } } // LayoutEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\LayoutEngine.java
1
请完成以下Java代码
public class EventResourceEntityImpl extends AbstractEventRegistryNoRevisionEntity implements EventResourceEntity, Serializable { private static final long serialVersionUID = 1L; protected String name; protected byte[] bytes; protected String deploymentId; public EventResourceEntityImpl() { } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public byte[] getBytes() { return bytes; }
@Override public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Object getPersistentState() { return EventResourceEntityImpl.class; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventResourceEntityImpl.java
1
请完成以下Java代码
public ViewHeaderProperties getHeaderProperties() { return rowsData.getHeaderProperties(); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } public ViewId getInitialViewId() { return initialViewId != null ? initialViewId : getViewId(); } @Override public ViewId getParentViewId() { return initialViewId; } public Optional<OrderId> getOrderId() { return rowsData.getOrder().map(Order::getOrderId); } public Optional<BPartnerId> getBpartnerId() { return rowsData.getBpartnerId(); } public SOTrx getSoTrx() { return rowsData.getSoTrx(); } public CurrencyId getCurrencyId() { return rowsData.getCurrencyId(); } public Set<ProductId> getProductIds() { return rowsData.getProductIds(); } public Optional<PriceListVersionId> getSinglePriceListVersionId() { return rowsData.getSinglePriceListVersionId(); } public Optional<PriceListVersionId> getBasePriceListVersionId() {
return rowsData.getBasePriceListVersionId(); } public PriceListVersionId getBasePriceListVersionIdOrFail() { return rowsData.getBasePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@")); } public List<ProductsProposalRow> getAllRows() { return ImmutableList.copyOf(getRows()); } public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests) { rowsData.addOrUpdateRows(requests); invalidateAll(); } public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request) { rowsData.patchRow(rowId, request); } public void removeRowsByIds(final Set<DocumentId> rowIds) { rowsData.removeRowsByIds(rowIds); invalidateAll(); } public ProductsProposalView filter(final ProductsProposalViewFilter filter) { rowsData.filter(filter); return this; } @Override public DocumentFilterList getFilters() { return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
1
请完成以下Java代码
public class JuelExpression implements Expression { private String expressionText; private ValueExpression valueExpression; public JuelExpression(ValueExpression valueExpression, String expressionText) { this.valueExpression = valueExpression; this.expressionText = expressionText; } @Override public Object getValue(VariableScope variableScope) { ELContext elContext = Context.getProcessEngineConfiguration() .getExpressionManager() .getElContext(variableScope); return getValueFromContext(elContext, Context.getProcessEngineConfiguration().getDelegateInterceptor()); } @Override public void setValue(Object value, VariableScope variableScope) { ELContext elContext = Context.getProcessEngineConfiguration() .getExpressionManager() .getElContext(variableScope); try { ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value); Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(invocation); } catch (Exception e) { throw new ActivitiException("Error while evaluating expression: " + expressionText, e); } } @Override public String toString() { if (valueExpression != null) { return valueExpression.getExpressionString(); } return super.toString(); } @Override public String getExpressionText() {
return expressionText; } @Override public Object getValue( ExpressionManager expressionManager, DelegateInterceptor delegateInterceptor, Map<String, Object> availableVariables ) { ELContext elContext = expressionManager.getElContext(availableVariables); return getValueFromContext(elContext, delegateInterceptor); } private Object getValueFromContext(ELContext elContext, DelegateInterceptor delegateInterceptor) { try { ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext); delegateInterceptor.handleInvocation(invocation); return invocation.getInvocationResult(); } catch (PropertyNotFoundException pnfe) { throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe); } catch (MethodNotFoundException mnfe) { throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe); } catch (Exception ele) { throw new ActivitiException("Error while evaluating expression: " + expressionText, ele); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java
1
请完成以下Java代码
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions, SessionRegistry registry) throws SessionAuthenticationException { if (this.exceptionIfMaximumExceeded || (sessions == null)) { throw new SessionAuthenticationException( this.messages.getMessage("ConcurrentSessionControlAuthenticationStrategy.exceededAllowed", new Object[] { allowableSessions }, "Maximum sessions of {0} for this principal exceeded")); } // Determine least recently used sessions, and mark them for invalidation sessions.sort(Comparator.comparing(SessionInformation::getLastRequest)); int maximumSessionsExceededBy = sessions.size() - allowableSessions + 1; List<SessionInformation> sessionsToBeExpired = sessions.subList(0, maximumSessionsExceededBy); for (SessionInformation session : sessionsToBeExpired) { session.expireNow(); } } /** * Sets the <tt>exceptionIfMaximumExceeded</tt> property, which determines whether the * user should be prevented from opening more sessions than allowed. If set to * <tt>true</tt>, a <tt>SessionAuthenticationException</tt> will be raised which means * the user authenticating will be prevented from authenticating. if set to * <tt>false</tt>, the user that has already authenticated will be forcibly logged * out. * @param exceptionIfMaximumExceeded defaults to <tt>false</tt>. */ public void setExceptionIfMaximumExceeded(boolean exceptionIfMaximumExceeded) { this.exceptionIfMaximumExceeded = exceptionIfMaximumExceeded; } /** * Sets the <tt>sessionLimit</tt> property. The default value is 1. Use -1 for * unlimited sessions. * @param maximumSessions the maximum number of permitted sessions a user can have * open simultaneously. */ public void setMaximumSessions(int maximumSessions) { this.sessionLimit = SessionLimit.of(maximumSessions);
} /** * Sets the <tt>sessionLimit</tt> property. The default value is 1. Use -1 for * unlimited sessions. * @param sessionLimit the session limit strategy * @since 6.5 */ public void setMaximumSessions(SessionLimit sessionLimit) { Assert.notNull(sessionLimit, "sessionLimit cannot be null"); this.sessionLimit = sessionLimit; } /** * Sets the {@link MessageSource} used for reporting errors back to the user when the * user has exceeded the maximum number of authentications. */ @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\ConcurrentSessionControlAuthenticationStrategy.java
1
请完成以下Java代码
public class JobUtil { public static JobEntity createJob(CaseInstanceEntity caseInstance, BaseElement baseElement, String jobHandlerType, CmmnEngineConfiguration cmmnEngineConfiguration) { JobEntity job = createJob((VariableContainer) caseInstance, baseElement, jobHandlerType, cmmnEngineConfiguration); job.setScopeId(caseInstance.getId()); job.setScopeDefinitionId(caseInstance.getCaseDefinitionId()); return job; } public static JobEntity createJob(PlanItemInstanceEntity planItemInstance, BaseElement baseElement, String jobHandlerType, CmmnEngineConfiguration cmmnEngineConfiguration) { JobEntity job = createJob((VariableContainer) planItemInstance, baseElement, jobHandlerType, cmmnEngineConfiguration); job.setScopeId(planItemInstance.getCaseInstanceId()); job.setSubScopeId(planItemInstance.getId()); job.setScopeDefinitionId(planItemInstance.getCaseDefinitionId()); return job; } protected static JobEntity createJob(VariableContainer variableContainer, BaseElement baseElement, String jobHandlerType, CmmnEngineConfiguration cmmnEngineConfiguration) { JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService(); JobEntity job = jobService.createJob(); job.setJobHandlerType(jobHandlerType); job.setScopeType(ScopeTypes.CMMN); job.setElementId(baseElement.getId()); if (baseElement instanceof CaseElement) { job.setElementName(((CaseElement) baseElement).getName()); }
List<ExtensionElement> jobCategoryElements = baseElement.getExtensionElements().get("jobCategory"); if (jobCategoryElements != null && jobCategoryElements.size() > 0) { ExtensionElement jobCategoryElement = jobCategoryElements.get(0); if (StringUtils.isNotEmpty(jobCategoryElement.getElementText())) { Expression categoryExpression = cmmnEngineConfiguration.getExpressionManager().createExpression(jobCategoryElement.getElementText()); Object categoryValue = categoryExpression.getValue(variableContainer); if (categoryValue != null) { job.setCategory(categoryValue.toString()); } } } job.setTenantId(variableContainer.getTenantId()); return job; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\JobUtil.java
1
请完成以下Java代码
public final class NullScriptsRegistry implements IScriptsRegistry { public static final NullScriptsRegistry instance = new NullScriptsRegistry(); private NullScriptsRegistry() { super(); } /** * @return false */ @Override public boolean isApplied(final IScript script) { return false; } /** * Does nothing
*/ @Override public void markApplied(final IScript script) { // nothing } /** * Does nothing */ @Override public void markIgnored(final IScript script) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\NullScriptsRegistry.java
1
请完成以下Java代码
private void reportLastEvent(Key key, ActivityStateWrapper stateWrapper) { var currentState = stateWrapper.getState(); long lastRecordedTime = currentState.getLastRecordedTime(); long lastReportedTime = stateWrapper.getLastReportedTime(); var metadata = currentState.getMetadata(); boolean hasExpired; boolean shouldReport; var updatedState = updateState(key, currentState); if (updatedState != null) { stateWrapper.setState(updatedState); lastRecordedTime = updatedState.getLastRecordedTime(); metadata = updatedState.getMetadata(); hasExpired = hasExpired(lastRecordedTime); shouldReport = stateWrapper.getStrategy().onReportingPeriodEnd(); } else { states.remove(key); hasExpired = false; shouldReport = true; } if (hasExpired) { states.remove(key); onStateExpiry(key, metadata); shouldReport = true; } if (shouldReport && lastReportedTime < lastRecordedTime) { long timeToReport = lastRecordedTime;
log.debug("Going to report last activity event for key: [{}]. Event time: [{}].", key, timeToReport); reportActivity(key, metadata, timeToReport, new ActivityReportCallback<>() { @Override public void onSuccess(Key key, long reportedTime) { updateLastReportedTime(key, reportedTime); } @Override public void onFailure(Key key, Throwable t) { log.debug("Failed to report last activity event for key: [{}]. Event time: [{}].", key, timeToReport, t); } }); } } @Override public long getLastRecordedTime(Key key) { ActivityStateWrapper stateWrapper = states.get(key); return stateWrapper == null ? 0L : stateWrapper.getState().getLastRecordedTime(); } private void updateLastReportedTime(Key key, long newLastReportedTime) { states.computeIfPresent(key, (__, stateWrapper) -> { stateWrapper.setLastReportedTime(Math.max(stateWrapper.getLastReportedTime(), newLastReportedTime)); return stateWrapper; }); } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\activity\AbstractActivityManager.java
1
请完成以下Java代码
public ApiUsageState update(ApiUsageState apiUsageState) { log.trace("Executing save [{}]", apiUsageState.getTenantId()); validateId(apiUsageState.getTenantId(), id -> INCORRECT_TENANT_ID + id); validateId(apiUsageState.getId(), __ -> "Can't save new usage state. Only update is allowed!"); apiUsageState.setVersion(null); ApiUsageState savedState = apiUsageStateDao.save(apiUsageState.getTenantId(), apiUsageState); eventPublisher.publishEvent(SaveEntityEvent.builder().tenantId(savedState.getTenantId()).entityId(savedState.getId()) .entity(savedState).build()); return savedState; } @Override public ApiUsageState findTenantApiUsageState(TenantId tenantId) { log.trace("Executing findTenantUsageRecord, tenantId [{}]", tenantId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); return apiUsageStateDao.findTenantApiUsageState(tenantId.getId()); } @Override public ApiUsageState findApiUsageStateByEntityId(EntityId entityId) { validateId(entityId.getId(), id -> "Invalid entity id " + id); return apiUsageStateDao.findApiUsageStateByEntityId(entityId); } @Override public ApiUsageState findApiUsageStateById(TenantId tenantId, ApiUsageStateId id) { log.trace("Executing findApiUsageStateById, tenantId [{}], apiUsageStateId [{}]", tenantId, id); validateId(tenantId, t -> INCORRECT_TENANT_ID + t); validateId(id, u -> "Incorrect apiUsageStateId " + u); return apiUsageStateDao.findById(tenantId, id.getId()); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findApiUsageStateById(tenantId, new ApiUsageStateId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(apiUsageStateDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Transactional @Override public void deleteByTenantId(TenantId tenantId) { deleteApiUsageStateByEntityId(tenantId); } @Override public EntityType getEntityType() { return EntityType.API_USAGE_STATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\usagerecord\ApiUsageStateServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void onError(Session session, Throwable error) { error.printStackTrace(); } /** * 服务器接收到客户端消息时调用的方法 */ @OnMessage public void onMessage(String message, Session session) { try{ //jackson ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //JSON字符串转 HashMap HashMap hashMap = mapper.readValue(message, HashMap.class); //消息类型 String type = (String) hashMap.get("type"); //to user String toUser = (String) hashMap.get("toUser"); Session toUserSession = sessionMap.get(toUser); String fromUser = (String) hashMap.get("fromUser"); //msg String msg = (String) hashMap.get("msg"); //sdp String sdp = (String) hashMap.get("sdp"); //ice Map iceCandidate = (Map) hashMap.get("iceCandidate"); HashMap<String, Object> map = new HashMap<>(); map.put("type",type); //呼叫的用户不在线 if(toUserSession == null){ toUserSession = session; map.put("type","call_back"); map.put("fromUser","系统消息"); map.put("msg","Sorry,呼叫的用户不在线!"); send(toUserSession,mapper.writeValueAsString(map)); return; } //对方挂断 if ("hangup".equals(type)) { map.put("fromUser",fromUser); map.put("msg","对方挂断!"); } //视频通话请求 if ("call_start".equals(type)) { map.put("fromUser",fromUser); map.put("msg","1"); } //视频通话请求回应 if ("call_back".equals(type)) { map.put("fromUser",toUser); map.put("msg",msg); } //offer if ("offer".equals(type)) {
map.put("fromUser",toUser); map.put("sdp",sdp); } //answer if ("answer".equals(type)) { map.put("fromUser",toUser); map.put("sdp",sdp); } //ice if ("_ice".equals(type)) { map.put("fromUser",toUser); map.put("iceCandidate",iceCandidate); } send(toUserSession,mapper.writeValueAsString(map)); }catch(Exception e){ e.printStackTrace(); } } /** * 封装一个send方法,发送消息到前端 */ private void send(Session session, String message) { try { System.out.println(message); session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } }
repos\springboot-demo-master\WebRTC\src\main\java\com\et\webrtc\config\WebRtcWSServer.java
2
请完成以下Java代码
protected boolean isCompensationBoundaryEvent(ActivityImpl sourceActivity) { String activityType = sourceActivity.getProperties().get(BpmnProperties.TYPE); return ActivityTypes.BOUNDARY_COMPENSATION.equals(activityType); } protected boolean isUserTaskWithTimeoutListener(ActivityImpl sourceActivity) { return ActivityTypes.TASK_USER_TASK.equals(sourceActivity.getProperties().get(BpmnProperties.TYPE)) && sourceActivity.isScope() && sourceActivity.equals(sourceActivity.getEventScope()) && sourceActivity.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS) != null && !sourceActivity.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS).isEmpty(); } protected ScopeImpl findMappedEventScope(ScopeImpl sourceEventScope, ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions) { if (sourceEventScope != null) { if (sourceEventScope == sourceEventScope.getProcessDefinition()) { return instruction.getTargetActivity().getProcessDefinition(); }
else { List<ValidatingMigrationInstruction> eventScopeInstructions = instructions.getInstructionsBySourceScope(sourceEventScope); if (eventScopeInstructions.size() > 0) { return eventScopeInstructions.get(0).getTargetActivity(); } } } return null; } protected void addFailure(ValidatingMigrationInstruction instruction, MigrationInstructionValidationReportImpl report, String sourceScopeId, String targetScopeId) { report.addFailure("The source activity's event scope (" + sourceScopeId + ") " + "must be mapped to the target activity's event scope (" + targetScopeId + ")"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\SameEventScopeInstructionValidator.java
1
请完成以下Java代码
public static List<Student> deepCopyUsingJackson(List<Student> students) { return students.stream() .map(Student::createDeepCopy) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingCloneable(List<Student> students) { return students.stream() .map(Student::clone) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingCopyConstructor(List<Student> students) { return students.stream() .map(Student::new) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingSerialization(List<Student> students) { return students.stream() .map(SerializationUtils::clone) .collect(Collectors.toList()); } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Course getCourse() { return course; }
public void setCourse(Course course) { this.course = course; } @Override public Student clone() { Student student; try { student = (Student) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } student.course = this.course.clone(); return student; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student that = (Student) o; return Objects.equals(studentId,that.studentId) && Objects.equals(studentName, that.studentName) && Objects.equals(course, that.course); } @Override public int hashCode() { return Objects.hash(studentId,studentName,course); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\deepcopyarraylist\Student.java
1
请完成以下Java代码
public class PickingSlotQRCodeJsonConverter { public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("PICKING_SLOT"); public static String toGlobalQRCodeJsonString(final PickingSlotQRCode qrCode) { return toGlobalQRCode(qrCode).getAsString(); } public static GlobalQRCode toGlobalQRCode(final PickingSlotQRCode qrCode) { return JsonConverterV1.toGlobalQRCode(qrCode); } public static PickingSlotQRCode fromGlobalQRCodeJsonString(final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static PickingSlotQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode) { if (!GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType())) {
throw new AdempiereException("Invalid QR Code") .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long } final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) { return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException("Invalid QR Code version: " + version); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\qrcode\PickingSlotQRCodeJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public PartitionerConfigReference.RefBuilder ref() { final PartitionerConfigReference.RefBuilder refBuilder = new PartitionerConfigReference.RefBuilder(this); refBuilders.add(refBuilder); return refBuilder; } public LineBuilder endRef() { final List<RefBuilder> distinctRefBuilders = refBuilders.stream() // if a builder's ref was already persisted, then we want distinct to return that one .sorted(Comparator.comparing(RefBuilder::getDLM_Partition_Config_Reference_ID).reversed()) .distinct() .collect(Collectors.toList()); refBuilders.clear(); refBuilders.addAll(distinctRefBuilders); parentBuilder.setChanged(true); // TODO: check if there was really any *new* reference return this; }
/** * Invokes the {@link RefBuilder}s and creates an ordered list of {@link PartitionerConfigReference}s within the {@link PartitionerConfigLine} which this builder is building. * */ public void buildRefs() { for (final PartitionerConfigReference.RefBuilder refBuilder : refBuilders) { final PartitionerConfigReference ref = refBuilder.build(buildLine); buildLine.references.add(ref); } buildLine.references.sort(Comparator.comparing(PartitionerConfigReference::getReferencedTableName)); } @Override public String toString() { return "LineBuilder [parentBuilder=" + parentBuilder + ", DLM_Partition_Config_Line_ID=" + dlm_Partition_Config_Line_ID + ", tableName=" + tableName + ", refBuilders=" + refBuilders + ", buildLine=" + buildLine + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigLine.java
2
请完成以下Java代码
public ProcessDefinitionInfoCacheObject execute(CommandContext commandContext) { return retrieveProcessDefinitionInfoCacheObject(processDefinitionId, commandContext); } }; if (Context.getCommandContext() != null) { infoCacheObject = retrieveProcessDefinitionInfoCacheObject( processDefinitionId, Context.getCommandContext() ); } else { infoCacheObject = commandExecutor.execute(cacheCommand); } return infoCacheObject; } public void add(String id, ProcessDefinitionInfoCacheObject obj) { cache.put(id, obj); } public void remove(String id) { cache.remove(id); } public void clear() { cache.clear(); } // For testing purposes only public int size() { return cache.size(); } protected ProcessDefinitionInfoCacheObject retrieveProcessDefinitionInfoCacheObject( String processDefinitionId, CommandContext commandContext ) { ProcessDefinitionInfoEntityManager infoEntityManager = commandContext.getProcessDefinitionInfoEntityManager(); ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper();
ProcessDefinitionInfoCacheObject cacheObject = null; if (cache.containsKey(processDefinitionId)) { cacheObject = cache.get(processDefinitionId); } else { cacheObject = new ProcessDefinitionInfoCacheObject(); cacheObject.setRevision(0); cacheObject.setInfoNode(objectMapper.createObjectNode()); } ProcessDefinitionInfoEntity infoEntity = infoEntityManager.findProcessDefinitionInfoByProcessDefinitionId( processDefinitionId ); if (infoEntity != null && infoEntity.getRevision() != cacheObject.getRevision()) { cacheObject.setRevision(infoEntity.getRevision()); if (infoEntity.getInfoJsonId() != null) { byte[] infoBytes = infoEntityManager.findInfoJsonById(infoEntity.getInfoJsonId()); try { ObjectNode infoNode = (ObjectNode) objectMapper.readTree(infoBytes); cacheObject.setInfoNode(infoNode); } catch (Exception e) { throw new ActivitiException( "Error reading json info node for process definition " + processDefinitionId, e ); } } } else if (infoEntity == null) { cacheObject.setRevision(0); cacheObject.setInfoNode(objectMapper.createObjectNode()); } return cacheObject; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\ProcessDefinitionInfoCache.java
1
请完成以下Java代码
public void setRealName(String realName) { this.realName = realName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; }
public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } @Override public String toString() { return "UserDetail{" + "id=" + id + ", userId=" + userId + ", age=" + age + ", realName='" + realName + '\'' + ", status='" + status + '\'' + ", hobby='" + hobby + '\'' + ", introduction='" + introduction + '\'' + ", lastLoginIp='" + lastLoginIp + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\UserDetail.java
1
请完成以下Java代码
public boolean releaseConnection(Connection connection) { connectionPool.add(connection); return usedConnections.remove(connection); } private static Connection createConnection(String url, String user, String password) throws SQLException { return DriverManager.getConnection(url, user, password); } @Override public int getSize() { return connectionPool.size() + usedConnections.size(); } @Override public List<Connection> getConnectionPool() { return connectionPool; } @Override public String getUrl() { return url; } @Override public String getUser() { return user; }
@Override public String getPassword() { return password; } @Override public void shutdown() throws SQLException { usedConnections.forEach(this::releaseConnection); for (Connection c : connectionPool) { c.close(); } connectionPool.clear(); } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\connectionpool\BasicConnectionPool.java
1
请完成以下Java代码
public void setAD_Index_Column_ID (int AD_Index_Column_ID) { if (AD_Index_Column_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Index_Column_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Index_Column_ID, Integer.valueOf(AD_Index_Column_ID)); } /** Get Index Column. @return Index Column */ public int getAD_Index_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Column_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Index_Table getAD_Index_Table() throws RuntimeException { return (I_AD_Index_Table)MTable.get(getCtx(), I_AD_Index_Table.Table_Name) .getPO(getAD_Index_Table_ID(), get_TrxName()); } /** Set Table Index. @param AD_Index_Table_ID Table Index */ public void setAD_Index_Table_ID (int AD_Index_Table_ID) { if (AD_Index_Table_ID < 1) set_Value (COLUMNNAME_AD_Index_Table_ID, null); else set_Value (COLUMNNAME_AD_Index_Table_ID, Integer.valueOf(AD_Index_Table_ID)); } /** Get Table Index. @return Table Index */ public int getAD_Index_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Column SQL. @param ColumnSQL Virtual Column (r/o) */ public void setColumnSQL (String ColumnSQL) { set_Value (COLUMNNAME_ColumnSQL, ColumnSQL); }
/** Get Column SQL. @return Virtual Column (r/o) */ public String getColumnSQL () { return (String)get_Value(COLUMNNAME_ColumnSQL); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ 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\org\compiere\model\X_AD_Index_Column.java
1
请完成以下Java代码
private int createOrUpdateSubscriptionProgress0() { int errorCount = 0; int count = 0; final Iterator<I_C_Flatrate_Term> termsToEvaluate = retrieveTermsToEvaluate(); while (termsToEvaluate.hasNext()) { final I_C_Flatrate_Term term = termsToEvaluate.next(); if (invokeEvalCurrentSPs(term)) { count++; } else { errorCount++; } } addLog(errorCount + " errors on updating subscriptions"); return count; } private Iterator<I_C_Flatrate_Term> retrieveTermsToEvaluate() { final Iterator<I_C_Flatrate_Term> termsToEval = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyContextClient(getCtx()) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, X_C_Flatrate_Term.CONTRACTSTATUS_DeliveryPause, X_C_Flatrate_Term.CONTRACTSTATUS_Running, X_C_Flatrate_Term.CONTRACTSTATUS_Waiting,
X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate).addColumn(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID).endOrderBy() .create() .iterate(I_C_Flatrate_Term.class); return termsToEval; } private boolean invokeEvalCurrentSPs(final I_C_Flatrate_Term flatrateTerm) { final Mutable<Boolean> success = new Mutable<>(false); Services.get(ITrxManager.class).runInNewTrx(() -> { try { subscriptionBL.evalCurrentSPs(flatrateTerm, currentDate); success.setValue(true); } catch (final AdempiereException e) { addLog("Error updating " + flatrateTerm + ": " + e.getMessage()); } }); return success.getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgress_Evaluate.java
1
请完成以下Java代码
public void setCS_Creditpass_Config_PaymentRule_ID (int CS_Creditpass_Config_PaymentRule_ID) { if (CS_Creditpass_Config_PaymentRule_ID < 1) { set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_PaymentRule_ID, null); } else { set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_PaymentRule_ID, Integer.valueOf(CS_Creditpass_Config_PaymentRule_ID)); } } // /** // * PaymentRule AD_Reference_ID=195 // * Reference name: _Payment Rule // */ // public static final int PAYMENTRULE_AD_Reference_ID=195; // /** Cash = B */ // public static final String PAYMENTRULE_Cash = "B"; // /** CreditCard = K */ // public static final String PAYMENTRULE_CreditCard = "K"; // /** DirectDeposit = T */ // public static final String PAYMENTRULE_DirectDeposit = "T"; // /** Check = S */ // public static final String PAYMENTRULE_Check = "S"; // /** OnCredit = P */ // public static final String PAYMENTRULE_OnCredit = "P"; // /** DirectDebit = D */ // public static final String PAYMENTRULE_DirectDebit = "D"; // /** Mixed = M */ // public static final String PAYMENTRULE_Mixed = "M"; /** Set Zahlungsweise. @param PaymentRule Wie die Rechnung bezahlt wird */ @Override public void setPaymentRule (java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } /** Get Zahlungsweise. @return Wie die Rechnung bezahlt wird */ @Override public java.lang.String getPaymentRule () { return (java.lang.String)get_Value(COLUMNNAME_PaymentRule); } /** Set Kaufstyp. @param PurchaseType Kaufstyp */ @Override public void setPurchaseType (java.math.BigDecimal PurchaseType) {
set_Value (COLUMNNAME_PurchaseType, PurchaseType); } /** Get Kaufstyp. @return Kaufstyp */ @Override public java.math.BigDecimal getPurchaseType () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PurchaseType); if (bd == null) { return BigDecimal.ZERO; } return bd; } /** Get Preis per Überprüfung. @return Preis per Überprüfung */ @Override public java.math.BigDecimal getRequestPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RequestPrice); if (bd == null) { return BigDecimal.ZERO; } return bd; } /** Set Preis per Überprüfung. @param RequestPrice Preis per Überprüfung */ @Override public void setRequestPrice (java.math.BigDecimal RequestPrice) { set_Value (COLUMNNAME_RequestPrice, RequestPrice); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config_PaymentRule.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingJobCandidate { @NonNull PickingJobAggregationType aggregationType; @Nullable InstantAndOrgId preparationDate; @Nullable String salesOrderDocumentNo; @Nullable OrderId salesOrderId; @Nullable String customerName; @Nullable BPartnerLocationId deliveryBPLocationId; @Nullable WarehouseTypeId warehouseTypeId; boolean partiallyPickedBefore; @Nullable BPartnerLocationId handoverLocationId; @NonNull @With PickingJobCandidateProducts products; @Nullable ShipmentScheduleAndJobScheduleIdSet scheduleIds; public Set<ProductId> getProductIds() {return products.getProductIds();} public OptionalBoolean hasQtyAvailableToPick() { return products.hasQtyAvailableToPick(); } @Nullable
public ProductId getProductId() { return products.getSingleProductIdOrNull(); } public ITranslatableString getProductName() { return products.getSingleProductNameOrNull(); } @Nullable public Quantity getQtyToDeliver() { return products.getSingleQtyToDeliverOrNull(); } @Nullable public Quantity getQtyAvailableToPick() { return products.getSingleQtyAvailableToPickOrNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidate.java
2
请完成以下Java代码
public int getM_RMALine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RMALine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Einzelpreis. @param PriceActual Effektiver Preis */ public void setPriceActual (BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ public BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return Env.ZERO; return bd; } /** Set Verarbeitet. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param QtyEntered Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); }
/** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity Invoiced. @param QtyInvoiced Invoiced Quantity */ public void setQtyInvoiced (BigDecimal QtyInvoiced) { set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Quantity Invoiced. @return Invoiced Quantity */ public BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java
1
请在Spring Boot框架中完成以下Java代码
public class TimeRange { public static TimeRange main(@NonNull final Instant from, @NonNull final Instant to) { return new TimeRange(true, from, to, Duration.ZERO); } public static TimeRange offset(@NonNull final TimeRange mainRange, @NonNull final Duration offset) { final boolean mainTimeRange = false; final Instant from = mainRange.getFrom().plus(offset); final Instant to = mainRange.getTo().plus(offset); return new TimeRange(mainTimeRange, from, to, offset); } @JsonProperty("fromMillis") long fromMillis; @JsonIgnore Instant from; @JsonProperty("toMillis") long toMillis; @JsonIgnore Instant to; @JsonIgnore boolean mainTimeRange; @JsonIgnore Duration offset; private TimeRange( final boolean mainTimeRange, @NonNull final Instant from, @NonNull final Instant to, @NonNull final Duration offset) { this.mainTimeRange = mainTimeRange; this.from = from; this.fromMillis = toMillis(from); this.to = to; this.toMillis = toMillis(to); this.offset = offset; } private static long toMillis(@NonNull final Instant instant) { return instant.isAfter(Instant.ofEpochMilli(0))
? instant.toEpochMilli() : 0; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("from", from) .add("to", to) .add("main", mainTimeRange) .add("offset", offset) .toString(); } public TimeRange offset(@NonNull final Duration offset) { final boolean mainTimeRange = false; final Instant from = this.from.plus(offset); final Instant to = this.to.plus(offset); return new TimeRange(mainTimeRange, from, to, offset); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\TimeRange.java
2
请完成以下Java代码
public static GenericData.Record mapPojoToRecordReflection(Pojo pojo) throws IllegalAccessException { Class<?> pojoClass = pojo.getClass(); Schema schema = ReflectData.get().getSchema(pojoClass); GenericData.Record avroRecord = new GenericData.Record(schema); for (Field field : pojoClass.getDeclaredFields()) { field.setAccessible(true); avroRecord.put(field.getName(), field.get(pojo)); } // Handle superclass fields Class<?> superClass = pojoClass.getSuperclass(); while (superClass != null && superClass != Object.class) { for (Field field : superClass.getDeclaredFields()) { field.setAccessible(true); avroRecord.put(field.getName(), field.get(pojo)); } superClass = superClass.getSuperclass(); } return avroRecord; } public static GenericData.Record mapPojoToRecordReflectDatumWriter(Object pojo) throws IOException {
Schema schema = ReflectData.get().getSchema(pojo.getClass()); ReflectDatumWriter<Object> writer = new ReflectDatumWriter<>(schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); writer.write(pojo, encoder); encoder.flush(); BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(out.toByteArray(), null); GenericDatumReader<GenericData.Record> reader = new GenericDatumReader<>(schema); return reader.read(null, decoder); } }
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\avro\pojotoavrorecord\ConvertingPojoToAvroRecord.java
1
请在Spring Boot框架中完成以下Java代码
public IdentityLinkEntityManager getIdentityLinkEntityManager() { return identityLinkEntityManager; } public IdentityLinkServiceConfiguration setIdentityLinkEntityManager(IdentityLinkEntityManager identityLinkEntityManager) { this.identityLinkEntityManager = identityLinkEntityManager; return this; } public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return historicIdentityLinkEntityManager; } public IdentityLinkServiceConfiguration setHistoricIdentityLinkEntityManager(HistoricIdentityLinkEntityManager historicIdentityLinkEntityManager) { this.historicIdentityLinkEntityManager = historicIdentityLinkEntityManager; return this; } @Override public ObjectMapper getObjectMapper() {
return objectMapper; } @Override public IdentityLinkServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public IdentityLinkEventHandler getIdentityLinkEventHandler() { return identityLinkEventHandler; } public IdentityLinkServiceConfiguration setIdentityLinkEventHandler(IdentityLinkEventHandler identityLinkEventHandler) { this.identityLinkEventHandler = identityLinkEventHandler; return this; } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\IdentityLinkServiceConfiguration.java
2
请完成以下Java代码
public int getLevelNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LevelNo); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_ValueNoCheck (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()); } public I_PA_ReportLine getPA_ReportLine() throws RuntimeException { return (I_PA_ReportLine)MTable.get(getCtx(), I_PA_ReportLine.Table_Name) .getPO(getPA_ReportLine_ID(), get_TrxName()); } /** Set Report Line. @param PA_ReportLine_ID Report Line */ public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */
public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ 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\org\compiere\model\X_T_Report.java
1
请完成以下Java代码
public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; } @Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height;
} @Override public void setHeight(int height) { this.height = height; } public List<String> getFlowNodeIds() { if (flowNodeIds == null) { flowNodeIds = new ArrayList<>(); } return flowNodeIds; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\Lane.java
1
请完成以下Java代码
public class C_BPartner_Location { @CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_IsBillToDefault }) public void updateBillToColumn(final I_C_BPartner_Location location, final ICalloutField field) { if (location == null) { return; } // 07224 // In case the isBillToDefault flag is set on true, the IsBillTo must be true, as well // The field will also be read only (set readonly logic in database) final boolean isBillToDefault = location.isBillToDefault(); if (!isBillToDefault) { return; } location.setIsBillTo(true); } @CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_IsShipToDefault }) public void updateShipToColumn(final I_C_BPartner_Location location, final ICalloutField field) { if (location == null) { return; } // 07224 // In case the isBillToDefault flag is set on true, the IsBillTo must be true, as well // The field will also be read only (set readonly logic in database) final boolean isShipToDefault = location.isShipToDefault(); if (!isShipToDefault) { return; } location.setIsShipTo(true); } @CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_C_Location_ID, I_C_BPartner_Location.COLUMNNAME_Name }) public void updateAddressString(final I_C_BPartner_Location bpLocation) { final int locationId = bpLocation.getC_Location_ID(); if (locationId <= 0) {
return; } final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setAddress(bpLocation); } @CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_ValidFrom}) public void updatePreviousId(final I_C_BPartner_Location bpLocation) { final int bPartnerId = bpLocation.getC_BPartner_ID(); if (bPartnerId <= 0) { return; } if (bpLocation.getValidFrom() == null) { return; } final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); bpartnerBL.setPreviousIdIfPossible(bpLocation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\callout\C_BPartner_Location.java
1
请完成以下Java代码
public boolean process(Sentence sentence) { Utility.normalize(sentence); instanceList.add(PerceptronTrainer.this.createInstance(sentence, mutableFeatureMap)); return false; } }); Instance[] instances = new Instance[instanceList.size()]; instanceList.toArray(instances); return instances; } private static DoubleArrayTrie<Integer> loadDictionary(String trainingFile, String dictionaryFile) throws IOException { FrequencyMap dictionaryMap = new FrequencyMap(); if (dictionaryFile == null) { out.printf("从训练文件%s中统计词库...\n", trainingFile); loadWordFromFile(trainingFile, dictionaryMap, true); } else { out.printf("从外部词典%s中加载词库...\n", trainingFile); loadWordFromFile(dictionaryFile, dictionaryMap, false); } DoubleArrayTrie<Integer> dat = new DoubleArrayTrie<Integer>(); dat.build(dictionaryMap); out.printf("加载完毕,词库总词数:%d,总词频:%d\n", dictionaryMap.size(), dictionaryMap.totalFrequency); return dat; } public Result train(String trainingFile, String modelFile) throws IOException { return train(trainingFile, trainingFile, modelFile); } public Result train(String trainingFile, String developFile, String modelFile) throws IOException { return train(trainingFile, developFile, modelFile, 0.1, 50, Runtime.getRuntime().availableProcessors()); } private static void loadWordFromFile(String path, FrequencyMap storage, boolean segmented) throws IOException {
BufferedReader br = IOUtility.newBufferedReader(path); String line; while ((line = br.readLine()) != null) { if (segmented) { for (String word : IOUtility.readLineToArray(line)) { storage.add(word); } } else { line = line.trim(); if (line.length() != 0) { storage.add(line); } } } br.close(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronTrainer.java
1
请完成以下Java代码
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gesamtbetrag. @param TotalAmt Gesamtbetrag */ @Override
public void setTotalAmt (java.math.BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Gesamtbetrag. @return Gesamtbetrag */ @Override public java.math.BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate.java
1
请完成以下Java代码
public int getCM_Ad_Cat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Template getCM_Template() throws RuntimeException { return (I_CM_Template)MTable.get(getCtx(), I_CM_Template.Table_Name) .getPO(getCM_Template_ID(), get_TrxName()); } /** Set Template. @param CM_Template_ID Template defines how content is displayed */ public void setCM_Template_ID (int CM_Template_ID) { if (CM_Template_ID < 1) set_Value (COLUMNNAME_CM_Template_ID, null); else set_Value (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID)); } /** Get Template. @return Template defines how content is displayed */ public int getCM_Template_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name.
@param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template_Ad_Cat.java
1
请在Spring Boot框架中完成以下Java代码
public class TodoService { @Autowired private Dao<Todo> todoDao; private Todo todo = new Todo(); public void save() { todoDao.save(todo); todo = new Todo(); } public Collection<Todo> getAllTodo() { return todoDao.getAll(); } public Collection<Todo> getAllTodoSortedByPriority() { return todoDao.getAll() .stream() .sorted(Comparator.comparingInt(Todo::getId))
.collect(Collectors.toList()); } public int saveTodo(Todo todo) { validate(todo); return todoDao.save(todo); } private void validate(Todo todo) { // Details omitted } public Todo getTodo() { return todo; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\jsfapplication\service\TodoService.java
2
请完成以下Java代码
public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(PickingConstantsV2.WINDOWID_PackageableView) .setCaption("Picking") // TODO: trl .setAllowOpeningRowDetails(false) .setFilters(getFilterDescriptorsProvider().getAll()) .addElementsFromViewRowClass(PackageableRow.class, viewDataType) .build(); } private DocumentFilterDescriptorsProvider getFilterDescriptorsProvider() { return PackageableViewFilters.getDescriptors(); } @Override public PackageableView createView(final @NonNull CreateViewRequest request) { final ViewId viewId = request.getViewId(); viewId.assertWindowId(PickingConstantsV2.WINDOWID_PackageableView); final DocumentFilterDescriptorsProvider filterDescriptors = getFilterDescriptorsProvider(); final PackageableRowsData rowsData = rowsRepo.newPackageableRowsData() .filters(request.getFiltersUnwrapped(filterDescriptors)) .stickyFilters(request.getStickyFilters()) .build(); return PackageableView.builder() .viewId(viewId) .rowsData(rowsData) .relatedProcessDescriptors(getRelatedProcessDescriptors()) .viewFilterDescriptors(filterDescriptors) .build(); }
private Iterable<? extends RelatedProcessDescriptor> getRelatedProcessDescriptors() { return ImmutableList.of( createProcessDescriptor(PackageablesView_OpenProductsToPick.class), createProcessDescriptor(PackageablesView_UnlockFromLoggedUser.class), createProcessDescriptor(PackageablesView_UnlockAll.class), createProcessDescriptor(PackageablesView_PrintPicklist.class)); } private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass); if (processId == null) { throw new AdempiereException("No processId found for " + processClass); } return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableViewFactoryV2.java
1
请完成以下Java代码
public class ProducerApp { public static void main(String[] args) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.digest(new byte[256]); byte[] dummy = digest.digest(); int hashLen = dummy.length; long size = Long.parseLong(args[1]); MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); System.out.println("Starting producer iterations..."); long start = System.currentTimeMillis(); long iterations = 0; int capacity = shm.capacity(); Random rnd = new Random(); while(System.currentTimeMillis() - start < 30000) { for (int i = 0; i < capacity - hashLen; i++) { byte value = (byte) (rnd.nextInt(256) & 0x00ff); digest.update(value); shm.put(i, value); } // Write hash at the end byte[] hash = digest.digest(); shm.position(capacity - hashLen); shm.put(hash); iterations++; } System.out.printf("%d iterations run\n", iterations);
System.out.println("Press <enter> to exit"); System.console().readLine(); } private static long getBufferAddress(MappedByteBuffer shm) { try { Class<?> cls = shm.getClass(); Method maddr = cls.getMethod("address"); maddr.setAccessible(true); Long addr = (Long) maddr.invoke(shm); if ( addr == null ) { throw new RuntimeException("Unable to retrieve buffer's address"); } return addr; } catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } } private static MappedByteBuffer createSharedMemory(String path, long size) { try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(), EnumSet.of( StandardOpenOption.CREATE, StandardOpenOption.SPARSE, StandardOpenOption.WRITE, StandardOpenOption.READ))) { return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); } catch( IOException ioe) { throw new RuntimeException(ioe); } } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\sharedmem\ProducerApp.java
1
请完成以下Java代码
public void dispatchEmail(String emailId, String subject, String body) throws IOException { Email toEmail = new Email(emailId); Content content = new Content("text/plain", body); Mail mail = new Mail(fromEmail, subject, toEmail, content); sendRequest(mail); } public void dispatchEmail(String emailId, String subject, String body, List<MultipartFile> files) throws IOException { Email toEmail = new Email(emailId); Content content = new Content("text/plain", body); Mail mail = new Mail(fromEmail, subject, toEmail, content); if (files != null && !files.isEmpty()) { for (MultipartFile file : files) { Attachments attachment = createAttachment(file); mail.addAttachments(attachment); } } sendRequest(mail); } public void dispatchHydrationAlert(String emailId, String username) throws IOException { Email toEmail = new Email(emailId); String templateId = sendGridConfigurationProperties.getHydrationAlertNotification().getTemplateId(); DynamicTemplatePersonalization personalization = new DynamicTemplatePersonalization(); personalization.add("name", username); personalization.add("lastDrinkTime", "Way too long ago"); personalization.add("hydrationStatus", "Thirsty as a camel"); personalization.addTo(toEmail); Mail mail = new Mail(); mail.setFrom(fromEmail); mail.setTemplateId(templateId); mail.addPersonalization(personalization);
sendRequest(mail); } private void sendRequest(Mail mail) throws IOException { Request request = new Request(); request.setMethod(Method.POST); request.setEndpoint(EMAIL_ENDPOINT); request.setBody(mail.build()); sendGrid.api(request); } private Attachments createAttachment(MultipartFile file) throws IOException { byte[] encodedFileContent = Base64.getEncoder().encode(file.getBytes()); Attachments attachment = new Attachments(); attachment.setDisposition("attachment"); attachment.setType(file.getContentType()); attachment.setFilename(file.getOriginalFilename()); attachment.setContent(new String(encodedFileContent, StandardCharsets.UTF_8)); return attachment; } }
repos\tutorials-master\saas-modules\sendgrid\src\main\java\com\baeldung\sendgrid\EmailDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
public class X_M_Picking_Config extends org.compiere.model.PO implements I_M_Picking_Config, org.compiere.model.I_Persistent { private static final long serialVersionUID = 462743628L; /** Standard Constructor */ public X_M_Picking_Config (final Properties ctx, final int M_Picking_Config_ID, @Nullable final String trxName) { super (ctx, M_Picking_Config_ID, trxName); } /** Load Constructor */ public X_M_Picking_Config (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setIsAllowOverdelivery (final boolean IsAllowOverdelivery) { set_Value (COLUMNNAME_IsAllowOverdelivery, IsAllowOverdelivery); } @Override public boolean isAllowOverdelivery() { return get_ValueAsBoolean(COLUMNNAME_IsAllowOverdelivery); } @Override public void setIsAutoProcess (final boolean IsAutoProcess) { set_Value (COLUMNNAME_IsAutoProcess, IsAutoProcess); } @Override public boolean isAutoProcess() { return get_ValueAsBoolean(COLUMNNAME_IsAutoProcess); } @Override public void setIsForbidAggCUsForDifferentOrders (final boolean IsForbidAggCUsForDifferentOrders) { set_Value (COLUMNNAME_IsForbidAggCUsForDifferentOrders, IsForbidAggCUsForDifferentOrders); } @Override public boolean isForbidAggCUsForDifferentOrders() { return get_ValueAsBoolean(COLUMNNAME_IsForbidAggCUsForDifferentOrders); }
@Override public void setM_Picking_Config_ID (final int M_Picking_Config_ID) { if (M_Picking_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID); } @Override public int getM_Picking_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID); } /** * WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772 * Reference name: WEBUI_PickingTerminal_ViewProfile */ public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772; /** groupByProduct = groupByProduct */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct"; /** Group by Order = groupByOrder */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder"; @Override public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile) { set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile); } @Override public java.lang.String getWEBUI_PickingTerminal_ViewProfile() { return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java
2
请完成以下Java代码
public RemittanceInformation5CH createRemittanceInformation5CH() { return new RemittanceInformation5CH(); } /** * Create an instance of {@link ServiceLevel8Choice } * */ public ServiceLevel8Choice createServiceLevel8Choice() { return new ServiceLevel8Choice(); } /** * Create an instance of {@link StructuredRegulatoryReporting3 } * */ public StructuredRegulatoryReporting3 createStructuredRegulatoryReporting3() { return new StructuredRegulatoryReporting3(); } /**
* Create an instance of {@link StructuredRemittanceInformation7 } * */ public StructuredRemittanceInformation7 createStructuredRemittanceInformation7() { return new StructuredRemittanceInformation7(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "http://www.six-interbank-clearing.com/de/pain.001.001.03.ch.02.xsd", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ObjectFactory.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsCountByQueryCriteria(this); } public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsByQueryCriteria(this, page); } // getter ////////////////////////////////// public boolean isTenantIdSet() { return isTenantIdSet; } public String getJobId() { return jobId; } public String getJobExceptionMessage() { return jobExceptionMessage; } public String getJobDefinitionId() { return jobDefinitionId; } public String getJobDefinitionType() { return jobDefinitionType; } public String getJobDefinitionConfiguration() { return jobDefinitionConfiguration; } public String[] getActivityIds() { return activityIds; }
public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Java代码
public MNewsItem[] getNewsItems(String where) { ArrayList<MNewsItem> list = new ArrayList<MNewsItem>(); String sql = "SELECT * FROM CM_NewsItem WHERE CM_NewsChannel_ID=? AND IsActive='Y'"; if (where != null && where.length() > 0) sql += " AND " + where; sql += " ORDER BY pubDate DESC"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, this.get_TrxName()); pstmt.setInt (1, this.get_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add(new MNewsItem(this.getCtx(), rs, this.get_TrxName())); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } MNewsItem[] retValue = new MNewsItem[list.size ()]; list.toArray (retValue); return retValue; } // getNewsItems /** * Get rss2 Channel Code * @param xmlCode xml * @param showFutureItems future * @return channel code */ public StringBuffer get_rss2ChannelCode(StringBuffer xmlCode, boolean showFutureItems) { if (this != null) // never null ?? { xmlCode.append ("<channel>"); xmlCode.append (" <title><![CDATA[" + this.getName () + "]]></title>"); xmlCode.append (" <link>" + this.getLink () + "</link>"); xmlCode.append (" <description><![CDATA[" + this.getDescription () + "]]></description>"); xmlCode.append (" <language>" + this.getAD_Language () + "</language>"); xmlCode.append (" <copyright>" + "" + "</copyright>"); xmlCode.append (" <pubDate>" + this.getCreated () + "</pubDate>"); xmlCode.append (" <image>"); xmlCode.append (" <url>" + "" + "</url>"); xmlCode.append (" <title><![CDATA[" + "" + "]]></title>"); xmlCode.append (" <link>" + "" + "</link>"); xmlCode.append (" </image>");
String whereClause = ""; if (!showFutureItems) whereClause = "now()>pubdate"; MNewsItem[] theseItems = getNewsItems(whereClause); for(int i=0;i<theseItems.length;i++) xmlCode=theseItems[i].get_rss2ItemCode(xmlCode,this); xmlCode.append ("</channel>"); } return xmlCode; } /** * After Save. * Insert * - create / update index * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; reIndex(newRecord); return success; } // afterSave public void reIndex(boolean newRecord) { String [] toBeIndexed = new String[2]; toBeIndexed[0] = this.getName(); toBeIndexed[1] = this.getDescription(); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), getCM_WebProject_ID(), this.getUpdated()); } } //
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNewsChannel.java
1
请完成以下Java代码
public void setupCallouts() { final IProgramaticCalloutProvider calloutProvider = Services.get(IProgramaticCalloutProvider.class); calloutProvider.registerAnnotatedCallout(new de.metas.tourplanning.callout.C_Order()); } /** * Search for matching {@link I_M_DeliveryDay} and set order's preparation date from it. */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Order.COLUMNNAME_C_BPartner_Location_ID, I_C_Order.COLUMNNAME_DatePromised, I_C_Order.COLUMNNAME_PreparationDate }) public void setPreparationDate(final I_C_Order order) { // // If PreparationDate was explicitelly set by user, don't change it if (isValueChanged(order, I_C_Order.COLUMNNAME_PreparationDate) && order.getPreparationDate() != null) { return; } // task 08931: if the order is created by a user, that user needs to make sure a proper preparation date is in place // Goal: motivate/educate the users to maintain proper tour planning masterdata to reduce trouble in the further stages of operative business. // However, if the order is created by the system (e.g. from EDI-olCands), we allow a fallback to DatePromised final boolean fallbackToDatePromised = !isUIAction(order); orderDeliveryDayBL.setPreparationDateAndTour(order, fallbackToDatePromised); } /** * Make sure the PreparationDate is set */
@DocValidate(timings = { ModelValidator.TIMING_AFTER_PREPARE }) public void assertValidPreparationDate(final I_C_Order order) { if (!order.isSOTrx()) { return; // task 09000: nothing to do, the PreparationDate is only relevant for sales orders. } // // Make sure the PreparationDate is set final Timestamp preparationDate = order.getPreparationDate(); if (preparationDate == null) { throw new FillMandatoryException(I_C_Order.COLUMNNAME_PreparationDate); } // task 09000: Actually, this is what we want, but commented out for now, because then the fallback won't work. // TODO: come up with another solution, e.g. no fallback and eval/fix this already in the OLCands // @formatter:off // // Make sure the PreparationDate not equals DatePromised, // because in that case, for sure it's an error which will strike the user later. // final Timestamp datePromised = order.getSupplyDate(); // if (Check.equals(preparationDate, datePromised)) // { // throw new AdempiereException("@Invalid@ @DatePromised@ = @PreparationDate@"); // } // @formatter:on } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\C_Order.java
1
请完成以下Java代码
public void setSystemStatus (java.lang.String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } /** Get System Status. @return Status of the system - Support priority depends on system status */ @Override public java.lang.String getSystemStatus () { return (java.lang.String)get_Value(COLUMNNAME_SystemStatus); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version)
{ set_ValueNoCheck (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } /** Set ZK WebUI URL. @param WebUI_URL ZK WebUI root URL */ @Override public void setWebUI_URL (java.lang.String WebUI_URL) { set_Value (COLUMNNAME_WebUI_URL, WebUI_URL); } /** Get ZK WebUI URL. @return ZK WebUI root URL */ @Override public java.lang.String getWebUI_URL () { return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java
1
请在Spring Boot框架中完成以下Java代码
public void persistAuthorsAndBooks() { List<Author> authors = new ArrayList<>(); for (int i = 0; i < 40; i++) { Author author = new Author(); author.setName("Name_" + i); author.setGenre("Genre_" + i); author.setAge(18 + i); for (int j = 0; j < 5; j++) { Book book = new Book(); book.setTitle("Title: " + j); book.setIsbn("Isbn: " + j); author.addBook(book); } authors.add(author); } authorRepository.saveAll(authors); } @Transactional public void updateAuthorsAndBooks() { List<Author> authors = authorRepository.fetchAll(); for (Author author : authors) {
author.setAge(author.getAge() + 1); for (Book book : author.getBooks()) { book.setIsbn(book.getIsbn() + "-2020"); } } } @Transactional public void updateBooksAndAuthors() { List<Book> books = bookRepository.fetchAll(); for (Book book : books) { book.setIsbn(book.getIsbn() + "-2021"); Author author = book.getAuthor(); author.setAge(author.getAge() + 1); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchUpdateOrder\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public static JsonDhlAddress getConsigneeAddress(@NonNull final Address address, @Nullable final ContactPerson deliveryContact) { final JsonDhlAddress.JsonDhlAddressBuilder addressBuilder = JsonDhlAddress.builder(); mapCommonAddressFields(addressBuilder, address); addressBuilder.additionalAddressInformation1(StringUtils.trunc(address.getStreet2(), 50, ON_TRUNC)); if (deliveryContact != null) { final String email = deliveryContact.getEmailAddress(); if (Check.isNotBlank(email)) { Check.assume(email.length() > 2, "email has minimum three characters"); addressBuilder.email(StringUtils.trunc(deliveryContact.getEmailAddress(), 80, ON_TRUNC)); } addressBuilder.phone(StringUtils.trunc(deliveryContact.getPhoneAsStringOrNull(), 20, ON_TRUNC)); } return addressBuilder.build(); } private static boolean isValidAlpha3CountryCode(@NonNull final String code) { if (code.length() != 3) { return false; } for (final String iso : Locale.getISOCountries()) { final Locale locale = new Locale("", iso); if (locale.getISO3Country().equalsIgnoreCase(code)) { return true; } } return false; } private static void mapCommonAddressFields(@NonNull final JsonDhlAddress.JsonDhlAddressBuilder addressBuilder, @NonNull final Address address)
{ final String country = address.getCountry().getAlpha3(); final String postalCode = StringUtils.trunc(address.getZipCode(), 10, ON_TRUNC); // Validate ISO 3166-1 alpha-3 country code Check.assume(isValidAlpha3CountryCode(country), "Invalid ISO alpha-3 country code: " + country); if (!IRL_COUNTRY.equals(country)) { Check.assumeNotNull(postalCode, "postalCode is not NULL"); Check.assume(postalCode.length() > 2, "postalCode has minimum three characters"); } addressBuilder.name1(StringUtils.trunc(address.getCompanyName1(), 50, ON_TRUNC)) .name2(StringUtils.trunc(address.getCompanyName2(), 50, ON_TRUNC)) .addressStreet(StringUtils.trunc(address.getStreet1(), 50, ON_TRUNC)) .addressHouse(StringUtils.trunc(address.getHouseNo(), 10, ON_TRUNC)) .postalCode(StringUtils.trim(postalCode)) .city(StringUtils.trunc(address.getCity(), 40, ON_TRUNC)) .country(country); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlAddressMapper.java
1
请完成以下Java代码
public I_CM_Ad_Cat getCM_Ad_Cat() throws RuntimeException { return (I_CM_Ad_Cat)MTable.get(getCtx(), I_CM_Ad_Cat.Table_Name) .getPO(getCM_Ad_Cat_ID(), get_TrxName()); } /** Set Advertisement Category. @param CM_Ad_Cat_ID Advertisement Category like Banner Homepage */ public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID) { if (CM_Ad_Cat_ID < 1) set_Value (COLUMNNAME_CM_Ad_Cat_ID, null); else set_Value (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID)); } /** Get Advertisement Category. @return Advertisement Category like Banner Homepage */ public int getCM_Ad_Cat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Template getCM_Template() throws RuntimeException { return (I_CM_Template)MTable.get(getCtx(), I_CM_Template.Table_Name) .getPO(getCM_Template_ID(), get_TrxName()); } /** Set Template. @param CM_Template_ID Template defines how content is displayed */ public void setCM_Template_ID (int CM_Template_ID) { if (CM_Template_ID < 1) set_Value (COLUMNNAME_CM_Template_ID, null); else set_Value (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID)); } /** Get Template. @return Template defines how content is displayed */ public int getCM_Template_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template_Ad_Cat.java
1
请在Spring Boot框架中完成以下Java代码
public String findPreviousCaseDefinitionId(String caseDefinitionKey, Integer version, String tenantId) { Map<String, Object> params = new HashMap<String, Object>(); params.put("key", caseDefinitionKey); params.put("version", version); params.put("tenantId", tenantId); return (String) getDbEntityManager().selectOne("selectPreviousCaseDefinitionId", params); } @SuppressWarnings("unchecked") public List<CaseDefinition> findCaseDefinitionsByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery, Page page) { configureCaseDefinitionQuery(caseDefinitionQuery); return getDbEntityManager().selectList("selectCaseDefinitionsByQueryCriteria", caseDefinitionQuery, page); } public long findCaseDefinitionCountByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery) { configureCaseDefinitionQuery(caseDefinitionQuery); return (Long) getDbEntityManager().selectOne("selectCaseDefinitionCountByQueryCriteria", caseDefinitionQuery); } @SuppressWarnings("unchecked") public List<CaseDefinition> findCaseDefinitionByDeploymentId(String deploymentId) { return getDbEntityManager().selectList("selectCaseDefinitionByDeploymentId", deploymentId); } protected void configureCaseDefinitionQuery(CaseDefinitionQueryImpl query) { getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public CaseDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestCaseDefinitionByKey(key); }
@Override public CaseDefinitionEntity findLatestDefinitionById(String id) { return findCaseDefinitionById(id); } @Override public CaseDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(CaseDefinitionEntity.class, definitionId); } @Override public CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId); } @Override public CaseDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { throw new UnsupportedOperationException("Currently finding case definition by version tag and tenant is not implemented."); } @Override public CaseDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findCaseDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionManager.java
2
请在Spring Boot框架中完成以下Java代码
class BusinessRuleLogRepository { public void create(final BusinessRuleLogEntryRequest request) { final I_AD_BusinessRule_Log record = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_BusinessRule_Log.class); record.setLevel(request.getLevel().toString()); record.setMsgText(request.getMessage()); record.setAD_Issue_ID(AdIssueId.toRepoId(request.getErrorId())); if (request.getDuration() != null) { record.setDurationMillis((int)request.getDuration().toMillis()); } record.setModule(request.getModuleName()); record.setAD_BusinessRule_ID(BusinessRuleId.toRepoId(request.getBusinessRuleId())); record.setAD_BusinessRule_Precondition_ID(BusinessRulePreconditionId.toRepoId(request.getPreconditionId()));
record.setAD_BusinessRule_Trigger_ID(BusinessRuleTriggerId.toRepoId(request.getTriggerId())); final TableRecordReference sourceRecordRef = request.getSourceRecordRef(); record.setSource_Table_ID(sourceRecordRef != null ? sourceRecordRef.getAD_Table_ID() : -1); record.setSource_Record_ID(sourceRecordRef != null ? sourceRecordRef.getRecord_ID() : -1); final TableRecordReference targetRecordRef = request.getTargetRecordRef(); record.setTarget_Table_ID(targetRecordRef != null ? targetRecordRef.getAD_Table_ID() : -1); record.setTarget_Record_ID(targetRecordRef != null ? targetRecordRef.getRecord_ID() : -1); record.setAD_BusinessRule_Event_ID(BusinessRuleEventId.toRepoId(request.getEventId())); InterfaceWrapperHelper.save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\log\BusinessRuleLogRepository.java
2
请完成以下Java代码
public ModelInstance parseModelFromStream(InputStream inputStream) { DomDocument document = null; synchronized(documentBuilderFactory) { document = DomUtil.parseInputStream(documentBuilderFactory, inputStream); } validateModel(document); return createModelInstance(document); } public ModelInstance getEmptyModel() { DomDocument document = null; synchronized(documentBuilderFactory) { document = DomUtil.getEmptyDocument(documentBuilderFactory); } return createModelInstance(document); } /** * Validate DOM document * * @param document the DOM document to validate */ public void validateModel(DomDocument document) { Schema schema = getSchema(document); if (schema == null) { return; } Validator validator = schema.newValidator(); try { synchronized(document) { validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (SAXException e) { throw new ModelValidationException("DOM document is not valid", e);
} } protected Schema getSchema(DomDocument document) { DomElement rootElement = document.getRootElement(); String namespaceURI = rootElement.getNamespaceURI(); return schemas.get(namespaceURI); } protected void addSchema(String namespaceURI, Schema schema) { schemas.put(namespaceURI, schema); } protected Schema createSchema(String location, ClassLoader classLoader) { URL cmmnSchema = ReflectUtil.getResource(location, classLoader); try { return schemaFactory.newSchema(cmmnSchema); } catch (SAXException e) { throw new ModelValidationException("Unable to parse schema:" + cmmnSchema); } } protected abstract ModelInstance createModelInstance(DomDocument document); }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\parser\AbstractModelParser.java
1
请完成以下Java代码
public class UseLocalTime { LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { return LocalTime.of(hour, min, seconds); } LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min) { return LocalTime.of(hour, min); } LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { return LocalTime.parse(timeRepresentation); } private LocalTime getLocalTimeFromClock() {
return LocalTime.now(); } LocalTime addAnHour(LocalTime localTime) { return localTime.plus(1, ChronoUnit.HOURS); } int getHourFromLocalTime(LocalTime localTime) { return localTime.getHour(); } LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { return localTime.withMinute(minute); } }
repos\tutorials-master\core-java-modules\core-java-8-datetime\src\main\java\com\baeldung\datetime\UseLocalTime.java
1
请完成以下Java代码
default void putContext(final String name, final String value) { Env.setContext(getCtx(), name, value); } /** * Put to window context. */ default void putWindowContext(final String name, final String value) { Env.setContext(getCtx(), getWindowNo(), name, value); } default void putContext(final String name, final boolean value) { Env.setContext(getCtx(), getWindowNo(), name, value); } /** * Put to window context. */ default void putWindowContext(final String name, final boolean value) { Env.setContext(getCtx(), getWindowNo(), name, value); } default void putContext(final String name, final java.util.Date value) {
Env.setContext(getCtx(), getWindowNo(), name, value); } /** * Put to window context. */ default void putContext(final String name, final int value) { Env.setContext(getCtx(), getWindowNo(), name, value); } default int getGlobalContextAsInt(final String name) { return Env.getContextAsInt(getCtx(), name); } default int getTabInfoContextAsInt(final String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), Env.TAB_INFO, name); } default boolean getContextAsBoolean(final String name) { return DisplayType.toBoolean(Env.getContext(getCtx(), getWindowNo(), name)); } boolean isLookupValuesContainingId(@NonNull RepoIdAware id); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\ICalloutField.java
1
请完成以下Java代码
public boolean isLocked(final int adTableId, final int recordId) { return getLockDatabase().isLocked(adTableId, recordId, LockOwner.ANY); } @Override public boolean isLocked(final Class<?> modelClass, final int recordId) { return getLockDatabase().isLocked(modelClass, recordId, LockOwner.ANY); } @Override public boolean isLocked(final Class<?> modelClass, final int recordId, final LockOwner lockOwner) { return getLockDatabase().isLocked(modelClass, recordId, lockOwner); } @Override public boolean isLocked(final Object model) { return getLockDatabase().isLocked(model, LockOwner.ANY); } @Override public final <T> T retrieveAndLock(final IQuery<T> query, final Class<T> clazz) { return getLockDatabase().retrieveAndLock(query, clazz); } @Override public final String getNotLockedWhereClause(final String tableName, final String joinColumnNameFQ) { return getLockDatabase().getNotLockedWhereClause(tableName, joinColumnNameFQ); } @Override public final <T> IQueryFilter<T> getNotLockedFilter(final Class<T> modelClass) { return getLockDatabase().getNotLockedFilter(modelClass); } @Override public String getLockedWhereClause(final Class<?> modelClass, final String joinColumnNameFQ, final LockOwner lockOwner) { return getLockDatabase().getLockedWhereClause(modelClass, joinColumnNameFQ, lockOwner); } @Override public final <T> IQueryFilter<T> getLockedByFilter(final Class<T> modelClass, final LockOwner lockOwner) { return getLockDatabase().getLockedByFilter(modelClass, lockOwner); } @Override
public ILock getExistingLockForOwner(final LockOwner lockOwner) { return getLockDatabase().retrieveLockForOwner(lockOwner); } @Override public <T> IQueryFilter<T> getNotLockedFilter(@NonNull String modelTableName, @NonNull String joinColumnNameFQ) { return getLockDatabase().getNotLockedFilter(modelTableName, joinColumnNameFQ); } @Override public <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider) { return getLockDatabase().getLockedRecordsQueryBuilder(modelClass, contextProvider); } @Override public int removeAutoCleanupLocks() { return getLockDatabase().removeAutoCleanupLocks(); } @Override public <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz) { return getLockDatabase().retrieveAndLockMultipleRecords(query, clazz); } @Override public <T> IQuery<T> addNotLockedClause(final IQuery<T> query) { return getLockDatabase().addNotLockedClause(query); } @Override public ExistingLockInfo getLockInfo(final TableRecordReference tableRecordReference, final LockOwner lockOwner) { return getLockDatabase().getLockInfo(tableRecordReference, lockOwner); } @Override public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(final @NonNull TableRecordReferenceSet recordRefs) { return getLockDatabase().getLockInfosByRecordIds(recordRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockManager.java
1
请完成以下Java代码
public void saveAll(@NonNull final Collection<BPartnerProductStats> stats) { stats.forEach(this::save); } public void save(@NonNull final BPartnerProductStats stats) { I_C_BPartner_Product_Stats record = null; if (stats.getRepoId() > 0) { record = load(stats.getRepoId(), I_C_BPartner_Product_Stats.class); } if (record == null) { record = newInstance(I_C_BPartner_Product_Stats.class); record.setAD_Org_ID(OrgId.ANY.getRepoId()); record.setC_BPartner_ID(stats.getBpartnerId().getRepoId()); record.setM_Product_ID(stats.getProductId().getRepoId()); } record.setLastShipDate(TimeUtil.asTimestamp(stats.getLastShipmentDate())); record.setLastReceiptDate(TimeUtil.asTimestamp(stats.getLastReceiptDate())); updateRecordLastSalesInvoiceInfo(record, stats.getLastSalesInvoice());
saveRecord(record); stats.setRepoId(record.getC_BPartner_Product_Stats_ID()); } private static void updateRecordLastSalesInvoiceInfo(@NonNull final I_C_BPartner_Product_Stats record, @Nullable final LastInvoiceInfo lastSalesInvoiceInfo) { final InvoiceId invoiceId = lastSalesInvoiceInfo != null ? lastSalesInvoiceInfo.getInvoiceId() : null; record.setLastSales_Invoice_ID(InvoiceId.toRepoId(invoiceId)); final LocalDate invoiceDate = lastSalesInvoiceInfo != null ? lastSalesInvoiceInfo.getInvoiceDate() : null; record.setLastSalesInvoiceDate(TimeUtil.asTimestamp(invoiceDate)); final Money price = lastSalesInvoiceInfo != null ? lastSalesInvoiceInfo.getPrice() : null; record.setLastSalesPrice(price != null ? price.toBigDecimal() : null); record.setLastSalesPrice_Currency_ID(price != null ? price.getCurrencyId().getRepoId() : -1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsRepository.java
1
请完成以下Java代码
protected void runJobLogic(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) { // We need to remove the job handler configuration externalWorkerJob.setJobHandlerConfiguration(null); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); VariableServiceConfiguration variableServiceConfiguration = processEngineConfiguration.getVariableServiceConfiguration(); VariableService variableService = variableServiceConfiguration.getVariableService(); ExecutionEntity executionEntity = processEngineConfiguration.getExecutionEntityManager().findById(externalWorkerJob.getExecutionId()); ExternalWorkerServiceTask externalWorkerServiceTask = (ExternalWorkerServiceTask) executionEntity.getCurrentFlowElement(); List<IOParameter> outParameters = externalWorkerServiceTask.getOutParameters(); if (outParameters != null && !outParameters.isEmpty()) { VariableContainerWrapper temporaryVariableContainer = new VariableContainerWrapper(variables); for (IOParameter outParameter : outParameters) { Object variableValue; if (StringUtils.isNotEmpty(outParameter.getSource())) { variableValue = temporaryVariableContainer.getVariable(outParameter.getSource()); } else { Expression outParameterExpression = processEngineConfiguration.getExpressionManager() .createExpression(outParameter.getSourceExpression()); variableValue = outParameterExpression.getValue(temporaryVariableContainer); } addVariable(externalWorkerJob, variableService, outParameter.getTarget(), variableValue); } } else if (variables != null && !variables.isEmpty()) { for (Map.Entry<String, Object> variableEntry : variables.entrySet()) {
String varName = variableEntry.getKey(); Object varValue = variableEntry.getValue(); addVariable(externalWorkerJob, variableService, varName, varValue); } } moveExternalWorkerJobToExecutableJob(externalWorkerJob, commandContext); } protected void addVariable(ExternalWorkerJobEntity externalWorkerJob, VariableService variableService, String varName, Object varValue) { VariableInstanceEntity variableInstance = variableService.createVariableInstance(varName); variableInstance.setScopeId(externalWorkerJob.getProcessInstanceId()); variableInstance.setSubScopeId(externalWorkerJob.getExecutionId()); variableInstance.setScopeType(ScopeTypes.BPMN_EXTERNAL_WORKER); variableService.insertVariableInstanceWithValue(variableInstance, varValue, externalWorkerJob.getTenantId()); CountingEntityUtil.handleInsertVariableInstanceEntityCount(variableInstance); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ExternalWorkerJobCompleteCmd.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; this.description = map.get(this.key); } public String getValue() { return value; } public void setValue(String value) { this.value = value;
} public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "RedisInfo{" + "key='" + key + '\'' + ", value='" + value + '\'' + ", desctiption='" + description + '\'' + '}'; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\domain\RedisInfo.java
1
请完成以下Java代码
public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; } @Override public String getDerivedFromRoot() { return null;
} @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "AppDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Receiver { private static final Logger log = LoggerFactory.getLogger(Receiver.class); /** * FANOUT广播队列监听一. * * @param message the message * @param channel the channel * @throws IOException the io exception 这里异常需要处理 */ @RabbitListener(queues = {"FANOUT_QUEUE_A"}) public void on(Message message, Channel channel) throws IOException { channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); log.debug("FANOUT_QUEUE_A " + new String(message.getBody())); } /** * FANOUT广播队列监听二. * * @param message the message * @param channel the channel
* @throws IOException the io exception 这里异常需要处理 */ @RabbitListener(queues = {"FANOUT_QUEUE_B"}) public void t(Message message, Channel channel) throws IOException { channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); log.debug("FANOUT_QUEUE_B " + new String(message.getBody())); } /** * DIRECT模式. * * @param message the message * @param channel the channel * @throws IOException the io exception 这里异常需要处理 */ @RabbitListener(queues = {"DIRECT_QUEUE"}) public void message(Message message, Channel channel) throws IOException { channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); log.debug("DIRECT " + new String(message.getBody())); } }
repos\SpringBootBucket-master\springboot-rabbitmq\src\main\java\com\xncoding\pos\mq\Receiver.java
2
请在Spring Boot框架中完成以下Java代码
static class CacheManagerEntityManagerFactoryDependsOnConfiguration { } static class CacheManagerEntityManagerFactoryDependsOnPostProcessor extends EntityManagerFactoryDependsOnPostProcessor { CacheManagerEntityManagerFactoryDependsOnPostProcessor() { super("cacheManager"); } } /** * Bean used to validate that a CacheManager exists and provide a more meaningful * exception. */ static class CacheManagerValidator implements InitializingBean { private final CacheProperties cacheProperties; private final ObjectProvider<CacheManager> cacheManager; CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) { this.cacheProperties = cacheProperties; this.cacheManager = cacheManager; } @Override public void afterPropertiesSet() { Assert.state(this.cacheManager.getIfAvailable() != null, () -> "No cache manager could be auto-configured, check your configuration (caching type is '" + this.cacheProperties.getType() + "')"); } }
/** * {@link ImportSelector} to add {@link CacheType} configuration classes. */ static class CacheConfigurationImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { CacheType[] types = CacheType.values(); String[] imports = new String[types.length]; for (int i = 0; i < types.length; i++) { imports[i] = CacheConfigurations.getConfigurationClass(types[i]); } return imports; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isAppend() { return this.append; } public void setAppend(boolean append) { this.append = append; } public @Nullable List<String> getIgnorePaths() { return this.ignorePaths; } public void setIgnorePaths(@Nullable List<String> ignorePaths) { this.ignorePaths = ignorePaths; } /** * Log format for Jetty access logs. */ public enum Format { /** * NCSA format, as defined in CustomRequestLog#NCSA_FORMAT. */ NCSA, /** * Extended NCSA format, as defined in CustomRequestLog#EXTENDED_NCSA_FORMAT. */ EXTENDED_NCSA } } /** * Jetty thread properties. */ public static class Threads { /** * Number of acceptor threads to use. When the value is -1, the default, the * number of acceptors is derived from the operating environment. */ private Integer acceptors = -1; /** * Number of selector threads to use. When the value is -1, the default, the * number of selectors is derived from the operating environment. */ private Integer selectors = -1; /** * Maximum number of threads. Doesn't have an effect if virtual threads are * enabled. */ private Integer max = 200; /** * Minimum number of threads. Doesn't have an effect if virtual threads are * enabled. */ private Integer min = 8; /** * Maximum capacity of the thread pool's backing queue. A default is computed * based on the threading configuration. */ private @Nullable Integer maxQueueCapacity; /** * Maximum thread idle time. */ private Duration idleTimeout = Duration.ofMillis(60000); public Integer getAcceptors() { return this.acceptors; } public void setAcceptors(Integer acceptors) { this.acceptors = acceptors; }
public Integer getSelectors() { return this.selectors; } public void setSelectors(Integer selectors) { this.selectors = selectors; } public void setMin(Integer min) { this.min = min; } public Integer getMin() { return this.min; } public void setMax(Integer max) { this.max = max; } public Integer getMax() { return this.max; } public @Nullable Integer getMaxQueueCapacity() { return this.maxQueueCapacity; } public void setMaxQueueCapacity(@Nullable Integer maxQueueCapacity) { this.maxQueueCapacity = maxQueueCapacity; } public void setIdleTimeout(Duration idleTimeout) { this.idleTimeout = idleTimeout; } public Duration getIdleTimeout() { return this.idleTimeout; } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\autoconfigure\JettyServerProperties.java
2