instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getFilename() { return entry.getFilename(); } @Override public byte[] getData() { final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); return attachmentEntryService.retrieveData(entry.getId()); } @Override public String getContentType() {
return entry.getMimeType(); } @Override public URI getUrl() { return entry.getUrl(); } @Override public Instant getCreated() { return entry.getCreatedUpdatedInfo().getCreated().toInstant(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentEntry.java
1
请完成以下Java代码
public boolean isDeveloperMode() { return developerModeBL().isEnabled(); } public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id) { return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id); } public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue) { return sysConfigBL().getBooleanValue(sysConfigName, defaultValue); } public boolean isChangeLogEnabled() { return sessionBL().isChangeLogEnabled(); } public String getInsertChangeLogType(final int adClientId) { return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId); } public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords) { sessionDAO().saveChangeLogs(changeLogRecords); } public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{ migrationLogger().logMigration(session, po, poInfo, actionType); } public void fireDocumentNoChange(final PO po, final String value) { documentNoBL().fireDocumentNoChange(po, value); // task 09776 } public ADRefList getRefListById(@NonNull final ReferenceId referenceId) { return adReferenceService().getRefListById(referenceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java
1
请完成以下Java代码
public void setC_Workplace_ExternalSystem_ID (final int C_Workplace_ExternalSystem_ID) { if (C_Workplace_ExternalSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Workplace_ExternalSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Workplace_ExternalSystem_ID, C_Workplace_ExternalSystem_ID); } @Override public int getC_Workplace_ExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ExternalSystem_ID); } @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); }
@Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_ExternalSystem.java
1
请在Spring Boot框架中完成以下Java代码
public class UserResource { private UserDaoService service; public UserResource(UserDaoService service) { this.service = service; } @GetMapping("/users") public List<User> retrieveAllUsers() { return service.findAll(); } //http://localhost:8080/users //EntityModel //WebMvcLinkBuilder @GetMapping("/users/{id}") public EntityModel<User> retrieveUser(@PathVariable int id) { User user = service.findOne(id); if(user==null) throw new UserNotFoundException("id:"+id); EntityModel<User> entityModel = EntityModel.of(user); WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers()); entityModel.add(link.withRel("all-users")); return entityModel; }
@DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { service.deleteById(id); } @PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { User savedUser = service.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserResource.java
2
请完成以下Java代码
public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) { this.logoutHandlers = logoutHandlers; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { chain.doFilter(this.requestFactory.create((HttpServletRequest) req, (HttpServletResponse) res), res); } @Override public void afterPropertiesSet() throws ServletException { super.afterPropertiesSet(); updateFactory(); } private void updateFactory() { String rolePrefix = this.rolePrefix; this.requestFactory = createServlet3Factory(rolePrefix); } /** * Sets the {@link AuthenticationTrustResolver} to be used. The default is * {@link AuthenticationTrustResolverImpl}. * @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be * null. */ public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null"); this.trustResolver = trustResolver; updateFactory(); } private HttpServletRequestFactory createServlet3Factory(String rolePrefix) { HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix, this.securityContextRepository); factory.setTrustResolver(this.trustResolver); factory.setAuthenticationEntryPoint(this.authenticationEntryPoint); factory.setAuthenticationManager(this.authenticationManager); factory.setLogoutHandlers(this.logoutHandlers); factory.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); return factory; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilter.java
1
请完成以下Java代码
private static PurchaseOrderRequestItem createPurchaseOrderRequestItem(final PurchaseCandidate purchaseCandidate) { final Quantity qtyToPurchase = purchaseCandidate.getQtyToPurchase(); final ProductAndQuantity productAndQuantity = ProductAndQuantity.of(purchaseCandidate.getVendorProductNo(), qtyToPurchase.toBigDecimal(), qtyToPurchase.getUOMId()); return PurchaseOrderRequestItem.builder() .purchaseCandidateId(PurchaseCandidateId.getRepoIdOr(purchaseCandidate.getId(), -1)) .productAndQuantity(productAndQuantity) .build(); } @Override public void updateRemoteLineReferences(@NonNull final Collection<PurchaseOrderItem> purchaseOrderItems) { purchaseOrderItems.forEach(this::updateRemoteLineReference); }
private void updateRemoteLineReference(@NonNull final PurchaseOrderItem purchaseOrderItem) { final RemotePurchaseOrderCreatedItem remotePurchaseOrderCreatedItem = map.get(purchaseOrderItem); final OrderAndLineId purchaseOrderAndLineId = purchaseOrderItem.getPurchaseOrderAndLineId(); final LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated = // LocalPurchaseOrderForRemoteOrderCreated.builder() .purchaseOrderId(OrderAndLineId.getOrderRepoIdOr(purchaseOrderAndLineId, -1)) .purchaseOrderLineId(OrderAndLineId.getOrderLineRepoIdOr(purchaseOrderAndLineId, -1)) .remotePurchaseOrderCreatedItem(remotePurchaseOrderCreatedItem) .build(); vendorGatewayService.associateLocalWithRemotePurchaseOrderId(localPurchaseOrderForRemoteOrderCreated); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remoteorder\RealVendorGatewayInvoker.java
1
请完成以下Java代码
public void setAD_Workflow_ID (final int AD_Workflow_ID) { if (AD_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); } @Override public int getAD_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Block.java
1
请完成以下Java代码
public class ProductCategoryAccounts { @Getter @NonNull private final ProductCategoryId productCategoryId; @Getter @NonNull private final AcctSchemaId acctSchemaId; @Getter @Nullable private CostingLevel costingLevel; @Getter @Nullable private CostingMethod costingMethod; private final ImmutableMap<String, Optional<AccountId>> accountIdsByColumnName; @Builder private ProductCategoryAccounts( @NonNull final ProductCategoryId productCategoryId, @NonNull final AcctSchemaId acctSchemaId,
@Nullable final CostingLevel costingLevel, @Nullable final CostingMethod costingMethod, @NonNull final Map<String, Optional<AccountId>> accountIdsByColumnName) { this.productCategoryId = productCategoryId; this.acctSchemaId = acctSchemaId; this.costingLevel = costingLevel; this.costingMethod = costingMethod; this.accountIdsByColumnName = ImmutableMap.copyOf(accountIdsByColumnName); } public Optional<AccountId> getAccountId(@NonNull final ProductAcctType acctType) { return accountIdsByColumnName.getOrDefault(acctType.getColumnName(), Optional.empty()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\ProductCategoryAccounts.java
1
请完成以下Java代码
public boolean hasArchive(@NonNull final InvoiceId invoiceId) { return getLastArchive(invoiceId).isPresent(); } private Optional<I_AD_Archive> getLastArchive(@NonNull final InvoiceId invoiceId) { return archiveBL.getLastArchiveRecord(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)); } @NonNull public JSONInvoiceInfoResponse getInvoiceInfo(@NonNull final InvoiceId invoiceId, final String ad_language) { final JSONInvoiceInfoResponse.JSONInvoiceInfoResponseBuilder result = JSONInvoiceInfoResponse.builder(); final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final CurrencyCode currency = currencyDAO.getCurrencyCodeById(CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final List<I_C_InvoiceLine> lines = invoiceDAO.retrieveLines(invoiceId); for (final I_C_InvoiceLine line : lines) { final String productName = productBL.getProductNameTrl(ProductId.ofRepoId(line.getM_Product_ID())).translate(ad_language); final Percent taxRate = taxDAO.getRateById(TaxId.ofRepoId(line.getC_Tax_ID())); result.lineInfo(JSONInvoiceLineInfo.builder() .lineNumber(line.getLine()) .productName(productName) .qtyInvoiced(line.getQtyEntered()) .price(line.getPriceEntered()) .taxRate(taxRate) .lineNetAmt(line.getLineNetAmt()) .currency(currency) .build()); } return result.build(); } @NonNull public Optional<JsonReverseInvoiceResponse> reverseInvoice(@NonNull final InvoiceId invoiceId) { final I_C_Invoice documentRecord = invoiceDAO.getByIdInTrx(invoiceId);
if (documentRecord == null) { return Optional.empty(); } documentBL.processEx(documentRecord, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); final JsonReverseInvoiceResponse.JsonReverseInvoiceResponseBuilder responseBuilder = JsonReverseInvoiceResponse.builder(); invoiceCandDAO .retrieveInvoiceCandidates(invoiceId) .stream() .map(this::buildJSONItem) .forEach(responseBuilder::affectedInvoiceCandidate); return Optional.of(responseBuilder.build()); } private JsonInvoiceCandidatesResponseItem buildJSONItem(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { return JsonInvoiceCandidatesResponseItem .builder() .externalHeaderId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalHeaderId())) .externalLineId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalLineId())) .metasfreshId(MetasfreshId.of(invoiceCandidate.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\InvoiceService.java
1
请完成以下Java代码
public class Customer { private Long ID; private String name; private Integer age; private LocalDateTime createdDate; public Customer() { } public Customer(String name, Integer age) { this.name = name; this.age = age; } public Customer(Long ID, String name, Integer age, LocalDateTime createdDate) { this.ID = ID; this.name = name; this.age = age; this.createdDate = createdDate; } @Override public String toString() { return "Customer{" + "ID=" + ID + ", name='" + name + '\'' + ", age=" + age + ", createdDate=" + createdDate + '}'; } public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public LocalDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(LocalDateTime createdDate) { this.createdDate = createdDate; } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\customer\Customer.java
1
请完成以下Java代码
public static void layerIterable2(BinTreeNode<String> root, List<String> list) { LinkedList<BinTreeNode<String>> queue = new LinkedList<>(); if (root == null) { return; } queue.addLast(root); while (!queue.isEmpty()) { BinTreeNode<String> p = queue.poll(); list.add(p.data); if (p.left != null) { queue.addLast(p.left); } if (p.right != null) { queue.addLast(p.right); } } } static class BinTreeNode<T> { /** * 数据 */ T data;
/** * 左节点 */ BinTreeNode<T> left; /** * 右节点 */ BinTreeNode<T> right; public BinTreeNode(T data, BinTreeNode left, BinTreeNode right) { this.data = data; this.left = left; this.right = right; } @Override public String toString() { return data.toString(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\BinTreeIterable.java
1
请完成以下Java代码
public void usePreparedStatement(){ try { String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);"; String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);"; PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL); PreparedStatement empAddressStmt = connection.prepareStatement(insertEmployeeAddrSQL); for(int i = 0; i < EMPLOYEES.length; i++){ String employeeId = UUID.randomUUID().toString(); employeeStmt.setString(1,employeeId); employeeStmt.setString(2,EMPLOYEES[i]); employeeStmt.setString(3,DESIGNATIONS[i]); employeeStmt.addBatch(); empAddressStmt.setString(1,UUID.randomUUID().toString()); empAddressStmt.setString(2,employeeId); empAddressStmt.setString(3,ADDRESSES[i]); empAddressStmt.addBatch(); } employeeStmt.executeBatch(); empAddressStmt.executeBatch(); connection.commit();
} catch (Exception e) { try { connection.rollback(); } catch (SQLException ex) { System.out.println("Error during rollback"); System.out.println(ex.getMessage()); } e.printStackTrace(System.out); } } public static void main(String[] args) { BatchProcessing batchProcessing = new BatchProcessing(); batchProcessing.getConnection(); batchProcessing.createTables(); batchProcessing.useStatement(); batchProcessing.usePreparedStatement(); } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\spring\jdbc\BatchProcessing.java
1
请完成以下Java代码
public class M_Pricelist_Excel extends JavaProcess { private static final String AD_PROCESS_VALUE_RV_Fresh_PriceList_ExcelReport = "RV_Fresh_PriceList_ExcelReport"; @Param(parameterName = I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, mandatory = true) private int p_M_Pricelist_Version_ID; @Param(parameterName = I_C_BPartner.COLUMNNAME_C_BPartner_ID, mandatory = true) private int p_C_BPartner_ID; @Param(parameterName = I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, mandatory = true) private int p_C_BPartner_Location_ID; @Override protected String doIt() throws Exception { final ProcessExecutionResult result = ProcessInfo.builder() .setCtx(Env.getCtx()) .setAD_ProcessByValue(AD_PROCESS_VALUE_RV_Fresh_PriceList_ExcelReport) .addParameter(I_M_PriceList_Version.COLUMNNAME_M_PriceList_Version_ID, p_M_Pricelist_Version_ID) .addParameter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, p_C_BPartner_ID)
.addParameter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, p_C_BPartner_Location_ID) .setJRDesiredOutputType(OutputType.XLS) .buildAndPrepareExecution() .onErrorThrowException() .executeSync() .getResult(); getProcessInfo().getResult().setReportData(result.getReportData()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\process\M_Pricelist_Excel.java
1
请完成以下Java代码
protected void validateType(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { if (!type.isPrimitive()) { if (!type.isArrayType()) { validateTypeInternal(type, validator, invalidTypes); } if (type.isMapLikeType()) { validateType(type.getKeyType(), validator, invalidTypes); } if (type.isContainerType() || type.hasContentType()) { validateType(type.getContentType(), validator, invalidTypes); } } } protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { String className = type.getRawClass().getName(); if (!validator.validate(className) && !invalidTypes.contains(className)) { invalidTypes.add(className); } } protected ProcessEngineConfiguration getProcessEngineConfiguration() { return engine.getProcessEngineConfiguration(); } @Override public void deleteVariable(String variableName) { try { removeVariableEntity(variableName); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { String errorMessage = String.format("Cannot delete %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage()); throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); } } @Override public void modifyVariables(PatchVariablesDto patch) { VariableMap variableModifications = null;
try { variableModifications = VariableValueDto.toMap(patch.getModifications(), engine, objectMapper); } catch (RestException e) { String errorMessage = String.format("Cannot modify variables for %s: %s", getResourceTypeName(), e.getMessage()); throw new InvalidRequestException(e.getStatus(), e, errorMessage); } List<String> variableDeletions = patch.getDeletions(); try { updateVariableEntities(variableModifications, variableDeletions); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { String errorMessage = String.format("Cannot modify variables for %s %s: %s", getResourceTypeName(), resourceId, e.getMessage()); throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); } } protected abstract VariableMap getVariableEntities(boolean deserializeValues); protected abstract void updateVariableEntities(VariableMap variables, List<String> deletions); protected abstract TypedValue getVariableEntity(String variableKey, boolean deserializeValue); protected abstract void setVariableEntity(String variableKey, TypedValue variableValue); protected abstract void removeVariableEntity(String variableKey); protected abstract String getResourceTypeName(); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\impl\AbstractVariablesResource.java
1
请在Spring Boot框架中完成以下Java代码
public ActiveMQConnectionFactory activeMQConnectionFactory() { ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL(mqBrokerURL); activeMQConnectionFactory.setUserName(mqUserName); activeMQConnectionFactory.setPassword(mqPassword); return activeMQConnectionFactory; } /** * Spring用于管理真正的ConnectionFactory的ConnectionFactory * * @param pooledConnectionFactory Pooled连接工厂 * @return 连接工厂 */ @Primary @Bean(name = "connectionFactory") public SingleConnectionFactory singleConnectionFactory(@Qualifier("pooledConnectionFactory") PooledConnectionFactory pooledConnectionFactory) { SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(); singleConnectionFactory.setTargetConnectionFactory(pooledConnectionFactory); return singleConnectionFactory; } /** * ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory * 可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗。 * 要依赖于 activemq-pool包 * * @param activeMQConnectionFactory 目标连接工厂 * @return Pooled连接工厂 */ @Bean(name = "pooledConnectionFactory") public PooledConnectionFactory pooledConnectionFactory(@Qualifier("targetConnectionFactory") ActiveMQConnectionFactory activeMQConnectionFactory) { PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(); pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory);
pooledConnectionFactory.setMaxConnections(maxConnections); return pooledConnectionFactory; } /** * 商户通知队列模板 * * @param singleConnectionFactory 连接工厂 * @return 商户通知队列模板 */ @Bean(name = "notifyJmsTemplate") public JmsTemplate notifyJmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory); notifyJmsTemplate.setDefaultDestinationName(tradeQueueDestinationName); return notifyJmsTemplate; } /** * 队列模板 * * @param singleConnectionFactory 连接工厂 * @return 队列模板 */ @Bean(name = "jmsTemplate") public JmsTemplate jmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory); notifyJmsTemplate.setDefaultDestinationName(orderQueryDestinationName); return notifyJmsTemplate; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\config\ActiveMqConfig.java
2
请完成以下Java代码
/* for testing */ void setIncludePort(boolean includePort) { this.includePort = includePort; } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList("patterns"); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST; } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { String host; if (includePort) { host = exchange.getRequest().getHeaders().getFirst("Host"); } else { InetSocketAddress address = exchange.getRequest().getHeaders().getHost(); if (address != null) { host = address.getHostString(); } else { return false; } } if (host == null) { return false; } String match = null; for (int i = 0; i < config.getPatterns().size(); i++) { String pattern = config.getPatterns().get(i); if (pathMatcher.match(pattern, host)) { match = pattern; break; } } if (match != null) { Map<String, String> variables = pathMatcher.extractUriTemplateVariables(match, host); ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables); return true; } return false;
} @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Hosts: %s", config.getPatterns()); } }; } public static class Config { private List<String> patterns = new ArrayList<>(); public List<String> getPatterns() { return patterns; } public Config setPatterns(List<String> patterns) { this.patterns = patterns; return this; } @Override public String toString() { return new ToStringCreator(this).append("patterns", patterns).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HostRoutePredicateFactory.java
1
请完成以下Java代码
public void setTarget(Parameter parameter) { targetRefAttribute.setReferenceTargetElement(this, parameter); } public TransformationExpression getTransformation() { return transformationChild.getChild(this); } public void setTransformation(TransformationExpression transformationExpression) { transformationChild.setChild(this, transformationExpression); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParameterMapping.class, CMMN_ELEMENT_PARAMETER_MAPPING) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<ParameterMapping>() { public ParameterMapping newInstance(ModelTypeInstanceContext instanceContext) { return new ParameterMappingImpl(instanceContext); }
}); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(Parameter.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF) .idAttributeReference(Parameter.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); transformationChild = sequenceBuilder.element(TransformationExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ParameterMappingImpl.java
1
请完成以下Java代码
public MClick[] getMClicks() { ArrayList<MClick> list = new ArrayList<MClick>(); /** @todo Clicks */ // MClick[] retValue = new MClick[list.size()]; list.toArray(retValue); return retValue; } // getMClicks /** * Get Count for date format * @param DateFormat valid TRUNC date format * @return count */ protected ValueNamePair[] getCount (String DateFormat) { ArrayList<ValueNamePair> list = new ArrayList<ValueNamePair>(); String sql = "SELECT TRUNC(Created, '" + DateFormat + "'), Count(*) " + "FROM W_Click " + "WHERE W_ClickCount_ID=? " + "GROUP BY TRUNC(Created, '" + DateFormat + "')"; // PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, getW_ClickCount_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String value = m_dateFormat.format(rs.getTimestamp(1)); String name = m_intFormat.format(rs.getInt(2)); ValueNamePair pp = ValueNamePair.of(value, name); list.add(pp); } rs.close(); pstmt.close(); pstmt = null; } catch (SQLException ex) { log.error(sql, ex); } try { if (pstmt != null) pstmt.close(); } catch (SQLException ex1) { } pstmt = null;
// ValueNamePair[] retValue = new ValueNamePair[list.size()]; list.toArray(retValue); return retValue; } // getCount /** * Get Monthly Count * @return monthly count */ public ValueNamePair[] getCountQuarter () { return getCount("Q"); } // getCountQuarter /** * Get Monthly Count * @return monthly count */ public ValueNamePair[] getCountMonth () { return getCount("MM"); } // getCountMonth /** * Get Weekly Count * @return weekly count */ public ValueNamePair[] getCountWeek () { return getCount("DY"); } // getCountWeek /** * Get Daily Count * @return dailt count */ public ValueNamePair[] getCountDay () { return getCount("J"); } // getCountDay } // MClickCount
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClickCount.java
1
请完成以下Java代码
public String getContentHTML () { return (String)get_Value(COLUMNNAME_ContentHTML); } /** 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 LinkURL. @param LinkURL Contains URL to a target */ public void setLinkURL (String LinkURL) { set_Value (COLUMNNAME_LinkURL, LinkURL); } /** Get LinkURL. @return Contains URL to a target */ public String getLinkURL () { return (String)get_Value(COLUMNNAME_LinkURL); } /** Set Publication Date. @param PubDate Date on which this article will / should get published */ public void setPubDate (Timestamp PubDate) { set_Value (COLUMNNAME_PubDate, PubDate); }
/** Get Publication Date. @return Date on which this article will / should get published */ public Timestamp getPubDate () { return (Timestamp)get_Value(COLUMNNAME_PubDate); } /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
1
请完成以下Java代码
public org.compiere.model.I_M_DiscountSchema getM_DiscountSchema() { return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class); } @Override public void setM_DiscountSchema(final org.compiere.model.I_M_DiscountSchema M_DiscountSchema) { set_ValueFromPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class, M_DiscountSchema); } @Override public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID) { if (M_DiscountSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID); } @Override public int getM_DiscountSchema_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID); } @Override public void setM_DiscountSchemaBreak_V_ID (final int M_DiscountSchemaBreak_V_ID) { if (M_DiscountSchemaBreak_V_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, M_DiscountSchemaBreak_V_ID); } @Override public int getM_DiscountSchemaBreak_V_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchemaBreak_V_ID);
} @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak_V.java
1
请完成以下Java代码
public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo
Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java
1
请完成以下Java代码
public String getScriptFormat() { return scriptFormatAttribute.getValue(this); } public void setScriptFormat(String scriptFormat) { scriptFormatAttribute.setValue(this, scriptFormat); } public Script getScript() { return scriptChild.getChild(this); } public void setScript(Script script) { scriptChild.setChild(this, script); } /** camunda extensions */ public String getCamundaResultVariable() { return camundaResultVariableAttribute.getValue(this);
} public void setCamundaResultVariable(String camundaResultVariable) { camundaResultVariableAttribute.setValue(this, camundaResultVariable); } public String getCamundaResource() { return camundaResourceAttribute.getValue(this); } public void setCamundaResource(String camundaResource) { camundaResourceAttribute.setValue(this, camundaResource); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ScriptTaskImpl.java
1
请完成以下Java代码
public MergePdfByteArrays add(final byte[] pdfByteArray) { try { final PdfReader reader = new PdfReader(pdfByteArray); int numberOfPages = reader.getNumberOfPages(); if (this.document == null) { this.document = new Document(reader.getPageSizeWithRotation(1)); this.outStream = new ByteArrayOutputStream(); this.writer = PdfWriter.getInstance(this.document, this.outStream); this.writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); // needs to be specified explicitly; will not work with PdfWriter.PrintScalingNone this.document.open(); this.cb = this.writer.getDirectContent(); } PdfImportedPage page; int rotation; { int i = 0; while (i < numberOfPages) { i++; document.setPageSize(reader.getPageSizeWithRotation(i)); document.newPage(); page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } } } catch (Exception e) { throw new AdempiereException(e); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\MergePdfByteArrays.java
1
请完成以下Java代码
public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_Value (COLUMNNAME_M_PickingSlot_ID, null); else set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * OrderPickingType AD_Reference_ID=542022 * Reference name: OrderPickingType List */ public static final int ORDERPICKINGTYPE_AD_Reference_ID=542022; /** Single = SG */ public static final String ORDERPICKINGTYPE_Single = "SG"; /** Multiple = MP */ public static final String ORDERPICKINGTYPE_Multiple = "MP"; @Override public void setOrderPickingType (final @Nullable java.lang.String OrderPickingType) { set_Value (COLUMNNAME_OrderPickingType, OrderPickingType); } @Override public java.lang.String getOrderPickingType()
{ return get_ValueAsString(COLUMNNAME_OrderPickingType); } @Override public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID) { if (PickFrom_Locator_ID < 1) set_Value (COLUMNNAME_PickFrom_Locator_ID, null); else set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID); } @Override public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } /** * PriorityRule AD_Reference_ID=154 * Reference name: _PriorityRule */ public static final int PRIORITYRULE_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITYRULE_High = "3"; /** Medium = 5 */ public static final String PRIORITYRULE_Medium = "5"; /** Low = 7 */ public static final String PRIORITYRULE_Low = "7"; /** Urgent = 1 */ public static final String PRIORITYRULE_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITYRULE_Minor = "9"; @Override public void setPriorityRule (final @Nullable java.lang.String PriorityRule) { set_Value (COLUMNNAME_PriorityRule, PriorityRule); } @Override public java.lang.String getPriorityRule() { return get_ValueAsString(COLUMNNAME_PriorityRule); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace.java
1
请完成以下Java代码
public WFNode unbox() { return node; } public @NonNull WFNodeId getId() {return node.getId();} public @NonNull WorkflowId getWorkflowId() { return workflowModel.getId(); } public @NonNull ClientId getClientId() {return node.getClientId();} public @NonNull WFNodeAction getAction() {return node.getAction();} public @NonNull ITranslatableString getName() {return node.getName();} @NonNull public ITranslatableString getDescription() {return node.getDescription();} @NonNull public ITranslatableString getHelp() {return node.getHelp();} public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();} public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();} public void setXPosition(final int x) { this.xPosition = x; } public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();} public void setYPosition(final int y) { this.yPosition = y; } public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId) {
return node.getTransitions(clientId) .stream() .map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition)) .collect(ImmutableList.toImmutableList()); } public void saveEx() { workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder() .nodeId(getId()) .xPosition(getXPosition()) .yPosition(getYPosition()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
1
请完成以下Java代码
public FactLineBuilder costElement(@Nullable final CostElementId costElementId) { assertNotBuild(); this.costElementId = costElementId; return this; } public FactLineBuilder costElement(@Nullable final CostElement costElement) { return costElement(costElement != null ? costElement.getId() : null); } public FactLineBuilder description(@Nullable final String description) { assertNotBuild(); this.description = StringUtils.trimBlankToOptional(description); return this; } public FactLineBuilder additionalDescription(@Nullable final String additionalDescription) { assertNotBuild(); this.additionalDescription = StringUtils.trimBlankToNull(additionalDescription); return this; } public FactLineBuilder openItemKey(@Nullable FAOpenItemTrxInfo openItemTrxInfo)
{ assertNotBuild(); this.openItemTrxInfo = openItemTrxInfo; return this; } public FactLineBuilder productId(@Nullable ProductId productId) { assertNotBuild(); this.productId = Optional.ofNullable(productId); return this; } public FactLineBuilder userElementString1(@Nullable final String userElementString1) { assertNotBuild(); this.userElementString1 = StringUtils.trimBlankToOptional(userElementString1); return this; } public FactLineBuilder salesOrderId(@Nullable final OrderId salesOrderId) { assertNotBuild(); this.salesOrderId = Optional.ofNullable(salesOrderId); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLineBuilder.java
1
请完成以下Java代码
protected @Nullable Object convertPayload(Message<?> message) { return this.delegate.convertPayload(message); } @Override protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) { Object value = record.value(); if (value == null) { return KafkaNull.INSTANCE; } Class<?> rawType = ResolvableType.forType(type).resolve(Object.class); if (!rawType.isInterface()) { return this.delegate.extractAndConvertValue(record, type); } InputStream inputStream = new ByteArrayInputStream(getAsByteArray(value)); // The inputStream is closed underneath by the ObjectMapper#_readTreeAndClose() return this.projectionFactory.createProjection(rawType, inputStream); } /** * Return the given source value as byte array.
* @param source must not be {@literal null}. * @return the source instance as byte array. */ private static byte[] getAsByteArray(Object source) { Assert.notNull(source, "Source must not be null"); if (source instanceof String) { return ((String) source).getBytes(StandardCharsets.UTF_8); } if (source instanceof byte[]) { return (byte[]) source; } if (source instanceof Bytes) { return ((Bytes) source).get(); } throw new ConversionException(String.format( "Unsupported payload type '%s'. Expected 'String', 'Bytes', or 'byte[]'", source.getClass()), null); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\ProjectingMessageConverter.java
1
请完成以下Java代码
public String getCompositor() { return compositor; } public void setCompositor(String compositor) { this.compositor = compositor; } public String getSinger() { return singer; } public void setSinger(String singer) { this.singer = singer; }
public LocalDateTime getReleased() { return released; } public void setReleased(LocalDateTime released) { this.released = released; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\jpa\domain\Song.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_Invoice_Candidate_HeaderAggregation_ID (final int C_Invoice_Candidate_HeaderAggregation_ID) { if (C_Invoice_Candidate_HeaderAggregation_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_HeaderAggregation_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_HeaderAggregation_ID, C_Invoice_Candidate_HeaderAggregation_ID); } @Override public int getC_Invoice_Candidate_HeaderAggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_HeaderAggregation_ID); } @Override public void setHeaderAggregationKey (final java.lang.String HeaderAggregationKey) { set_ValueNoCheck (COLUMNNAME_HeaderAggregationKey, HeaderAggregationKey); } @Override public java.lang.String getHeaderAggregationKey() { return get_ValueAsString(COLUMNNAME_HeaderAggregationKey); } @Override public void setHeaderAggregationKeyBuilder_ID (final int HeaderAggregationKeyBuilder_ID) { if (HeaderAggregationKeyBuilder_ID < 1) set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, null); else set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, HeaderAggregationKeyBuilder_ID); } @Override public int getHeaderAggregationKeyBuilder_ID() { return get_ValueAsInt(COLUMNNAME_HeaderAggregationKeyBuilder_ID); } @Override
public void setInvoicingGroupNo (final int InvoicingGroupNo) { set_ValueNoCheck (COLUMNNAME_InvoicingGroupNo, InvoicingGroupNo); } @Override public int getInvoicingGroupNo() { return get_ValueAsInt(COLUMNNAME_InvoicingGroupNo); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @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.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_HeaderAggregation.java
1
请完成以下Java代码
public static int compute(String a, String b) { return ed(a, b); } /** * 编辑距离 * * @param wrongWord 串A,其实它们两个调换位置还是一样的 * @param rightWord 串B * @return 它们之间的距离 */ public static int ed(String wrongWord, String rightWord) { final int m = wrongWord.length(); final int n = rightWord.length(); int[][] d = new int[m + 1][n + 1]; for (int j = 0; j <= n; ++j) { d[0][j] = j; } for (int i = 0; i <= m; ++i) { d[i][0] = i; } for (int i = 1; i <= m; ++i) { char ci = wrongWord.charAt(i - 1); for (int j = 1; j <= n; ++j) { char cj = rightWord.charAt(j - 1); if (ci == cj) { d[i][j] = d[i - 1][j - 1]; } else if (i > 1 && j > 1 && ci == rightWord.charAt(j - 2) && cj == wrongWord.charAt(i - 2)) { // 交错相等 d[i][j] = 1 + Math.min(d[i - 2][j - 2], Math.min(d[i][j - 1], d[i - 1][j])); } else { // 等号右边的分别代表 将ci改成cj 错串加cj 错串删ci d[i][j] = Math.min(d[i - 1][j - 1] + 1, Math.min(d[i][j - 1] + 1, d[i - 1][j] + 1)); } } } return d[m][n]; } /** * 编辑距离 * * @param wrongWord 串A,其实它们两个调换位置还是一样的 * @param rightWord 串B * @return 它们之间的距离 */ public static int compute(char[] wrongWord, char[] rightWord) { final int m = wrongWord.length; final int n = rightWord.length; int[][] d = new int[m + 1][n + 1]; for (int j = 0; j <= n; ++j) { d[0][j] = j;
} for (int i = 0; i <= m; ++i) { d[i][0] = i; } for (int i = 1; i <= m; ++i) { char ci = wrongWord[i - 1]; for (int j = 1; j <= n; ++j) { char cj = rightWord[j - 1]; if (ci == cj) { d[i][j] = d[i - 1][j - 1]; } else if (i > 1 && j > 1 && ci == rightWord[j - 2] && cj == wrongWord[i - 2]) { // 交错相等 d[i][j] = 1 + Math.min(d[i - 2][j - 2], Math.min(d[i][j - 1], d[i - 1][j])); } else { // 等号右边的分别代表 将ci改成cj 错串加cj 错串删ci d[i][j] = Math.min(d[i - 1][j - 1] + 1, Math.min(d[i][j - 1] + 1, d[i - 1][j] + 1)); } } } return d[m][n]; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\EditDistance.java
1
请完成以下Java代码
public Map<Character, Integer> charFrequencyUsingGetOrDefault(String sentence) { Map<Character, Integer> charMap = new HashMap<>(); for (int c = 0; c < sentence.length(); c++) { charMap.put(sentence.charAt(c), charMap.getOrDefault(sentence.charAt(c), 0) + 1); } return charMap; } public Map<Character, Integer> charFrequencyUsingMerge(String sentence) { Map<Character, Integer> charMap = new HashMap<>(); for (int c = 0; c < sentence.length(); c++) { charMap.merge(sentence.charAt(c), 1, Integer::sum); } return charMap; } public Map<Character, Integer> charFrequencyUsingCompute(String sentence) { Map<Character, Integer> charMap = new HashMap<>(); for (int c = 0; c < sentence.length(); c++) { charMap.compute(sentence.charAt(c), (key, value) -> (value == null) ? 1 : value + 1); } return charMap; } public Map<Character, Long> charFrequencyUsingAtomicMap(String sentence) { AtomicLongMap<Character> map = AtomicLongMap.create(); for (int c = 0; c < sentence.length(); c++) { map.getAndIncrement(sentence.charAt(c)); } return map.asMap(); } public Map<Character, Integer> charFrequencyWithConcurrentMap(String sentence, Map<Character, Integer> charMap) { for (int c = 0; c < sentence.length(); c++) { charMap.compute(sentence.charAt(c), (key, value) -> (value == null) ? 1 : value + 1); } return charMap;
} public Map<Character, AtomicInteger> charFrequencyWithGetAndIncrement(String sentence) { Map<Character, AtomicInteger> charMap = new HashMap<>(); for (int c = 0; c < sentence.length(); c++) { charMap.putIfAbsent(sentence.charAt(c), new AtomicInteger(0)); charMap.get(sentence.charAt(c)) .incrementAndGet(); } return charMap; } public Map<Character, AtomicInteger> charFrequencyWithGetAndIncrementComputeIfAbsent(String sentence) { Map<Character, AtomicInteger> charMap = new HashMap<>(); for (int c = 0; c < sentence.length(); c++) { charMap.computeIfAbsent(sentence.charAt(c), k -> new AtomicInteger(0)) .incrementAndGet(); } return charMap; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\incrementmapkey\IncrementMapValueWays.java
1
请完成以下Java代码
public static Set<Character> byMap(String input) { Map<Character, Integer> map = new HashMap<>(); for (char c : input.toCharArray()) { map.compute(c, (character, count) -> count == null ? 1 : ++count); } int maxCount = map.values() .stream() .mapToInt(Integer::intValue) .max() .getAsInt(); return map.keySet() .stream() .filter(c -> map.get(c) == maxCount) .collect(toSet()); }
public static Set<Character> byBucket(String input) { int[] buckets = new int[128]; int maxCount = 0; for (char c : input.toCharArray()) { buckets[c]++; maxCount = Math.max(buckets[c], maxCount); } int finalMaxCount = maxCount; return IntStream.range(0, 128) .filter(c -> buckets[c] == finalMaxCount) .mapToObj(i -> (char) i) .collect(Collectors.toSet()); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\charfreq\CharacterWithHighestFrequency.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonWFProcess { private static final AdMessageKey NO_ACTIVITY_ERROR_MSG = AdMessageKey.of("de.metas.workflow.rest_api.model.NO_ACTIVITY_ERROR_MSG"); @NonNull String id; @NonNull JsonWFProcessHeaderProperties headerProperties; @NonNull List<JsonWFActivity> activities; boolean isAllowAbort; public static JsonWFProcess of( @NonNull final WFProcess wfProcess, @NonNull final WFProcessHeaderProperties headerProperties, @NonNull final ImmutableMap<WFActivityId, UIComponent> uiComponents, @NonNull final JsonOpts jsonOpts) { return builder() .id(wfProcess.getId().getAsString()) .headerProperties(JsonWFProcessHeaderProperties.of(headerProperties, jsonOpts)) .activities(wfProcess.getActivities() .stream() .map(activity -> JsonWFActivity.of( activity,
uiComponents.get(activity.getId()), jsonOpts)) .collect(ImmutableList.toImmutableList())) .isAllowAbort(wfProcess.isAllowAbort()) .build(); } @JsonIgnore public JsonWFActivity getActivityById(@NonNull final String activityId) { return activities.stream().filter(activity -> activity.getActivityId().equals(activityId)) .findFirst() .orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG) .appendParametersToMessage() .setParameter("ID", activityId) .setParameter("WFProcess", this)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonWFProcess.java
2
请完成以下Java代码
public String getCollectionVariable() { return collectionVariable; } public void setCollectionVariable(String collectionVariable) { this.collectionVariable = collectionVariable; } public String getCollectionElementVariable() { return collectionElementVariable; } public void setCollectionElementVariable(String collectionElementVariable) { this.collectionElementVariable = collectionElementVariable; } public String getCollectionElementIndexVariable() { return collectionElementIndexVariable; } public void setCollectionElementIndexVariable(String collectionElementIndexVariable) { this.collectionElementIndexVariable = collectionElementIndexVariable; } public void setInnerActivityBehavior(ActivityBehavior innerActivityBehavior) { this.innerActivityBehavior = innerActivityBehavior; if (innerActivityBehavior instanceof org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) { ((org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) innerActivityBehavior).setV5MultiInstanceActivityBehavior(this); } else { ((AbstractBpmnActivityBehavior) this.innerActivityBehavior).setMultiInstanceActivityBehavior(this); } } public ActivityBehavior getInnerActivityBehavior() { return innerActivityBehavior; } /** * ACT-1339. Calling ActivityEndListeners within an {@link AtomicOperation} so that an executionContext is present. * * @author Aris Tzoumas * @author Joram Barrez */
private static final class CallActivityListenersOperation implements AtomicOperation { private List<ExecutionListener> listeners; private CallActivityListenersOperation(List<ExecutionListener> listeners) { this.listeners = listeners; } @Override public void execute(InterpretableExecution execution) { for (ExecutionListener executionListener : listeners) { try { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new ExecutionListenerInvocation(executionListener, execution)); } catch (Exception e) { throw new ActivitiException("Couldn't execute listener", e); } } } @Override public boolean isAsync(InterpretableExecution execution) { return false; } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1
请完成以下Java代码
protected void register(String description, ServletContext servletContext) { try { servletContext.addListener(this.listener); } catch (RuntimeException ex) { throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex); } } /** * Returns {@code true} if the specified listener is one of the supported types. * @param listener the listener to test * @return if the listener is of a supported type */ public static boolean isSupportedType(EventListener listener) { for (Class<?> type : SUPPORTED_TYPES) {
if (ClassUtils.isAssignableValue(type, listener)) { return true; } } return false; } /** * Return the supported types for this registration. * @return the supported types */ public static Set<Class<?>> getSupportedTypes() { return SUPPORTED_TYPES; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletListenerRegistrationBean.java
1
请完成以下Java代码
public int getW_InvActualAdjust_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_W_InvActualAdjust_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getW_Inventory_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getW_Inventory_Acct(), get_TrxName()); } /** Set (Not Used). @param W_Inventory_Acct Warehouse Inventory Asset Account - Currently not used */ public void setW_Inventory_Acct (int W_Inventory_Acct) { set_Value (COLUMNNAME_W_Inventory_Acct, Integer.valueOf(W_Inventory_Acct)); } /** Get (Not Used). @return Warehouse Inventory Asset Account - Currently not used */ public int getW_Inventory_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Inventory_Acct); if (ii == null) return 0; return ii.intValue();
} public I_C_ValidCombination getW_Revaluation_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getW_Revaluation_Acct(), get_TrxName()); } /** Set Inventory Revaluation. @param W_Revaluation_Acct Account for Inventory Revaluation */ public void setW_Revaluation_Acct (int W_Revaluation_Acct) { set_Value (COLUMNNAME_W_Revaluation_Acct, Integer.valueOf(W_Revaluation_Acct)); } /** Get Inventory Revaluation. @return Account for Inventory Revaluation */ public int getW_Revaluation_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct); 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_M_Warehouse_Acct.java
1
请完成以下Java代码
public Request build() { // TODO: validation return this; } @Override public HttpHeaders getHeaders() { return httpHeaders; } @Override public HttpMethod getMethod() { return method; } @Override public @Nullable URI getUri() { return uri;
} @Override public ServerRequest getServerRequest() { return serverRequest; } @Override public Collection<ResponseConsumer> getResponseConsumers() { return responseConsumers; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\ProxyExchange.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonHUConsolidationJobPickingSlotContent { @NonNull PickingSlotId pickingSlotId; @NonNull JsonDisplayableQRCode pickingSlotQRCode; @NonNull List<Item> items; // // // @Value @Builder @Jacksonized public static class Item { @NonNull HuId huId; @NonNull String displayName; @NonNull String packingInfo; @NonNull List<ItemStorage> storages; }
// // // @Value @Builder @Jacksonized public static class ItemStorage { @NonNull String productName; @NonNull BigDecimal qty; @NonNull String uom; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\rest_api\json\JsonHUConsolidationJobPickingSlotContent.java
2
请在Spring Boot框架中完成以下Java代码
public class StudentDaoWithDeprecatedJdbcTemplateMethods { JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public List<Student> getStudentsOfAgeAndGender(Integer age, String gender) { String sql = "select student_id, student_name, age, gender, grade, state from student where age= ? and gender = ?"; Object[] args = {age, gender}; return jdbcTemplate.query(sql, args, new StudentRowMapper()); } public List<Student> getStudentsOfAgeGenderAndGrade(Integer age, String gender, Integer grade) { String sql = "select student_id, student_name, age, gender, grade, state from student where age= ? and gender = ? and grade = ?"; Object[] args = {age, gender, grade}; return jdbcTemplate.query(sql, args, new StudentRowMapper()); }
public List<Student> getStudentsOfGradeAndState(Integer grade, String state) { String sql = "select student_id, student_name, age, gender, grade, state from student where grade = ? and state = ?"; Object[] args = {grade, state}; return jdbcTemplate.query(sql, args, new StudentResultExtractor()); } public Student getStudentOfStudentIDAndGrade(Integer studentID, Integer grade) { String sql = "select student_id, student_name, age, gender, grade, state from student where student_id = ? and grade = ?"; Object[] args = {studentID, grade}; return jdbcTemplate.queryForObject(sql, args, new StudentRowMapper()); } public Integer getCountOfStudentsInAGradeFromAState(Integer grade, String state) { String sql = "select student_id, student_name, age, gender, grade, state from student where grade = ? and state = ?"; Object[] args = {grade, state}; RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler(); jdbcTemplate.query(sql, args, countCallbackHandler); return countCallbackHandler.getRowCount(); } }
repos\tutorials-master\persistence-modules\spring-jdbc\src\main\java\com\baeldung\spring\jdbc\replacedeprecated\StudentDaoWithDeprecatedJdbcTemplateMethods.java
2
请完成以下Java代码
public Stream<I_M_AttributeInstance> streamAttributeInstances( @NonNull final AttributeSetInstanceId asiId, @NonNull final Set<AttributeId> attributeIds) { if (asiId.isNone() || attributeIds.isEmpty()) { return Stream.of(); } return queryBL.createQueryBuilder(I_M_AttributeInstance.class) .addEqualsFilter(I_M_AttributeInstance.COLUMNNAME_M_AttributeSetInstance_ID, asiId) .addInArrayFilter(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, attributeIds) .stream(); } @Override public I_M_AttributeInstance createNewAttributeInstance( final Properties ctx, final I_M_AttributeSetInstance asi, @NonNull final AttributeId attributeId, final String trxName) { final I_M_AttributeInstance ai = InterfaceWrapperHelper.create(ctx, I_M_AttributeInstance.class, trxName); ai.setAD_Org_ID(asi.getAD_Org_ID()); ai.setM_AttributeSetInstance(asi); ai.setM_Attribute_ID(attributeId.getRepoId()); return ai; } @Override public void save(@NonNull final I_M_AttributeSetInstance asi) { saveRecord(asi); } @Override public void save(@NonNull final I_M_AttributeInstance ai)
{ saveRecord(ai); } @Override public Set<AttributeId> getAttributeIdsByAttributeSetInstanceId(@NonNull final AttributeSetInstanceId attributeSetInstanceId) { return queryBL .createQueryBuilderOutOfTrx(I_M_AttributeInstance.class) .addEqualsFilter(I_M_AttributeInstance.COLUMN_M_AttributeSetInstance_ID, attributeSetInstanceId) .create() .listDistinct(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, Integer.class) .stream() .map(AttributeId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceDAO.java
1
请完成以下Java代码
private static @Nullable String extractSessionId(HttpServletRequest request) { HttpSession session = request.getSession(false); return (session != null) ? session.getId() : null; } /** * Indicates the TCP/IP address the authentication request was received from. * @return the address */ public String getRemoteAddress() { return this.remoteAddress; } /** * Indicates the <code>HttpSession</code> id the authentication request was received * from. * @return the session ID */ public @Nullable String getSessionId() { return this.sessionId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
WebAuthenticationDetails that = (WebAuthenticationDetails) o; return Objects.equals(this.remoteAddress, that.remoteAddress) && Objects.equals(this.sessionId, that.sessionId); } @Override public int hashCode() { return Objects.hash(this.remoteAddress, this.sessionId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append(" ["); sb.append("RemoteIpAddress=").append(this.getRemoteAddress()).append(", "); sb.append("SessionId=").append(this.getSessionId()).append("]"); return sb.toString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\WebAuthenticationDetails.java
1
请完成以下Java代码
public class InOutLineMaterialTrackingListener extends MaterialTrackingListenerAdapter { public static final transient InOutLineMaterialTrackingListener instance = new InOutLineMaterialTrackingListener(); public static final String LISTENER_TableName = I_M_InOutLine.Table_Name; /** * Increase {@link I_M_Material_Tracking#COLUMNNAME_QtyReceived} */ @Override public void afterModelLinked(final MTLinkRequest request) { final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(request.getModel(), I_M_InOutLine.class); final I_M_Material_Tracking materialTracking = request.getMaterialTrackingRecord(); if (!isEligible(receiptLine, materialTracking)) { return; } final BigDecimal qtyReceivedToAdd = receiptLine.getMovementQty(); final BigDecimal qtyReceived = materialTracking.getQtyReceived(); final BigDecimal qtyReceivedNew = qtyReceived.add(qtyReceivedToAdd); materialTracking.setQtyReceived(qtyReceivedNew); InterfaceWrapperHelper.save(materialTracking); // task 08021 final IQualityBasedInvoicingDAO qualityBasedInvoicingDAO = Services.get(IQualityBasedInvoicingDAO.class); final IMaterialTrackingDocuments materialTrackingDocuments = qualityBasedInvoicingDAO.retrieveMaterialTrackingDocuments(materialTracking); final PPOrderQualityCalculator calculator = new PPOrderQualityCalculator(); calculator.update(materialTrackingDocuments); // end task 08021 } /** * Decrease {@link I_M_Material_Tracking#COLUMNNAME_QtyReceived} */ @Override public void afterModelUnlinked(final Object model, final I_M_Material_Tracking materialTrackingOld) {
final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(model, I_M_InOutLine.class); if (!isEligible(receiptLine, materialTrackingOld)) { return; } final BigDecimal qtyReceivedToRemove = receiptLine.getMovementQty(); final BigDecimal qtyReceived = materialTrackingOld.getQtyReceived(); final BigDecimal qtyReceivedNew = qtyReceived.subtract(qtyReceivedToRemove); materialTrackingOld.setQtyReceived(qtyReceivedNew); InterfaceWrapperHelper.save(materialTrackingOld); } private final boolean isEligible(final I_M_InOutLine inoutLine, final I_M_Material_Tracking materialTracking) { // check if the inoutLine's product is our tracked product. if (materialTracking.getM_Product_ID() != inoutLine.getM_Product_ID()) { return false; } final I_M_InOut inout = inoutLine.getM_InOut(); // Shipments are not eligible (just in case) if (inout.isSOTrx()) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\listeners\InOutLineMaterialTrackingListener.java
1
请完成以下Java代码
public List<I_M_HU_Trx_Line> retrieveReferencingTrxLines(final Properties ctx, final int adTableId, final int recordId, final String trxName) { Check.assume(adTableId > 0, "adTableId > 0"); Check.assume(recordId > 0, "recordId > 0"); final IHUTrxQuery huTrxQuery = createHUTrxQuery(); huTrxQuery.setAD_Table_ID(adTableId); huTrxQuery.setRecord_ID(recordId); return retrieveTrxLines(ctx, huTrxQuery, trxName); } @Override public List<I_M_HU_Trx_Line> retrieveTrxLines(final I_M_HU_Trx_Hdr trxHdr) { final Properties ctx = InterfaceWrapperHelper.getCtx(trxHdr); final String trxName = InterfaceWrapperHelper.getTrxName(trxHdr); final IHUTrxQuery huTrxQuery = createHUTrxQuery(); huTrxQuery.setM_HU_Trx_Hdr_ID(trxHdr.getM_HU_Trx_Hdr_ID()); return retrieveTrxLines(ctx, huTrxQuery, trxName); } @Override public List<I_M_HU_Trx_Line> retrieveTrxLines(final I_M_HU_Item huItem) { final Properties ctx = InterfaceWrapperHelper.getCtx(huItem); final String trxName = InterfaceWrapperHelper.getTrxName(huItem); final IHUTrxQuery huTrxQuery = createHUTrxQuery(); huTrxQuery.setM_HU_Item_ID(huItem.getM_HU_Item_ID()); return retrieveTrxLines(ctx, huTrxQuery, trxName); } @Override public I_M_HU_Trx_Line retrieveCounterpartTrxLine(final I_M_HU_Trx_Line trxLine) { final I_M_HU_Trx_Line trxLineCounterpart = trxLine.getParent_HU_Trx_Line(); if (trxLineCounterpart == null) { throw new AdempiereException("Counterpart transaction was not found for " + trxLine);
} if (HUConstants.DEBUG_07277_saveHUTrxLine && trxLineCounterpart.getM_HU_Trx_Line_ID() <= 0) { throw new AdempiereException("Counterpart transaction was not saved for " + trxLine + "\nCounterpart trx: " + trxLineCounterpart); } return trxLineCounterpart; } @Override public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHuId(@NonNull final HuId huId) { final IHUTrxQuery huTrxQuery = createHUTrxQuery(); huTrxQuery.setM_HU_ID(huId.getRepoId()); return retrieveTrxLines(Env.getCtx(), huTrxQuery, ITrx.TRXNAME_ThreadInherited); } @Override @Deprecated public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHU(final I_M_HU hu) { final Properties ctx = InterfaceWrapperHelper.getCtx(hu); final String trxName = InterfaceWrapperHelper.getTrxName(hu); final IHUTrxQuery huTrxQuery = createHUTrxQuery(); huTrxQuery.setM_HU_ID(hu.getM_HU_ID()); return retrieveTrxLines(ctx, huTrxQuery, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxDAO.java
1
请在Spring Boot框架中完成以下Java代码
public void setJndiName(@Nullable String jndiName) { this.jndiName = jndiName; } public EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() { return this.embeddedDatabaseConnection; } public void setEmbeddedDatabaseConnection(EmbeddedDatabaseConnection embeddedDatabaseConnection) { this.embeddedDatabaseConnection = embeddedDatabaseConnection; } public ClassLoader getClassLoader() { return this.classLoader; } public Xa getXa() { return this.xa; } public void setXa(Xa xa) { this.xa = xa; } /** * XA Specific datasource settings. */ public static class Xa { /** * XA datasource fully qualified name. */ private @Nullable String dataSourceClassName; /** * Properties to pass to the XA data source. */ private Map<String, String> properties = new LinkedHashMap<>(); public @Nullable String getDataSourceClassName() { return this.dataSourceClassName; } public void setDataSourceClassName(@Nullable String dataSourceClassName) { this.dataSourceClassName = dataSourceClassName; } public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } }
static class DataSourceBeanCreationException extends BeanCreationException { private final DataSourceProperties properties; private final EmbeddedDatabaseConnection connection; DataSourceBeanCreationException(String message, DataSourceProperties properties, EmbeddedDatabaseConnection connection) { super(message); this.properties = properties; this.connection = connection; } DataSourceProperties getProperties() { return this.properties; } EmbeddedDatabaseConnection getConnection() { return this.connection; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
2
请完成以下Java代码
public int getPhase() { return this.phase; } /** * Set the phase; default is 0. * @param phase the phase. */ public void setPhase(int phase) { this.phase = phase; } /** * Set to false to prevent automatic startup. * @param autoStartup the autoStartup. */ public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void start() { this.callback.accept(this.streamCreator); this.running = true; }
@Override public void stop() { this.running = false; } @Override public boolean isRunning() { return this.running; } @Override public boolean isAutoStartup() { return this.autoStartup; } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\support\StreamAdmin.java
1
请完成以下Java代码
default void addListener(int index, Listener<K, V> listener) { } /** * Add a listener. * @param listener the listener. * @since 2.5.3 */ default void addListener(Listener<K, V> listener) { } /** * Get the current list of listeners. * @return the listeners. * @since 2.5.3 */ default List<Listener<K, V>> getListeners() { return Collections.emptyList(); } /** * Add a post processor. * @param postProcessor the post processor. * @since 2.5.3 */ default void addPostProcessor(ConsumerPostProcessor<K, V> postProcessor) { } /** * Remove a post processor. * @param postProcessor the post processor. * @return true if removed. * @since 2.5.3 */ default boolean removePostProcessor(ConsumerPostProcessor<K, V> postProcessor) { return false; } /** * Get the current list of post processors. * @return the post processor. * @since 2.5.3 */ default List<ConsumerPostProcessor<K, V>> getPostProcessors() { return Collections.emptyList(); } /** * Update the consumer configuration map; useful for situations such as * credential rotation. * @param updates the configuration properties to update. * @since 2.7 */ default void updateConfigs(Map<String, Object> updates) { } /** * Remove the specified key from the configuration map. * @param configKey the key to remove. * @since 2.7 */ default void removeConfig(String configKey) {
} /** * Called whenever a consumer is added or removed. * * @param <K> the key type. * @param <V> the value type. * * @since 2.5 * */ interface Listener<K, V> { /** * A new consumer was created. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer. */ default void consumerAdded(String id, Consumer<K, V> consumer) { } /** * An existing consumer was removed. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer. */ default void consumerRemoved(@Nullable String id, Consumer<K, V> consumer) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ConsumerFactory.java
1
请完成以下Java代码
public String getA_Table_Rate_Type () { return (String)get_Value(COLUMNNAME_A_Table_Rate_Type); } /** A_Term AD_Reference_ID=53256 */ public static final int A_TERM_AD_Reference_ID=53256; /** Period = PR */ public static final String A_TERM_Period = "PR"; /** Yearly = YR */ public static final String A_TERM_Yearly = "YR"; /** Set Period/Yearly. @param A_Term Period/Yearly */ public void setA_Term (String A_Term) { set_Value (COLUMNNAME_A_Term, A_Term); } /** Get Period/Yearly. @return Period/Yearly */ public String getA_Term () { return (String)get_Value(COLUMNNAME_A_Term); } /** 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 Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Header.java
1
请完成以下Java代码
public boolean isApproved() { return approvalStatus != null && approvalStatus.isApproved(); } private boolean isEligibleForChangingPickStatus() { return !isProcessed() && getType().isPickable(); } public boolean isEligibleForPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForPicking(); } public boolean isEligibleForRejectPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForRejectPicking(); } public boolean isEligibleForPacking() { return isEligibleForChangingPickStatus() && isApproved() && pickStatus != null
&& pickStatus.isEligibleForPacking(); } public boolean isEligibleForReview() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForReview(); } public boolean isEligibleForProcessing() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForProcessing(); } public String getLocatorName() { return locator != null ? locator.getDisplayName() : ""; } @Override public List<ProductsToPickRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRow.java
1
请完成以下Java代码
private DocTypeId getOrderDocTypeId( @Nullable final JsonDocTypeInfo orderDocumentType, @Nullable final OrgId orgId) { if (orderDocumentType == null) { return null; } if (orgId == null) { throw new InvalidEntityException(TranslatableStrings.constant( "When specifying Order Document Type, the org code also has to be specified")); } final DocBaseType docBaseType = Optional.of(orderDocumentType) .map(JsonDocTypeInfo::getDocBaseType)
.map(DocBaseType::ofCode) .orElse(null); final DocSubType subType = Optional.of(orderDocumentType) .map(JsonDocTypeInfo::getDocSubType) .map(DocSubType::ofNullableCode) .orElse(DocSubType.ANY); return Optional.ofNullable(docBaseType) .map(baseType -> docTypeService.getDocTypeId(docBaseType, subType, orgId)) .orElseThrow(() -> MissingResourceException.builder() .resourceName("DocType") .parentResource(orderDocumentType) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\invoicecandidates\impl\InvoiceJsonConverters.java
1
请完成以下Java代码
public Window asAWTWindow() { return this; } @Override public void showCenterScreen() { validate(); pack(); AEnv.showCenterWindow(parentFrame, this); } @Override public void dispose() { final ProcessPanel panel = this.panel; if (panel != null) { panel.dispose(); this.panel = null; } super.dispose(); } public boolean isDisposed()
{ final ProcessPanel panel = this.panel; return panel == null || panel.isDisposed(); } @Override public void setVisible(final boolean visible) { super.setVisible(visible); final ProcessPanel panel = this.panel; if (panel != null) { panel.setVisible(visible); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessModalDialog.java
1
请完成以下Java代码
private Map<String, Pattern> getPatterns(Map<?, ?> properties, String prefix) { Map<String, Pattern> patterns = new LinkedHashMap<>(); properties.forEach((key, value) -> { String name = String.valueOf(key); if (name.startsWith(prefix)) { Pattern pattern = Pattern.compile((String) value); patterns.put(name, pattern); } }); return patterns; } public boolean isRestartInclude(URL url) { return isMatch(url.toString(), this.restartIncludePatterns); } public boolean isRestartExclude(URL url) { return isMatch(url.toString(), this.restartExcludePatterns); } public Map<String, Object> getPropertyDefaults() { return Collections.unmodifiableMap(this.propertyDefaults); } private boolean isMatch(String url, List<Pattern> patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(url).find()) { return true; } } return false; } public static DevToolsSettings get() { if (settings == null) { settings = load(); } return settings; }
static DevToolsSettings load() { return load(SETTINGS_RESOURCE_LOCATION); } static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { throw new IllegalStateException("Unable to load devtools settings from location [" + location + "]", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\settings\DevToolsSettings.java
1
请完成以下Java代码
public class ItemInstance { protected ItemDefinition item; protected StructureInstance structureInstance; public ItemInstance(ItemDefinition item, StructureInstance structureInstance) { this.item = item; this.structureInstance = structureInstance; } public ItemDefinition getItem() { return this.item; } public StructureInstance getStructureInstance() {
return this.structureInstance; } private FieldBaseStructureInstance getFieldBaseStructureInstance() { return (FieldBaseStructureInstance) this.structureInstance; } public Object getFieldValue(String fieldName) { return this.getFieldBaseStructureInstance().getFieldValue(fieldName); } public void setFieldValue(String fieldName, Object value) { this.getFieldBaseStructureInstance().setFieldValue(fieldName, value); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\ItemInstance.java
1
请完成以下Java代码
public List<PickFromHU> getPickFromHUs() { return pickFromHUs; } public String getDescription() { final StringBuilder description = new StringBuilder(); for (final PickFromHU pickFromHU : pickFromHUs) { final String huValue = String.valueOf(pickFromHU.getHuId().getRepoId()); if (description.length() > 0) { description.append(", "); } description.append(huValue); } description.insert(0, Services.get(IMsgBL.class).translate(Env.getCtx(), "M_HU_ID") + ": "); return description.toString(); } public LotNumberQuarantine getLotNumberQuarantine() { return lotNoQuarantine; }
public Map<I_M_Attribute, Object> getAttributes() { return attributes; } // // --------------------------------------------------------------- // @Value @Builder public static class PickFromHU { @NonNull HuId huId; @NonNull Quantity qtyToPick; @NonNull Quantity qtyToPickInStockingUOM; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineCandidate.java
1
请完成以下Java代码
private void growScrollbars() { // fatter scroll bars Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; scrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(SCROLL_Size, 0)); scrollPane.getHorizontalScrollBar().setPreferredSize(new Dimension(0, SCROLL_Size)); } } } @Override public String prepareTable(ColumnInfo[] layout, String from, String where, boolean multiSelection, String tableName) { for (int i = 0; i < layout.length; i++) { if (layout[i].getColClass() == IDColumn.class) { idColumnIndex = i; break; } } sql = super.prepareTable(layout, from, where, multiSelection, tableName); return sql; } public String getSQL() { return sql; } public void prepareTable(Class<?> cl, String[] columnNames, String sqlWhere, String sqlOrderBy) { ColumnInfo[] layout = MiniTableUtil.createColumnInfo(cl, columnNames); String tableName = MiniTableUtil.getTableName(cl); String from = tableName; final boolean multiSelection = false; prepareTable(layout, from, sqlWhere, multiSelection, tableName); if (!Check.isEmpty(sqlOrderBy, true)) { sql += " ORDER BY " + sqlOrderBy; } } public void loadData(Object... sqlParams) { if (sql == null) throw new IllegalStateException("Table not initialized. Please use prepareTable method first"); int selectedId = getSelectedId(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); this.loadTable(rs); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } selectById(selectedId); } public int getSelectedId() { if (idColumnIndex < 0) return -1; int row = getSelectedRow(); if (row != -1) { Object data = getModel().getValueAt(row, 0); if (data != null) { Integer id = ((IDColumn)data).getRecord_ID();
return id == null ? -1 : id.intValue(); } } return -1; } public void selectById(int id) { selectById(id, true); } public void selectById(int id, boolean fireEvent) { if (idColumnIndex < 0) return; boolean fireSelectionEventOld = fireSelectionEvent; try { fireSelectionEvent = fireEvent; if (id < 0) { this.getSelectionModel().removeSelectionInterval(0, this.getRowCount()); return; } for (int i = 0; i < this.getRowCount(); i++) { IDColumn key = (IDColumn)this.getModel().getValueAt(i, idColumnIndex); if (key != null && id > 0 && key.getRecord_ID() == id) { this.getSelectionModel().setSelectionInterval(i, i); break; } } } finally { fireSelectionEvent = fireSelectionEventOld; } } private boolean fireSelectionEvent = true; }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\swing\MiniTable2.java
1
请完成以下Java代码
protected List<InetAddress> getLocalAllInetAddress() throws Exception { List<InetAddress> result = new ArrayList<>(4); // 遍历所有的网络接口 for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) { NetworkInterface iface = networkInterfaces.nextElement(); // 在所有的接口下再遍历 IP for (Enumeration<InetAddress> inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) { InetAddress inetAddr = inetAddresses.nextElement(); //排除 LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress 类型的 IP 地址 if (!inetAddr.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/ && !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()) { result.add(inetAddr); } } } return result; } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: AbstractServerInfos.java </p> * <p>方法描述: 获取某个网络接口的 Mac 地址 </p> * <p>创建时间: 2020/10/10 11:03 </p> * * @param inetAddr inetAddr * @return java.lang.String * @author 方瑞冬 * @version 1.0 */ protected String getMacByInetAddress(InetAddress inetAddr) {
try { byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mac.length; i++) { if (i != 0) { stringBuilder.append("-"); } //将十六进制 byte 转化为字符串 String temp = Integer.toHexString(mac[i] & 0xff); if (temp.length() == 1) { stringBuilder.append("0").append(temp); } else { stringBuilder.append(temp); } } return stringBuilder.toString().toUpperCase(); } catch (SocketException e) { e.printStackTrace(); } return null; } }
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\AbstractServerInfos.java
1
请完成以下Spring Boot application配置
server: port: 8090 spring: security: oauth2: client: provider: spring-auth-server: issuer-uri: http://localhost:8080 registration: test-client: provider: spring-auth-server client-name: test-client client-id: ignored # Dynamically set client-secret: ignored # Dynamically set authorization-grant-type: - authorization_code - refresh_token - client_credentials scope: - openid - email - profile baeldung: security: client: registration:
registration-endpoint: http://localhost:8080/connect/register registration-username: registrar-client registration-password: secret token-endpoint: http://localhost:8080/oauth2/token registration-scopes: client.create grant-types: client_credentials
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\resources\application.yaml
2
请完成以下Java代码
public class CustomerDeserializer extends StdDeserializer<Customer> { private static final long serialVersionUID = 1L; public CustomerDeserializer() { this(null); } public CustomerDeserializer(Class<Customer> t) { super(t); } @Override public Customer deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException { Customer feedback = new Customer(); ObjectCodec codec = parser.getCodec(); JsonNode node = codec.readTree(parser); feedback.setId(node.get(0) .asLong()); feedback.setFirstName(node.get(1) .asText()); feedback.setLastName(node.get(2) .asText());
feedback.setStreet(node.get(3) .asText()); feedback.setPostalCode(node.get(4) .asText()); feedback.setCity(node.get(5) .asText()); feedback.setState(node.get(6) .asText()); JsonNode phoneNumber = node.get(7); feedback.setPhoneNumber(phoneNumber.isNull() ? null : phoneNumber.asText()); JsonNode email = node.get(8); feedback.setEmail(email.isNull() ? null : email.asText()); return feedback; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\CustomerDeserializer.java
1
请完成以下Java代码
public class SetRemovalTimeToHistoricDecisionInstancesBuilderImpl implements SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder { protected HistoricDecisionInstanceQuery query; protected List<String> ids; protected Date removalTime; protected Mode mode = null; protected boolean isHierarchical; protected CommandExecutor commandExecutor; public SetRemovalTimeToHistoricDecisionInstancesBuilderImpl(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } public SetRemovalTimeToHistoricDecisionInstancesBuilder byQuery(HistoricDecisionInstanceQuery query) { this.query = query; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder byIds(String... ids) { this.ids = ids != null ? Arrays.asList(ids) : null; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder absoluteRemovalTime(Date removalTime) { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.ABSOLUTE_REMOVAL_TIME; this.removalTime = removalTime; return this; } @Override public SetRemovalTimeToHistoricDecisionInstancesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
mode = Mode.CLEARED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder hierarchical() { isHierarchical = true; return this; } public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricDecisionInstancesCmd(this)); } public HistoricDecisionInstanceQuery getQuery() { return query; } public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } public boolean isHierarchical() { return isHierarchical; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricDecisionInstancesBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class RelatedInvoicesForSubscriptionsProvider implements RelatedRecordsProvider { @Override public SourceRecordsKey getSourceRecordsKey() { return SourceRecordsKey.of(I_C_Flatrate_Term.Table_Name); } @Override public IPair<SourceRecordsKey, List<ITableRecordReference>> provideRelatedRecords( @NonNull final List<ITableRecordReference> records) { final List<FlatrateTermId> flatrateTermIds = records .stream() .map(ref -> FlatrateTermId.ofRepoId(ref.getRecord_ID())) .collect(ImmutableList.toImmutableList()); final IQueryBL queryBL = Services.get(IQueryBL.class); final ImmutableList<ITableRecordReference> invoiceReferences = queryBL.createQueryBuilder(I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, getTableId(I_C_Flatrate_Term.class)) .addInArrayFilter(I_C_Invoice_Candidate.COLUMNNAME_Record_ID, flatrateTermIds) .andCollectChildren(I_C_Invoice_Line_Alloc.COLUMN_C_Invoice_Candidate_ID)
.addOnlyActiveRecordsFilter() .andCollect(I_C_Invoice_Line_Alloc.COLUMN_C_InvoiceLine_ID) .andCollect(I_C_InvoiceLine.COLUMN_C_Invoice_ID) .create() .listIds() .stream() .map(invoiceRepoId -> TableRecordReference.of(I_C_Invoice.Table_Name, invoiceRepoId)) .collect(ImmutableList.toImmutableList()); final SourceRecordsKey resultSourceRecordsKey = SourceRecordsKey.of(I_C_Invoice.Table_Name); final IPair<SourceRecordsKey, List<ITableRecordReference>> result = ImmutablePair.of(resultSourceRecordsKey, invoiceReferences); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\order\restart\RelatedInvoicesForSubscriptionsProvider.java
2
请完成以下Java代码
void shutDownGracefully(GracefulShutdownCallback callback) { logger.info("Commencing graceful shutdown. Waiting for active requests to complete"); CountDownLatch shutdownUnderway = new CountDownLatch(1); new Thread(() -> doShutdown(callback, shutdownUnderway), "tomcat-shutdown").start(); try { shutdownUnderway.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } private void doShutdown(GracefulShutdownCallback callback, CountDownLatch shutdownUnderway) { try { List<Connector> connectors = getConnectors(); connectors.forEach(this::close); shutdownUnderway.countDown(); awaitInactiveOrAborted(); if (this.aborted) { logger.info("Graceful shutdown aborted with one or more requests still active"); callback.shutdownComplete(GracefulShutdownResult.REQUESTS_ACTIVE); } else { logger.info("Graceful shutdown complete"); callback.shutdownComplete(GracefulShutdownResult.IDLE); } } finally { shutdownUnderway.countDown(); } } private List<Connector> getConnectors() { List<Connector> connectors = new ArrayList<>(); for (Service service : this.tomcat.getServer().findServices()) { Collections.addAll(connectors, service.findConnectors()); } return connectors; } private void close(Connector connector) { connector.pause(); connector.getProtocolHandler().closeServerSocketGraceful(); } private void awaitInactiveOrAborted() { try {
for (Container host : this.tomcat.getEngine().findChildren()) { for (Container context : host.findChildren()) { while (!this.aborted && isActive(context)) { Thread.sleep(50); } } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } private boolean isActive(Container context) { try { if (((StandardContext) context).getInProgressAsyncCount() > 0) { return true; } for (Container wrapper : context.findChildren()) { if (((StandardWrapper) wrapper).getCountAllocated() > 0) { return true; } } return false; } catch (Exception ex) { throw new RuntimeException(ex); } } void abort() { this.aborted = true; } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\GracefulShutdown.java
1
请完成以下Java代码
public void createWorkFlowAndBom(final I_PP_Order ppOrderRecord) { createWorkflowAndBOM(ppOrderRecord); } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_PP_Order.COLUMNNAME_QtyEntered, I_PP_Order.COLUMNNAME_DateStartSchedule, I_PP_Order.COLUMNNAME_AD_Workflow_ID, I_PP_Order.COLUMNNAME_PP_Product_BOM_ID }) public void updateAndPostEventOnQtyEnteredChange(final I_PP_Order ppOrderRecord) { if (ppOrderBL.isSomethingProcessed(ppOrderRecord)) { throw new LiberoException("Cannot quantity is not allowed because there is something already processed on this order"); // TODO: trl } final PPOrderChangedEventFactory eventFactory = PPOrderChangedEventFactory.newWithPPOrderBeforeChange(ppOrderConverter, ppOrderRecord); final PPOrderId orderId = PPOrderId.ofRepoId(ppOrderRecord.getPP_Order_ID()); deleteWorkflowAndBOM(orderId); createWorkflowAndBOM(ppOrderRecord); final PPOrderChangedEvent event = eventFactory.inspectPPOrderAfterChange(); materialEventService.enqueueEventAfterNextCommit(event); } private void deleteWorkflowAndBOM(final PPOrderId orderId) { ppOrderRoutingRepository.deleteByOrderId(orderId); ppOrderBOMDAO.deleteByOrderId(orderId); } private void createWorkflowAndBOM(final I_PP_Order ppOrder) { ppOrderBL.createOrderRouting(ppOrder); ppOrderBOMBL.createOrderBOMAndLines(ppOrder); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void beforeDelete(@NonNull final I_PP_Order ppOrder) { // // Delete depending records final String docStatus = ppOrder.getDocStatus(); if (X_PP_Order.DOCSTATUS_Drafted.equals(docStatus) || X_PP_Order.DOCSTATUS_InProgress.equals(docStatus)) {
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); orderCostsService.deleteByOrderId(ppOrderId); deleteWorkflowAndBOM(ppOrderId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_PP_Order.COLUMNNAME_M_Product_ID, I_PP_Order.COLUMNNAME_PP_Product_BOM_ID }) public void validateBOMAndProduct(@NonNull final I_PP_Order ppOrder) { final ProductBOMId bomId = ProductBOMId.ofRepoId(ppOrder.getPP_Product_BOM_ID()); final ProductId productIdOfBOM = productBOMDAO.getBOMProductId(bomId); if (ppOrder.getM_Product_ID() != productIdOfBOM.getRepoId()) { throw new AdempiereException(AdMessageKey.of("PP_Order_BOM_Doesnt_Match")) .markAsUserValidationError() .appendParametersToMessage() .setParameter("PP_Order.M_Product_ID", ppOrder.getM_Product_ID()) .setParameter("PP_Order.PP_Product_BOM_ID.M_Product_ID", productIdOfBOM.getRepoId()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void setSeqNo(final I_PP_Order ppOrder) { if (ppOrder.getSeqNo() <= 0) { ppOrder.setSeqNo(ppOrderDAO.getNextSeqNoPerDateStartSchedule(ppOrder).toInt()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Order.java
1
请完成以下Java代码
public static IncotermsId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, IncotermsId.class, IncotermsId::ofRepoId); } public static int toRepoId(@Nullable final IncotermsId incotermsId) { return toRepoIdOr(incotermsId, -1); } public static int toRepoIdOr(@Nullable final IncotermsId incotermsId, final int defaultValue) { return incotermsId != null ? incotermsId.getRepoId() : defaultValue; }
private IncotermsId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Incoterms_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final IncotermsId o1, @Nullable final IncotermsId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsId.java
1
请在Spring Boot框架中完成以下Java代码
public class ProjectInfoProperties { private final Build build = new Build(); private final Git git = new Git(); public Build getBuild() { return this.build; } public Git getGit() { return this.git; } /** * Build specific info properties. */ public static class Build { /** * Location of the generated build-info.properties file. */ private Resource location = new ClassPathResource("META-INF/build-info.properties"); /** * File encoding. */ private Charset encoding = StandardCharsets.UTF_8; public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } } /** * Git specific info properties. */ public static class Git { /** * Location of the generated git.properties file.
*/ private Resource location = new ClassPathResource("git.properties"); /** * File encoding. */ private Charset encoding = StandardCharsets.UTF_8; public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\info\ProjectInfoProperties.java
2
请完成以下Java代码
public ExternalSystemId getExternalSystemIdByExternalSystemCode(@NonNull final JsonPurchaseCandidateCreateItem request) { return externalSystemRepository.getIdByType(ExternalSystemType.ofValue(request.getExternalSystemCode())); } @Nullable public String getExternalSystemTypeById(@NonNull final PurchaseCandidate purchaseCandidate) { return Optional.ofNullable(purchaseCandidate.getExternalSystemId()) .map(externalSystemId -> externalSystemRepository.getById(externalSystemId).getType().toJson()) .orElse(null); } @NonNull public List<ExternalSystemIdWithExternalIds> fromJson(@NonNull final List<JsonPurchaseCandidateReference> candidates) {
final List<ExternalSystemIdWithExternalIds> externalSystemIdWithExternalIds = new ArrayList<>(); for (final JsonPurchaseCandidateReference cand : candidates) { final ExternalHeaderIdWithExternalLineIds headerAndLineId = ExternalHeaderIdWithExternalLineIds.builder() .externalHeaderId(JsonExternalIds.toExternalId(cand.getExternalHeaderId())) .externalLineIds(JsonExternalIds.toExternalIds(cand.getExternalLineIds())) .build(); externalSystemIdWithExternalIds.add(ExternalSystemIdWithExternalIds.builder() .externalSystemId(externalSystemRepository.getIdByType(ExternalSystemType.ofValue(cand.getExternalSystemCode()))) .externalHeaderIdWithExternalLineIds(headerAndLineId) .build()); } return externalSystemIdWithExternalIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\POJsonConverters.java
1
请完成以下Java代码
public TaxAmountType1Choice getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link TaxAmountType1Choice } * */ public void setTp(TaxAmountType1Choice value) { this.tp = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } *
*/ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TaxAmountAndType1.java
1
请完成以下Java代码
public void setIsFetchedFrom (final boolean IsFetchedFrom) { set_Value (COLUMNNAME_IsFetchedFrom, IsFetchedFrom); } @Override public boolean isFetchedFrom() { return get_ValueAsBoolean(COLUMNNAME_IsFetchedFrom); } @Override public void setIsPayFrom (final boolean IsPayFrom) { set_Value (COLUMNNAME_IsPayFrom, IsPayFrom); } @Override public boolean isPayFrom() { return get_ValueAsBoolean(COLUMNNAME_IsPayFrom); } @Override public void setIsRemitTo (final boolean IsRemitTo) { set_Value (COLUMNNAME_IsRemitTo, IsRemitTo); } @Override public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * Role AD_Reference_ID=541254 * Reference name: Role */ public static final int ROLE_AD_Reference_ID=541254; /** Main Producer = MP */ public static final String ROLE_MainProducer = "MP"; /** Hostpital = HO */ public static final String ROLE_Hostpital = "HO"; /** Physician Doctor = PD */ public static final String ROLE_PhysicianDoctor = "PD"; /** General Practitioner = GP */ public static final String ROLE_GeneralPractitioner = "GP"; /** Health Insurance = HI */ public static final String ROLE_HealthInsurance = "HI"; /** Nursing Home = NH */ public static final String ROLE_NursingHome = "NH"; /** Caregiver = CG */ public static final String ROLE_Caregiver = "CG"; /** Preferred Pharmacy = PP */ public static final String ROLE_PreferredPharmacy = "PP"; /** Nursing Service = NS */ public static final String ROLE_NursingService = "NS"; /** Payer = PA */ public static final String ROLE_Payer = "PA"; /** Payer = PA */ public static final String ROLE_Pharmacy = "PH"; @Override public void setRole (final @Nullable java.lang.String Role) { set_Value (COLUMNNAME_Role, Role); } @Override public java.lang.String getRole() { return get_ValueAsString(COLUMNNAME_Role); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java
1
请完成以下Java代码
public BooleanWithReason recomputeSumsFromLines() { if (isImported) { //leave the values as is if the record was imported return BooleanWithReason.falseBecause("The remittance advice is imported!"); } Amount remittedAmountSumAmount = null; Amount paymentDiscountAmountSumAmount = null; Amount serviceFeeSumAmount = null; for (final RemittanceAdviceLine line : lines) { remittedAmountSumAmount = remittedAmountSumAmount == null ? line.getRemittedAmountAdjusted() : remittedAmountSumAmount.add(line.getRemittedAmountAdjusted()); if (line.getPaymentDiscountAmount() != null) { paymentDiscountAmountSumAmount = paymentDiscountAmountSumAmount == null ? line.getPaymentDiscountAmount() : paymentDiscountAmountSumAmount.add(line.getPaymentDiscountAmount()); } if (line.getServiceFeeAmount() != null) { serviceFeeSumAmount = serviceFeeSumAmount == null ? line.getServiceFeeAmount() : serviceFeeSumAmount.add(line.getServiceFeeAmount()); } } remittedAmountSum = remittedAmountSumAmount != null ? remittedAmountSumAmount.toBigDecimal() : BigDecimal.ZERO; paymentDiscountAmountSum = paymentDiscountAmountSumAmount != null ? paymentDiscountAmountSumAmount.toBigDecimal() : null; serviceFeeAmount = serviceFeeSumAmount != null ? serviceFeeSumAmount.toBigDecimal() : null; if (serviceFeeAmount != null && serviceFeeAmount.signum() != 0 && serviceFeeCurrencyId == null) { throw new AdempiereException("Missing ServiceFeeCurrencyID!"); } return BooleanWithReason.TRUE;
} public void setPaymentId(@NonNull final PaymentId paymentId) { this.paymentId = paymentId; } /** * @return true, if acknowledged status changed, false otherwise */ public boolean recomputeIsDocumentAcknowledged() { final boolean isDocumentAcknowledged_refreshedValue = lines.stream().allMatch(RemittanceAdviceLine::isReadyForCompletion); final boolean hasAcknowledgedStatusChanged = isDocumentAcknowledged != isDocumentAcknowledged_refreshedValue; this.isDocumentAcknowledged = isDocumentAcknowledged_refreshedValue; return hasAcknowledgedStatusChanged; } /** * @return true, if read only currencies flag changed, false otherwise */ public boolean recomputeCurrenciesReadOnlyFlag() { final boolean currenciesReadOnlyFlag_refreshedValue = lines.stream().anyMatch(RemittanceAdviceLine::isInvoiceResolved); final boolean currenciesReadOnlyFlagChanged = currenciesReadOnlyFlag != currenciesReadOnlyFlag_refreshedValue; this.currenciesReadOnlyFlag = currenciesReadOnlyFlag_refreshedValue; return currenciesReadOnlyFlagChanged; } public void setProcessedFlag(final boolean processed) { this.processed = processed; getLines().forEach(line -> line.setProcessed(processed)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\RemittanceAdvice.java
1
请完成以下Java代码
public ELContext build() { CompositeELResolver elResolver = createCompositeResolver(); return new ActivitiElContext(elResolver); } public ELContext buildWithCustomFunctions(List<CustomFunctionProvider> customFunctionProviders) { CompositeELResolver elResolver = createCompositeResolver(); ActivitiElContext elContext = new ActivitiElContext(elResolver); try { addDateFunctions(elContext); addListFunctions(elContext); if (customFunctionProviders != null) { customFunctionProviders.forEach(provider -> { try { provider.addCustomFunctions(elContext); } catch (Exception e) { logger.error("Error setting up EL custom functions", e); } });
} } catch (NoSuchMethodException e) { logger.error("Error setting up EL custom functions", e); } return elContext; } private void addResolvers(CompositeELResolver compositeResolver) { Stream.ofNullable(resolvers).flatMap(Collection::stream).forEach(compositeResolver::add); } private CompositeELResolver createCompositeResolver() { CompositeELResolver elResolver = new CompositeELResolver(); elResolver.add( new ReadOnlyMapELResolver((Objects.nonNull(variables) ? new HashMap<>(variables) : Collections.emptyMap())) ); addResolvers(elResolver); return elResolver; } }
repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ELContextBuilder.java
1
请完成以下Java代码
public CostDetailCreateRequest withQty(@NonNull final Quantity qty) { if (Objects.equals(this.qty, qty)) { return this; } return toBuilder().qty(qty).build(); } public CostDetailCreateRequest withQtyZero() { return withQty(qty.toZero()); } public CostDetailBuilder toCostDetailBuilder() { final CostDetailBuilder costDetail = CostDetail.builder() .clientId(getClientId()) .orgId(getOrgId()) .acctSchemaId(getAcctSchemaId()) .productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId()) // .amtType(getAmtType()) .amt(getAmt()) .qty(getQty()) // .documentRef(getDocumentRef()) .description(getDescription()) .dateAcct(getDate()); if (isExplicitCostElement()) { costDetail.costElementId(getCostElementId()); } return costDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateRequest.java
1
请完成以下Java代码
public class LocalDateRestVariableConverter implements RestVariableConverter { @Override public String getRestTypeName() { return "localDate"; } @Override public Class<?> getVariableType() { return LocalDate.class; } @Override public Object getVariableValue(EngineRestVariable result) { if (result.getValue() != null) { if (!(result.getValue() instanceof String)) { throw new FlowableIllegalArgumentException("Converter can only convert string to localDate"); } try { return LocalDate.parse((String) result.getValue()); } catch (DateTimeParseException e) {
throw new FlowableIllegalArgumentException("The given variable value is not a localDate: '" + result.getValue() + "'", e); } } return null; } @Override public void convertVariableValue(Object variableValue, EngineRestVariable result) { if (variableValue != null) { if (!(variableValue instanceof LocalDate)) { throw new FlowableIllegalArgumentException("Converter can only convert localDate"); } result.setValue(variableValue.toString()); } else { result.setValue(null); } } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\LocalDateRestVariableConverter.java
1
请完成以下Java代码
public String getSecureHttpHeadersAsString() { return secureHttpHeaders != null ? secureHttpHeaders.formatAsString(true) : null; } public void setSecureHttpHeaders(HttpHeaders secureHttpHeaders) { this.secureHttpHeaders = secureHttpHeaders; } public String getBody() { return body; } public void setBody(String body) { if (multiValueParts != null && !multiValueParts.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both body and multi value parts"); } else if (formParameters != null && !formParameters.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both body and form parameters"); } this.body = body; } public String getBodyEncoding() { return bodyEncoding; } public void setBodyEncoding(String bodyEncoding) { this.bodyEncoding = bodyEncoding; } public Collection<MultiValuePart> getMultiValueParts() { return multiValueParts; } public void addMultiValuePart(MultiValuePart part) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and multi value parts"); } else if (formParameters != null && !formParameters.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both form parameters and multi value parts"); } if (multiValueParts == null) { multiValueParts = new ArrayList<>(); } multiValueParts.add(part); } public Map<String, List<String>> getFormParameters() {
return formParameters; } public void addFormParameter(String key, String value) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and form parameters"); } else if (multiValueParts != null && !multiValueParts.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both multi value parts and form parameters"); } if (formParameters == null) { formParameters = new LinkedHashMap<>(); } formParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public boolean isNoRedirects() { return noRedirects; } public void setNoRedirects(boolean noRedirects) { this.noRedirects = noRedirects; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpRequest.java
1
请完成以下Java代码
public void debugConcurrentScopeIsPruned(PvmExecutionImpl execution) { logDebug( "036", "Concurrent scope is pruned {}", execution); } public void debugCancelConcurrentScopeExecution(PvmExecutionImpl execution) { logDebug( "037", "Cancel concurrent scope execution {}", execution); } public void destroyConcurrentScopeExecution(PvmExecutionImpl execution) { logDebug( "038", "Destroy concurrent scope execution", execution); } public void completeNonScopeEventSubprocess() { logDebug( "039", "Destroy non-socpe event subprocess"); } public void endConcurrentExecutionInEventSubprocess() { logDebug( "040", "End concurrent execution in event subprocess"); } public ProcessEngineException missingDelegateVariableMappingParentClassException(String className, String delegateVarMapping) { return new ProcessEngineException( exceptionMessage("041", "Class '{}' doesn't implement '{}'.", className, delegateVarMapping)); }
public ProcessEngineException missingBoundaryCatchEventError(String executionId, String errorCode, String errorMessage) { return new ProcessEngineException( exceptionMessage( "042", "Execution with id '{}' throws an error event with errorCode '{}' and errorMessage '{}', but no error handler was defined. ", executionId, errorCode, errorMessage)); } public ProcessEngineException missingBoundaryCatchEventEscalation(String executionId, String escalationCode) { return new ProcessEngineException( exceptionMessage( "043", "Execution with id '{}' throws an escalation event with escalationCode '{}', but no escalation handler was defined. ", executionId, escalationCode)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnBehaviorLogger.java
1
请完成以下Java代码
public int getCM_NewsChannel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsChannel_ID); if (ii == null) return 0; return ii.intValue(); } /** Set News Item / Article. @param CM_NewsItem_ID News item or article defines base content */ public void setCM_NewsItem_ID (int CM_NewsItem_ID) { if (CM_NewsItem_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_NewsItem_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_NewsItem_ID, Integer.valueOf(CM_NewsItem_ID)); } /** Get News Item / Article. @return News item or article defines base content */ public int getCM_NewsItem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsItem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Content HTML. @param ContentHTML Contains the content itself */ public void setContentHTML (String ContentHTML) { set_Value (COLUMNNAME_ContentHTML, ContentHTML); } /** Get Content HTML. @return Contains the content itself */ public String getContentHTML () { return (String)get_Value(COLUMNNAME_ContentHTML); } /** 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 LinkURL. @param LinkURL Contains URL to a target */ public void setLinkURL (String LinkURL) { set_Value (COLUMNNAME_LinkURL, LinkURL); } /** Get LinkURL. @return Contains URL to a target */ public String getLinkURL () { return (String)get_Value(COLUMNNAME_LinkURL); } /** Set Publication Date. @param PubDate Date on which this article will / should get published */ public void setPubDate (Timestamp PubDate) { set_Value (COLUMNNAME_PubDate, PubDate); } /** Get Publication Date. @return Date on which this article will / should get published */ public Timestamp getPubDate () { return (Timestamp)get_Value(COLUMNNAME_PubDate); } /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
1
请完成以下Java代码
public final class NetUtils { private NetUtils() { } /** * * @return never returns <code>null</code> */ public static IHostIdentifier getLocalHost() { InetAddress localHostAddress; try { localHostAddress = InetAddress.getLocalHost(); } catch (final UnknownHostException e) { // fallback localHostAddress = InetAddress.getLoopbackAddress(); } return of(localHostAddress); } public static IHostIdentifier of(final String hostOrAddress) throws UnknownHostException { Check.assumeNotEmpty(hostOrAddress, "hostOrAddress not empty"); final InetAddress inetAddress = InetAddress.getByName(hostOrAddress); return of(inetAddress); } public static IHostIdentifier of(@NonNull final InetAddress inetAddress) { final String hostAddress = inetAddress.getHostAddress(); final String hostName = inetAddress.getHostName(); return new HostIdentifier(hostName, hostAddress); } @Immutable private static final class HostIdentifier implements IHostIdentifier { private final String hostName; private final String hostAddress; private transient String _toString; private transient Integer _hashcode; private HostIdentifier(final String hostName, final String hostAddress) { this.hostAddress = hostAddress; this.hostName = hostName; } @Override public String toString() { if (_toString == null) { _toString = (hostName != null ? hostName : "") + "/" + hostAddress; } return _toString; } @Override public int hashCode() {
if (_hashcode == null) { _hashcode = Objects.hash(hostName, hostAddress); } return _hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HostIdentifier) { final HostIdentifier other = (HostIdentifier)obj; return Objects.equals(hostName, other.hostName) && Objects.equals(hostAddress, other.hostAddress); } else { return false; } } @Override public String getIP() { return hostAddress; } @Override public String getHostName() { return hostName; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\net\NetUtils.java
1
请在Spring Boot框架中完成以下Java代码
public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId; } public Boolean getIncludeLocalVariables() { return includeLocalVariables; } public void setIncludeLocalVariables(Boolean includeLocalVariables) { this.includeLocalVariables = includeLocalVariables; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public void setCaseInstanceIds(Set<String> caseInstanceIds) { this.caseInstanceIds = caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
protected Class<? extends Annotation> getAnnotationType() { return EnableDurableClient.class; } @Override @SuppressWarnings("all") public void setImportMetadata(AnnotationMetadata importMetadata) { if (isAnnotationPresent(importMetadata)) { AnnotationAttributes enableDurableClientAttributes = getAnnotationAttributes(importMetadata); this.durableClientId = enableDurableClientAttributes.containsKey("id") ? enableDurableClientAttributes.getString("id") : null; this.durableClientTimeout = enableDurableClientAttributes.containsKey("timeout") ? enableDurableClientAttributes.getNumber("timeout") : DEFAULT_DURABLE_CLIENT_TIMEOUT; this.keepAlive = enableDurableClientAttributes.containsKey("keepAlive") ? enableDurableClientAttributes.getBoolean("keepAlive") : DEFAULT_KEEP_ALIVE; this.readyForEvents = enableDurableClientAttributes.containsKey("readyForEvents") ? enableDurableClientAttributes.getBoolean("readyForEvents") : DEFAULT_READY_FOR_EVENTS; } } protected Optional<String> getDurableClientId() { return Optional.ofNullable(this.durableClientId) .filter(StringUtils::hasText); } protected Integer getDurableClientTimeout() { return this.durableClientTimeout != null ? this.durableClientTimeout : DEFAULT_DURABLE_CLIENT_TIMEOUT; } protected Boolean getKeepAlive() { return this.keepAlive != null ? this.keepAlive : DEFAULT_KEEP_ALIVE; }
protected Boolean getReadyForEvents() { return this.readyForEvents != null ? this.readyForEvents : DEFAULT_READY_FOR_EVENTS; } protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive()); clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); } @Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2
请完成以下Java代码
public boolean isNegateToConvertToRealValue() { return getToRealValueMultiplier() < 0; } private int getToRealValueMultiplier() { int toRealValueMultiplier = this.toRealValueMultiplier; if (toRealValueMultiplier == 0) { toRealValueMultiplier = this.toRealValueMultiplier = computeToRealValueMultiplier(); } return toRealValueMultiplier; } private int computeToRealValueMultiplier() { int multiplier = 1; // Adjust by SOTrx if needed if (!isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Adjust by Credit Memo if needed if (!isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } private int getToRelativeValueMultiplier() { // NOTE: the relative->real and real->relative value multipliers are the same return getToRealValueMultiplier(); } public Money fromNotAdjustedAmount(@NonNull final Money money)
{ final int multiplier = computeFromNotAdjustedAmountMultiplier(); return multiplier > 0 ? money : money.negate(); } private int computeFromNotAdjustedAmountMultiplier() { int multiplier = 1; // Do we have to SO adjust? if (isAPAdjusted) { final int multiplierAP = soTrx.isPurchase() ? -1 : +1; multiplier *= multiplierAP; } // Do we have to adjust by Credit Memo? if (isCreditMemoAdjusted) { final int multiplierCM = isCreditMemo ? -1 : +1; multiplier *= multiplierCM; } return multiplier; } /** * @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise. */ public boolean isOutgoingMoney() { return isCreditMemo ^ soTrx.isPurchase(); } public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew) { return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern(); } public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew) { return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java
1
请在Spring Boot框架中完成以下Java代码
public class FailedJobListener implements CommandContextCloseListener { private static final Logger LOGGER = LoggerFactory.getLogger(FailedJobListener.class); protected CommandExecutor commandExecutor; protected Job job; protected JobServiceConfiguration jobServiceConfiguration; public FailedJobListener(CommandExecutor commandExecutor, Job job, JobServiceConfiguration jobServiceConfiguration) { this.commandExecutor = commandExecutor; this.job = job; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public void closing(CommandContext commandContext) { } @Override public void afterSessionsFlush(CommandContext commandContext) { } @Override public void closed(CommandContext context) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_EXECUTION_SUCCESS, job), jobServiceConfiguration.getEngineName());
} } @Override public void closeFailure(CommandContext commandContext) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityExceptionEvent(FlowableEngineEventType.JOB_EXECUTION_FAILURE, job, commandContext.getException()), jobServiceConfiguration.getEngineName()); } CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew(); FailedJobCommandFactory failedJobCommandFactory = jobServiceConfiguration.getFailedJobCommandFactory(); Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), commandContext.getException()); LOGGER.trace("Using FailedJobCommandFactory '{}' and command of type '{}'", failedJobCommandFactory.getClass(), cmd.getClass()); commandExecutor.execute(commandConfig, cmd); } @Override public Integer order() { return 20; } @Override public boolean multipleAllowed() { return true; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\FailedJobListener.java
2
请在Spring Boot框架中完成以下Java代码
public RecordMessageConverter converter() { JsonMessageConverter converter = new JsonMessageConverter(); DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); typeMapper.setTypePrecedence(TypePrecedence.TYPE_ID); typeMapper.addTrustedPackages("com.common"); Map<String, Class<?>> mappings = new HashMap<>(); mappings.put("foo", Foo2.class); mappings.put("bar", Bar2.class); typeMapper.setIdClassMapping(mappings); converter.setTypeMapper(typeMapper); return converter; } @Bean public NewTopic foos() { return new NewTopic("foos", 1, (short) 1); }
@Bean public NewTopic bars() { return new NewTopic("bars", 1, (short) 1); } @Bean @Profile("default") // Don't run from test(s) public ApplicationRunner runner() { return args -> { System.out.println("Hit Enter to terminate..."); System.in.read(); }; } }
repos\spring-kafka-main\samples\sample-02\src\main\java\com\example\Application.java
2
请完成以下Java代码
public class Brand { /** * The name of the brand. */ private String name; /** * Instantiates a new Brand. * * @param name * the {@link #name} */ public Brand(String name) { this.name = name; } /**
* Gets the {@link #name}. * * @return the {@link #name} */ public String getName() { return name; } /** * Sets the {@link #name}. * * @param name * the new {@link #name} */ public void setName(String name) { this.name = name; } }
repos\tutorials-master\di-modules\dagger\src\main\java\com\baeldung\dagger\intro\Brand.java
1
请在Spring Boot框架中完成以下Java代码
public class UserData { private final UserId userId; private final Password password; private final Set<RoleId> roles; @JsonCreator public UserData(@JsonProperty("userId") UserId userId, @JsonProperty("password") Password password, @JsonProperty("roles") Set<RoleId> roles) { this.userId = userId; this.password = password; this.roles = roles; } public UserData(UserId userId, Password password, String ... roles) { this.userId = userId; this.password = password; this.roles = new HashSet<>();
for (String role: roles) { this.roles.add(new RoleId(role)); } } public UserId getUserId() { return userId; } public boolean verifyPassword(String password) { return this.password.verify(password); } public Set<RoleId> getRoles() { return roles; } }
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\services\dto\UserData.java
2
请完成以下Java代码
public List<SignaturePropertyType> getSignatureProperty() { if (signatureProperty == null) { signatureProperty = new ArrayList<SignaturePropertyType>(); } return this.signatureProperty; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id;
} /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\SignaturePropertiesType.java
1
请完成以下Java代码
public final class KeyNamePairList { @JsonCreator public static final KeyNamePairList of(@JsonProperty("l") final Collection<KeyNamePair> values) { if (values == null || values.isEmpty()) { return EMPTY; } return new KeyNamePairList(values); } public static final KeyNamePairList of(final KeyNamePair[] arr) { if (arr == null || arr.length == 0) { return EMPTY; } return new KeyNamePairList(ImmutableList.copyOf(arr)); }
public static final KeyNamePairList of() { return EMPTY; } public static final KeyNamePairList EMPTY = new KeyNamePairList(ImmutableList.<KeyNamePair> of()); @JsonProperty("l") private final List<KeyNamePair> values; private KeyNamePairList(final Collection<KeyNamePair> values) { super(); this.values = ImmutableList.copyOf(values); } public List<KeyNamePair> getValues() { return values; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\KeyNamePairList.java
1
请完成以下Java代码
private AdMessageKey getNotificationAD_Message(final I_M_InOut inout) {return inout.isSOTrx() ? MSG_Event_RETURN_FROM_CUSTOMER_Generated : MSG_Event_RETURN_TO_VENDOR_Generated;} private UserId getNotificationRecipientUserId(final I_M_InOut inout) { // // In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofCode(inout.getDocStatus()); if (docStatus.isReversedOrVoided()) { final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user if (currentUserId > 0) { return UserId.ofRepoId(currentUserId); }
return UserId.ofRepoId(inout.getUpdatedBy()); // last updated } // // Fallback: notify only the creator else { return UserId.ofRepoId(inout.getCreatedBy()); } } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\ReturnInOutUserNotificationsProducer.java
1
请完成以下Spring Boot application配置
spring.application.name=spring-ai-groq-demo spring.ai.openai.base-url=https://api.groq.com/openai spring.ai.openai.api-key=gsk_XXXX spring.ai.openai.chat.base-url=https://api.groq.com/openai spring.ai.openai.chat.api-key=gsk_XXXX spri
ng.ai.openai.chat.options.temperature=0.7 spring.ai.openai.chat.options.model=llama-3.3-70b-versatile
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-groq.properties
2
请完成以下Java代码
public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities.java
1
请完成以下Java代码
private boolean checkLimits(TenantId tenantId) { if (debugModeRateLimitsConfig.isCalculatedFieldDebugPerTenantLimitsEnabled() && !rateLimitService.checkRateLimit(LimitedApi.CALCULATED_FIELD_DEBUG_EVENTS, (Object) tenantId, debugModeRateLimitsConfig.getCalculatedFieldDebugPerTenantLimitsConfiguration())) { log.trace("[{}] Calculated field debug event limits exceeded!", tenantId); return false; } return true; } public static Exception toException(Throwable error) { return Exception.class.isInstance(error) ? (Exception) error : new Exception(error); } public void tell(TbActorMsg tbActorMsg) { appActor.tell(tbActorMsg); } public void tellWithHighPriority(TbActorMsg tbActorMsg) { appActor.tellWithHighPriority(tbActorMsg); }
public ScheduledFuture<?> schedulePeriodicMsgWithDelay(TbActorRef ctx, TbActorMsg msg, long delayInMs, long periodInMs) { log.debug("Scheduling periodic msg {} every {} ms with delay {} ms", msg, periodInMs, delayInMs); return getScheduler().scheduleWithFixedDelay(() -> ctx.tell(msg), delayInMs, periodInMs, TimeUnit.MILLISECONDS); } public ScheduledFuture<?> scheduleMsgWithDelay(TbActorRef ctx, TbActorMsg msg, long delayInMs) { log.debug("Scheduling msg {} with delay {} ms", msg, delayInMs); if (delayInMs > 0) { return getScheduler().schedule(() -> ctx.tell(msg), delayInMs, TimeUnit.MILLISECONDS); } else { ctx.tell(msg); return null; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ActorSystemContext.java
1
请在Spring Boot框架中完成以下Java代码
public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } @Override public ByteArrayRef getByteArrayRef() { return byteArrayRef; } // common methods ////////////////////////////////////////////////////////// protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id);
sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
2
请完成以下Java代码
public DocumentId getId() { return rowId; } @Override public boolean isProcessed() { return false; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames();
} @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override @NonNull public List<ProductionSimulationRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRow.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_U_Web_Properties[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Key. @param U_Key Key */ public void setU_Key (String U_Key) { set_Value (COLUMNNAME_U_Key, U_Key); } /** Get Key. @return Key */ public String getU_Key () { return (String)get_Value(COLUMNNAME_U_Key); } /** Set Value. @param U_Value Value */ public void setU_Value (String U_Value) { set_Value (COLUMNNAME_U_Value, U_Value); } /** Get Value. @return Value */
public String getU_Value () { return (String)get_Value(COLUMNNAME_U_Value); } /** Set Web Properties. @param U_Web_Properties_ID Web Properties */ public void setU_Web_Properties_ID (int U_Web_Properties_ID) { if (U_Web_Properties_ID < 1) set_ValueNoCheck (COLUMNNAME_U_Web_Properties_ID, null); else set_ValueNoCheck (COLUMNNAME_U_Web_Properties_ID, Integer.valueOf(U_Web_Properties_ID)); } /** Get Web Properties. @return Web Properties */ public int getU_Web_Properties_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_Web_Properties_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_Web_Properties.java
1
请完成以下Java代码
private Order emitUpdate(Order order) { emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId() .equals(q.getOrderId()), order); return order; } private Order updateOrder(Order order, Consumer<Order> updateFunction) { updateFunction.accept(order); return order; } private UpdateResult persistUpdate(Order order) { return orders.replaceOne(eq(ORDER_ID_PROPERTY_NAME, order.getOrderId()), orderToDocument(order)); } private void update(String orderId, Consumer<Order> updateFunction) { UpdateResult result = getOrder(orderId).map(o -> updateOrder(o, updateFunction)) .map(this::emitUpdate) .map(this::persistUpdate) .orElse(null); logger.info("Result of updating order with orderId '{}': {}", orderId, result); } private Document orderToDocument(Order order) { return new Document(ORDER_ID_PROPERTY_NAME, order.getOrderId()).append(PRODUCTS_PROPERTY_NAME, order.getProducts()) .append(ORDER_STATUS_PROPERTY_NAME, order.getOrderStatus()
.toString()); } private Order documentToOrder(@NonNull Document document) { Order order = new Order(document.getString(ORDER_ID_PROPERTY_NAME)); Document products = document.get(PRODUCTS_PROPERTY_NAME, Document.class); products.forEach((k, v) -> order.getProducts() .put(k, (Integer) v)); String status = document.getString(ORDER_STATUS_PROPERTY_NAME); if (OrderStatus.CONFIRMED.toString() .equals(status)) { order.setOrderConfirmed(); } else if (OrderStatus.SHIPPED.toString() .equals(status)) { order.setOrderShipped(); } return order; } private Bson shippedProductFilter(String productId) { return and(eq(ORDER_STATUS_PROPERTY_NAME, OrderStatus.SHIPPED.toString()), exists(String.format(PRODUCTS_PROPERTY_NAME + ".%s", productId))); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\MongoOrdersEventHandler.java
1
请完成以下Java代码
public MReportLine[] getLiness() { return m_lines; } // getLines /** * List Info */ public void list() { System.out.println(toString()); if (m_lines == null) return; for (int i = 0; i < m_lines.length; i++) m_lines[i].list();
} // list /** * String representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MReportLineSet[") .append(get_ID()).append(" - ").append(getName()) .append ("]"); return sb.toString (); } } // MReportLineSet
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportLineSet.java
1
请完成以下Java代码
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws Exception { Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list); if (workbook != null); downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception { OutputStream outputStream=null; try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); outputStream = response.getOutputStream(); workbook.write(outputStream); } catch (IOException e) { throw new Exception(e.getMessage()); }finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception { if (StringUtils.isBlank(filePath)){
return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ throw new Exception("template not null"); } catch (Exception e) { e.printStackTrace(); throw new Exception(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception { if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ throw new Exception("excel file not null"); } catch (Exception e) { throw new Exception(e.getMessage()); } return list; } }
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\Util\FileUtil.java
1
请在Spring Boot框架中完成以下Java代码
public String getBaseUnit() { return baseUnit; } /** * Sets the value of the baseUnit property. * * @param value * allowed object is * {@link String } * */ public void setBaseUnit(String value) { this.baseUnit = value; } /** * Gets the value of the purchaseUnit property. * * @return * possible object is * {@link String } * */ public String getPurchaseUnit() { return purchaseUnit; } /** * Sets the value of the purchaseUnit property. * * @param value * allowed object is * {@link String } * */ public void setPurchaseUnit(String value) { this.purchaseUnit = value; } /** * Gets the value of the salesUnit property. * * @return * possible object is * {@link String }
* */ public String getSalesUnit() { return salesUnit; } /** * Sets the value of the salesUnit property. * * @param value * allowed object is * {@link String } * */ public void setSalesUnit(String value) { this.salesUnit = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PRICATListLineItemExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
public class WebServicesConfiguration extends WsConfigurerAdapter { @Value("${ws.api.path:/ws/api/v1/*}") private String webserviceApiPath; @Value("${ws.port.type.name:UsersPort}") private String webservicePortTypeName; @Value("${ws.target.namespace:http://www.baeldung.com/springbootsoap/feignclient}") private String webserviceTargetNamespace; @Value("${ws.location.uri:http://localhost:18080/ws/api/v1/}") private String locationUri; @Bean public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); servlet.setTransformWsdlLocations(true); return new ServletRegistrationBean<>(servlet, webserviceApiPath); }
@Bean(name = "users") public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema usersSchema) { DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); wsdl11Definition.setPortTypeName(webservicePortTypeName); wsdl11Definition.setTargetNamespace(webserviceTargetNamespace); wsdl11Definition.setLocationUri(locationUri); wsdl11Definition.setSchema(usersSchema); return wsdl11Definition; } @Bean public XsdSchema userSchema() { return new SimpleXsdSchema(new ClassPathResource("users.xsd")); } }
repos\tutorials-master\feign\src\main\java\com\baeldung\feign\soap\WebServicesConfiguration.java
2
请完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Date getHiredDate() { return hiredDate; } public void setHiredDate(Date hiredDate) { this.hiredDate = hiredDate; }
public List<Email> getEmails() { return emails; } public void setEmails(List<Email> emails) { this.emails = emails; } @Override public String toString() { return "Employee{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", salary=" + salary + ", hiredDate=" + hiredDate + '}'; } }
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\dbutils\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/") .setViewName("index"); } @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize(DataSize.ofBytes(10000000L)); factory.setMaxRequestSize(DataSize.ofBytes(10000000L)); return factory.createMultipartConfig(); } @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } /** Static resource locations including themes*/ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/", "/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } /** BEGIN theme configuration */ @Bean public ResourceBundleThemeSource themeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setDefaultEncoding("UTF-8"); themeSource.setBasenamePrefix("themes."); return themeSource; } @Bean public CookieThemeResolver themeResolver() { CookieThemeResolver resolver = new CookieThemeResolver(); resolver.setDefaultThemeName("default"); resolver.setCookieName("example-theme-cookie");
return resolver; } @Bean public ThemeChangeInterceptor themeChangeInterceptor() { ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor(); interceptor.setParamName("theme"); return interceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(themeChangeInterceptor()); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return factory -> factory.setRegisterDefaultServlet(true); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
public void setM_Shipment_Declaration_ID (int M_Shipment_Declaration_ID) { if (M_Shipment_Declaration_ID < 1) set_Value (COLUMNNAME_M_Shipment_Declaration_ID, null); else set_Value (COLUMNNAME_M_Shipment_Declaration_ID, Integer.valueOf(M_Shipment_Declaration_ID)); } /** Get Abgabemeldung. @return Abgabemeldung */ @Override public int getM_Shipment_Declaration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_Shipment_Declaration_Line. @param M_Shipment_Declaration_Line_ID M_Shipment_Declaration_Line */ @Override public void setM_Shipment_Declaration_Line_ID (int M_Shipment_Declaration_Line_ID) { if (M_Shipment_Declaration_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Line_ID, Integer.valueOf(M_Shipment_Declaration_Line_ID)); } /** Get M_Shipment_Declaration_Line. @return M_Shipment_Declaration_Line */ @Override public int getM_Shipment_Declaration_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Pck. Gr.. @param PackageSize Pck. Gr. */ @Override public void setPackageSize (java.lang.String PackageSize) { set_Value (COLUMNNAME_PackageSize, PackageSize);
} /** Get Pck. Gr.. @return Pck. Gr. */ @Override public java.lang.String getPackageSize () { return (java.lang.String)get_Value(COLUMNNAME_PackageSize); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Line.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ErrorEventDefinition.class, BPMN_ELEMENT_ERROR_EVENT_DEFINITION) .namespaceUri(BPMN20_NS) .extendsType(EventDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<ErrorEventDefinition>() { public ErrorEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new ErrorEventDefinitionImpl(instanceContext); } }); errorRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ERROR_REF) .qNameAttributeReference(Error.class) .build(); camundaErrorCodeVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ERROR_CODE_VARIABLE) .namespace(CAMUNDA_NS) .build(); camundaErrorMessageVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ERROR_MESSAGE_VARIABLE) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public ErrorEventDefinitionImpl(ModelTypeInstanceContext context) { super(context); }
public Error getError() { return errorRefAttribute.getReferenceTargetElement(this); } public void setError(Error error) { errorRefAttribute.setReferenceTargetElement(this, error); } @Override public void setCamundaErrorCodeVariable(String camundaErrorCodeVariable) { camundaErrorCodeVariableAttribute.setValue(this, camundaErrorCodeVariable); } @Override public String getCamundaErrorCodeVariable() { return camundaErrorCodeVariableAttribute.getValue(this); } @Override public void setCamundaErrorMessageVariable(String camundaErrorMessageVariable) { camundaErrorMessageVariableAttribute.setValue(this, camundaErrorMessageVariable); } @Override public String getCamundaErrorMessageVariable() { return camundaErrorMessageVariableAttribute.getValue(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ErrorEventDefinitionImpl.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public int getSold() { return sold; } public void setSold(int sold) { this.sold = sold; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", title=" + title + ", sold=" + sold + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTopNRowsPerGroup\src\main\java\com\bookstore\entity\Author.java
1