instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ShoppingCartService { private final ShoppingCartRepository shoppingCartRepository; public ShoppingCartService(ShoppingCartRepository shoppingCartRepository) { this.shoppingCartRepository = shoppingCartRepository; } @Transactional public void addToTheBeginning() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().add(0, "Modern history"); } @Transactional public void addToTheEnd() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().add("The last day"); } @Transactional public void addInTheMiddle() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().add(cart.getBooks().size() / 2, "Middle man"); } @Transactional public void removeFirst() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().remove(0); }
@Transactional public void removeLast() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().remove(cart.getBooks().size() - 1); } @Transactional public void removeMiddle() { ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno"); cart.getBooks().remove(cart.getBooks().size() / 2); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootElementCollectionNoOrderColumn\src\main\java\com\bookstore\service\ShoppingCartService.java
2
请完成以下Java代码
public int getQtyStockEstimateSeqNo_AtDate() { return get_ValueAsInt(COLUMNNAME_QtyStockEstimateSeqNo_AtDate); } @Override public void setQtyStockEstimateTime_AtDate (final @Nullable java.sql.Timestamp QtyStockEstimateTime_AtDate) { set_Value (COLUMNNAME_QtyStockEstimateTime_AtDate, QtyStockEstimateTime_AtDate); } @Override public java.sql.Timestamp getQtyStockEstimateTime_AtDate() { return get_ValueAsTimestamp(COLUMNNAME_QtyStockEstimateTime_AtDate); } @Override public void setQtySupply_DD_Order_AtDate (final @Nullable BigDecimal QtySupply_DD_Order_AtDate) { set_Value (COLUMNNAME_QtySupply_DD_Order_AtDate, QtySupply_DD_Order_AtDate); } @Override public BigDecimal getQtySupply_DD_Order_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_DD_Order_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupply_PP_Order_AtDate (final @Nullable BigDecimal QtySupply_PP_Order_AtDate) { set_Value (COLUMNNAME_QtySupply_PP_Order_AtDate, QtySupply_PP_Order_AtDate); } @Override public BigDecimal getQtySupply_PP_Order_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PP_Order_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupply_PurchaseOrder_AtDate (final @Nullable BigDecimal QtySupply_PurchaseOrder_AtDate) { set_Value (COLUMNNAME_QtySupply_PurchaseOrder_AtDate, QtySupply_PurchaseOrder_AtDate); } @Override public BigDecimal getQtySupply_PurchaseOrder_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PurchaseOrder_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyRequired_AtDate (final @Nullable BigDecimal QtySupplyRequired_AtDate) { set_Value (COLUMNNAME_QtySupplyRequired_AtDate, QtySupplyRequired_AtDate); } @Override
public BigDecimal getQtySupplyRequired_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyRequired_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplySum_AtDate (final @Nullable BigDecimal QtySupplySum_AtDate) { set_Value (COLUMNNAME_QtySupplySum_AtDate, QtySupplySum_AtDate); } @Override public BigDecimal getQtySupplySum_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplySum_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyToSchedule_AtDate (final @Nullable BigDecimal QtySupplyToSchedule_AtDate) { set_Value (COLUMNNAME_QtySupplyToSchedule_AtDate, QtySupplyToSchedule_AtDate); } @Override public BigDecimal getQtySupplyToSchedule_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyToSchedule_AtDate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit.java
1
请完成以下Java代码
public class EmployeeBean implements Serializable { /** * */ private static final long serialVersionUID = -3760445487636086034L; private String firstName; private String lastName; private LocalDate startDate; public EmployeeBean() { } public EmployeeBean(String firstName, String lastName, LocalDate startDate) { this.firstName = firstName; this.lastName = lastName; this.startDate = startDate; } 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 LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } }
repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\pojo\EmployeeBean.java
1
请完成以下Java代码
class ConnectionInputStream extends FilterInputStream { private volatile boolean closing; ConnectionInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { if (this.closing) { return; } this.closing = true; try {
super.close(); } finally { try { NestedUrlConnection.this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnection.java
1
请完成以下Java代码
public class TriggerExecutionOperation extends AbstractOperation { public TriggerExecutionOperation(CommandContext commandContext, ExecutionEntity execution) { super(commandContext, execution); } @Override public void run() { FlowElement currentFlowElement = getCurrentFlowElement(execution); if (currentFlowElement instanceof FlowNode) { ActivityBehavior activityBehavior = (ActivityBehavior) ((FlowNode) currentFlowElement).getBehavior(); if (activityBehavior instanceof TriggerableActivityBehavior) { if (currentFlowElement instanceof BoundaryEvent) { commandContext.getHistoryManager().recordActivityStart(execution); } ((TriggerableActivityBehavior) activityBehavior).trigger(execution, null, null); if (currentFlowElement instanceof BoundaryEvent) { commandContext.getHistoryManager().recordActivityEnd(execution, null); } } else { throw new ActivitiException(
"Invalid behavior: " + activityBehavior + " should implement " + TriggerableActivityBehavior.class.getName() ); } } else { throw new ActivitiException( "Programmatic error: no current flow element found or invalid type: " + currentFlowElement + ". Halting." ); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\TriggerExecutionOperation.java
1
请完成以下Java代码
public void setBezugsrefernznr(String bezugsrefernznr) { this.bezugsrefernznr = bezugsrefernznr; } public BigInteger getAuszugsNr() { return auszugsNr; } public void setAuszugsNr(BigInteger auszugsNr) { this.auszugsNr = auszugsNr; } public Saldo getAnfangsSaldo() { return anfangsSaldo; } public void setAnfangsSaldo(Saldo anfangsSaldo) { this.anfangsSaldo = anfangsSaldo; } public Saldo getSchlussSaldo() { return schlussSaldo; } public void setSchlussSaldo(Saldo schlussSaldo) { this.schlussSaldo = schlussSaldo; }
public Saldo getAktuellValutenSaldo() { return aktuellValutenSaldo; } public void setAktuellValutenSaldo(Saldo aktuellValutenSaldo) { this.aktuellValutenSaldo = aktuellValutenSaldo; } public Saldo getZukunftValutenSaldo() { return zukunftValutenSaldo; } public void setZukunftValutenSaldo(Saldo zukunftValutenSaldo) { this.zukunftValutenSaldo = zukunftValutenSaldo; } public List<BankstatementLine> getLines() { return lines; } public void setLines(List<BankstatementLine> lines) { this.lines = lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Bankstatement.java
1
请完成以下Java代码
private boolean decodeAndCheckMatches(CharSequence rawPassword, String encodedPassword) { String[] parts = encodedPassword.split("\\$"); if (parts.length != 4) { return false; } long params = Long.parseLong(parts[1], 16); byte[] salt = decodePart(parts[2]); byte[] derived = decodePart(parts[3]); int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff); int memoryCost = (int) params >> 8 & 0xff; int parallelization = (int) params & 0xff; byte[] generated = SCrypt.generate(Utf8.encode(rawPassword), salt, cpuCost, memoryCost, parallelization, this.keyLength); return MessageDigest.isEqual(derived, generated); } private String digest(CharSequence rawPassword, byte[] salt) { byte[] derived = SCrypt.generate(Utf8.encode(rawPassword), salt, this.cpuCost, this.memoryCost, this.parallelization, this.keyLength); String params = Long.toString( ((int) (Math.log(this.cpuCost) / Math.log(2)) << 16L) | this.memoryCost << 8 | this.parallelization, 16);
StringBuilder sb = new StringBuilder((salt.length + derived.length) * 2); sb.append("$").append(params).append('$'); sb.append(encodePart(salt)).append('$'); sb.append(encodePart(derived)); return sb.toString(); } private byte[] decodePart(String part) { return Base64.getDecoder().decode(Utf8.encode(part)); } private String encodePart(byte[] part) { return Utf8.decode(Base64.getEncoder().encode(part)); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\scrypt\SCryptPasswordEncoder.java
1
请完成以下Java代码
public static JsonOLCandCreateBulkRequest loadJsonOLCandCreateBulkRequest(@NonNull final String resourceName) { return fromRessource(resourceName, JsonOLCandCreateBulkRequest.class); } public static JsonOLCandCreateRequest loadJsonOLCandCreateRequest(@NonNull final String resourceName) { return fromRessource(resourceName, JsonOLCandCreateRequest.class); } private static <T> T fromRessource(@NonNull final String resourceName, @NonNull final Class<T> clazz) { final InputStream inputStream = Check.assumeNotNull( JsonOLCandUtil.class.getResourceAsStream(resourceName), "There needs to be a loadable resource with name={}", resourceName); final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try { return jsonObjectMapper.readValue(inputStream, clazz); } catch (final JsonParseException e) { throw new JsonOLCandUtilException("JsonParseException", e); } catch (final JsonMappingException e) { throw new JsonOLCandUtilException("JsonMappingException", e); } catch (final IOException e) { throw new JsonOLCandUtilException("IOException", e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonOLCandUtil.java
1
请完成以下Java代码
protected TimerDeclarationImpl findTimerDeclarationForActivity(CommandContext commandContext, JobEntity job) { ExecutionEntity execution = commandContext.getExecutionManager().findExecutionById(job.getExecutionId()); if (execution == null) { throw new ProcessEngineException("No execution found with id '" + job.getExecutionId() + "' for job id '" + jobId + "'."); } ActivityImpl activity = execution.getProcessDefinition().findActivity(job.getActivityId()); if (activity != null) { if (TimerTaskListenerJobHandler.TYPE.equals(job.getJobHandlerType())) { return findTimeoutListenerDeclaration(job, activity); } Map<String, TimerDeclarationImpl> timerDeclarations = TimerDeclarationImpl.getDeclarationsForScope(activity.getEventScope()); if (!timerDeclarations.isEmpty() && timerDeclarations.containsKey(job.getActivityId())) { return timerDeclarations.get(job.getActivityId()); } } return null; } protected TimerDeclarationImpl findTimeoutListenerDeclaration(JobEntity job, ActivityImpl activity) { Map<String, Map<String, TimerDeclarationImpl>> timeoutDeclarations = TimerDeclarationImpl.getTimeoutListenerDeclarationsForScope(activity.getEventScope()); if (!timeoutDeclarations.isEmpty()) { Map<String, TimerDeclarationImpl> activityTimeouts = timeoutDeclarations.get(job.getActivityId()); if (activityTimeouts != null && !activityTimeouts.isEmpty()) { JobHandlerConfiguration jobHandlerConfiguration = job.getJobHandlerConfiguration();
if (jobHandlerConfiguration instanceof TimerJobConfiguration) { return activityTimeouts.get(((TimerJobConfiguration) jobHandlerConfiguration).getTimerElementSecondaryKey()); } } } return null; } protected TimerDeclarationImpl findTimerDeclarationForProcessStartEvent(CommandContext commandContext, JobEntity job) { ProcessDefinitionEntity processDefinition = commandContext.getProcessEngineConfiguration().getDeploymentCache().findDeployedProcessDefinitionById(job.getProcessDefinitionId()); @SuppressWarnings("unchecked") List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER); for (TimerDeclarationImpl timerDeclarationCandidate : timerDeclarations) { if (timerDeclarationCandidate.getJobDefinitionId().equals(job.getJobDefinitionId())) { return timerDeclarationCandidate; } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\RecalculateJobDuedateCmd.java
1
请在Spring Boot框架中完成以下Java代码
class MailSenderJndiConfiguration { private final MailProperties properties; MailSenderJndiConfiguration(MailProperties properties) { this.properties = properties; } @Bean JavaMailSenderImpl mailSender(Session session) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setDefaultEncoding(this.properties.getDefaultEncoding().name()); sender.setSession(session); return sender; }
@Bean @ConditionalOnMissingBean Session session() { String jndiName = this.properties.getJndiName(); Assert.state(jndiName != null, "'jndiName' must not be null"); try { return JndiLocatorDelegate.createDefaultResourceRefLocator().lookup(jndiName, Session.class); } catch (NamingException ex) { throw new IllegalStateException(String.format("Unable to find Session in JNDI location %s", jndiName), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailSenderJndiConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DemoApplication { private static final Logger log = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public CommandLineRunner loadData(CustomerRepository repository) { return (args) -> { // save a couple of customers repository.save(new Customer("Jack", "Bauer")); repository.save(new Customer("Chloe", "O'Brian")); repository.save(new Customer("Kim", "Bauer")); repository.save(new Customer("David", "Palmer")); repository.save(new Customer("Michelle", "Dessler")); // fetch all customers log.info("Customers found with findAll():"); log.info("-------------------------------"); for (Customer customer : repository.findAll()) { log.info(customer.toString()); } log.info(""); // fetch an individual customer by ID Customer customer = repository.findById(1L).get(); log.info("Customer found with findOne(1L):");
log.info("--------------------------------"); log.info(customer.toString()); log.info(""); // fetch customers by last name log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):"); log.info("--------------------------------------------"); for (Customer bauer : repository .findByLastNameStartsWithIgnoreCase("Bauer")) { log.info(bauer.toString()); } log.info(""); }; } }
repos\springboot-demo-master\vaadin\src\main\java\com\et\vaadin\DemoApplication.java
2
请完成以下Java代码
public void setQualityRating (int QualityRating) { set_Value (COLUMNNAME_QualityRating, Integer.valueOf(QualityRating)); } /** Get Quality Rating. @return Method for rating vendors */ public int getQualityRating () { Integer ii = (Integer)get_Value(COLUMNNAME_QualityRating); if (ii == null) return 0; return ii.intValue(); } /** Set Royalty Amount. @param RoyaltyAmt (Included) Amount for copyright, etc. */ public void setRoyaltyAmt (BigDecimal RoyaltyAmt) { set_Value (COLUMNNAME_RoyaltyAmt, RoyaltyAmt); } /** Get Royalty Amount. @return (Included) Amount for copyright, etc. */ public BigDecimal getRoyaltyAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoyaltyAmt); if (bd == null) return Env.ZERO; return bd; } /** Set UPC/EAN. @param UPC Bar Code (Universal Product Code or its superset European Article Number) */ public void setUPC (String UPC) { set_Value (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number) */ public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } /** Set Partner Category. @param VendorCategory Product Category of the Business Partner */ public void setVendorCategory (String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } /** Get Partner Category. @return Product Category of the Business Partner */ public String getVendorCategory () { return (String)get_Value(COLUMNNAME_VendorCategory); } /** Set Partner Product Key. @param VendorProductNo Product Key of the Business Partner */ public void setVendorProductNo (String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } /** Get Partner Product Key. @return Product Key of the Business Partner */ public String getVendorProductNo () { return (String)get_Value(COLUMNNAME_VendorProductNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java
1
请完成以下Spring Boot application配置
logging.level.org.springframework.mail=DEBUG spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=username spring.mail.password=password # Other properties spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=5000 spring.mail.properties.mail.smtp.writetimeout=5000 # TLS , port 587 spring.mail.properties.mail.smtp.starttls.enable=true # SSL, post 465 #spring.mail.properties.mail
.smtp.socketFactory.port = 465 #spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory # References # https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
repos\spring-boot-master\email\src\main\resources\application.properties
2
请完成以下Java代码
public String toString() { if (valueExpression != null) { return valueExpression.getExpressionString(); } return super.toString(); } @Override public String getExpressionText() { return expressionText; } @Override public Object getValue( ExpressionManager expressionManager, DelegateInterceptor delegateInterceptor, Map<String, Object> availableVariables ) { ELContext elContext = expressionManager.getElContext(availableVariables); return getValueFromContext(elContext, delegateInterceptor); }
private Object getValueFromContext(ELContext elContext, DelegateInterceptor delegateInterceptor) { try { ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext); delegateInterceptor.handleInvocation(invocation); return invocation.getInvocationResult(); } catch (PropertyNotFoundException pnfe) { throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe); } catch (MethodNotFoundException mnfe) { throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe); } catch (Exception ele) { throw new ActivitiException("Error while evaluating expression: " + expressionText, ele); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java
1
请完成以下Java代码
public Collection<Class<? extends AbstractTransactionEvent>> getHandledEventType() { return ImmutableList.of( TransactionCreatedEvent.class, TransactionDeletedEvent.class); } @Override public void handleEvent(@NonNull final AbstractTransactionEvent event) { final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } private UpdateMainDataRequest createDataUpdateRequestForEvent(@NonNull final AbstractTransactionEvent event) { final OrgId orgId = event.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); final MainDataRecordIdentifier identifier = MainDataRecordIdentifier .createForMaterial(event.getMaterialDescriptor(), timeZone); final BigDecimal eventQuantity = event.getQuantityDelta(); final UpdateMainDataRequestBuilder dataRequestBuilder = UpdateMainDataRequest.builder() .identifier(identifier) .onHandQtyChange(eventQuantity);
if (event.isDirectMovementWarehouse()) { dataRequestBuilder.directMovementQty(eventQuantity); } if (event.getInventoryLineId() > 0) { dataRequestBuilder.qtyInventoryCount(eventQuantity); dataRequestBuilder.qtyInventoryTime(event.getMaterialDescriptor().getDate()); } return dataRequestBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\TransactionEventHandlerForCockpitRecords.java
1
请完成以下Java代码
public Permission mergeWith(final Permission permissionFrom) { final TableColumnPermission columnPermissionFrom = checkCompatibleAndCast(permissionFrom); return asNewBuilder() .addAccesses(columnPermissionFrom.accesses) .build(); } public int getAD_Table_ID() { return resource.getAD_Table_ID(); } public int getAD_Column_ID() { return resource.getAD_Column_ID(); } public static class Builder { private TableColumnResource resource; private final Set<Access> accesses = new LinkedHashSet<>(); public TableColumnPermission build() { return new TableColumnPermission(this); } public Builder setFrom(final TableColumnPermission columnPermission) { setResource(columnPermission.getResource()); setAccesses(columnPermission.accesses); return this; } public Builder setResource(final TableColumnResource resource) {
this.resource = resource; return this; } public final Builder addAccess(final Access access) { accesses.add(access); return this; } public final Builder removeAccess(final Access access) { accesses.remove(access); return this; } public final Builder setAccesses(final Set<Access> acceses) { accesses.clear(); accesses.addAll(acceses); return this; } public final Builder addAccesses(final Set<Access> acceses) { accesses.addAll(acceses); return this; } public final Builder removeAllAccesses() { accesses.clear(); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java
1
请完成以下Java代码
public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); }
@Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请完成以下Java代码
protected void updateAndValidateImportRecordsImpl() { final ImportRecordsSelection selection = getImportRecordsSelection(); BPartnerGlobalIDImportTableSqlUpdater.updateBPartnerGlobalIDImortTable(selection); } @Override protected String getImportOrderBySql() { return I_I_BPartner_GlobalID.COLUMNNAME_GlobalId; } @Override public I_I_BPartner_GlobalID retrieveImportRecord(Properties ctx, ResultSet rs) throws SQLException { return new X_I_BPartner_GlobalID(ctx, rs, ITrx.TRXNAME_ThreadInherited); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override
protected ImportRecordResult importRecord(@NonNull IMutable<Object> state, @NonNull I_I_BPartner_GlobalID importRecord, final boolean isInsertOnly) { final IBPartnerDAO partnerDAO = Services.get(IBPartnerDAO.class); if (importRecord.getC_BPartner_ID() > 0 && !Check.isEmpty(importRecord.getURL3(), true)) { final I_C_BPartner bpartner = partnerDAO.getById(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID())); bpartner.setURL3(importRecord.getURL3()); InterfaceWrapperHelper.save(bpartner); return ImportRecordResult.Updated; } return ImportRecordResult.Nothing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportProcess.java
1
请完成以下Java代码
private void consolidateWithIdentifier(@NonNull final JsonRequestLocationUpsertItem requestItem) { final ExternalIdentifier externalIdentifier = ExternalIdentifier.of(requestItem.getLocationIdentifier()); final JsonRequestLocation jsonLocation = requestItem.getLocation(); switch (externalIdentifier.getType()) { case METASFRESH_ID: // nothing to do; the JsonRequestLocationUpsertItem has no metasfresh-ID to consolidate with break; case EXTERNAL_REFERENCE: // nothing to do break; case GLN: if (!jsonLocation.isGlnSet()) { jsonLocation.setGln(externalIdentifier.asGLN().getCode()); } break; default: throw new AdempiereException("Unexpected IdentifierString.Type=" + externalIdentifier.getType()) .appendParametersToMessage() .setParameter("externalIdentifier", externalIdentifier) .setParameter("jsonRequestLocationUpsertItem", requestItem); }
} private void consolidateWithIdentifier(@NonNull final JsonRequestContactUpsertItem requestItem) { final ExternalIdentifier externalIdentifier = ExternalIdentifier.of(requestItem.getContactIdentifier()); switch (externalIdentifier.getType()) { case METASFRESH_ID: // nothing to do; the JsonRequestContactUpsertItem has no metasfresh-ID to consolidate with break; case EXTERNAL_REFERENCE: // nothing to do break; default: throw new AdempiereException("Unexpected IdentifierString.Type=" + externalIdentifier.getType()) .appendParametersToMessage() .setParameter("externalIdentifier", externalIdentifier) .setParameter("jsonRequestContactUpsertItem", requestItem); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\JsonRequestConsolidateService.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { return checkBankStatementIsDraftOrInProcessOrCompleted(context) .and(() -> checkSingleLineSelectedWhichIsForeignCurrency(context)); } private ProcessPreconditionsResolution checkSingleLineSelectedWhichIsForeignCurrency(@NonNull final IProcessPreconditionsContext context) { final Set<TableRecordReference> bankStatemementLineRefs = context.getSelectedIncludedRecords(); if (bankStatemementLineRefs.size() != 1) { return ProcessPreconditionsResolution.rejectWithInternalReason("a single line shall be selected"); } final TableRecordReference bankStatemementLineRef = bankStatemementLineRefs.iterator().next(); final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(bankStatemementLineRef.getRecord_ID()); final I_C_BankStatementLine line = bankStatementBL.getLineById(bankStatementLineId); final CurrencyId currencyId = CurrencyId.ofRepoId(line.getC_Currency_ID()); final CurrencyId baseCurrencyId = bankStatementBL.getBaseCurrencyId(line); if (CurrencyId.equals(currencyId, baseCurrencyId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("line is not in foreign currency"); } return ProcessPreconditionsResolution.accept(); } @Nullable @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_CurrencyRate.equals(parameter.getColumnName()))
{ return getSingleSelectedBankStatementLine().getCurrencyRate(); } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected String doIt() { if (currencyRate == null || currencyRate.signum() == 0) { throw new FillMandatoryException("CurrencyRate"); } bankStatementBL.changeCurrencyRate(getSingleSelectedBankStatementLineId(), currencyRate); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_ChangeCurrencyRate.java
1
请完成以下Java代码
public boolean processLockedWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage) { boolean success = false; try { //dev-note: we acquire a lock to make sure the `isAvailableToWork` check is accurate mainLock.lock(); if (!isAvailableToWork()) { return false; } success = processWorkPackage(workPackage); return success; } catch (final Throwable t) { logger.error("*** processLockedWorkPackage failed! Moving forward...", t); return false; } finally { if (!success) { WorkPackageLockHelper.unlockNoFail(workPackage); } mainLock.unlock(); } } @NonNull public Set<QueuePackageProcessorId> getAssignedPackageProcessorIds() { return getQueue().getQueuePackageProcessorIds(); } @Override public QueueProcessorId getQueueProcessorId() { return getQueue().getQueueProcessorId(); } private boolean processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage) { boolean success = false; try { final IWorkpackageProcessor workPackageProcessor = getWorkpackageProcessor(workPackage); final PerformanceMonitoringService perfMonService = getPerfMonService(); final WorkpackageProcessorTask task = new WorkpackageProcessorTask(this, workPackageProcessor, workPackage, logsRepository, perfMonService); executeTask(task); success = true; return true; } finally { if (!success) { logger.info("Submitting for processing next workPackage failed. workPackage={}.", workPackage); getEventDispatcher().unregisterListeners(workPackage.getC_Queue_WorkPackage_ID()); }
} } private IWorkpackageProcessor getWorkpackageProcessor(final I_C_Queue_WorkPackage workPackage) { final IWorkpackageProcessorFactory factory = getActualWorkpackageProcessorFactory(); final Properties ctx = InterfaceWrapperHelper.getCtx(workPackage); final int packageProcessorId = workPackage.getC_Queue_PackageProcessor_ID(); return factory.getWorkpackageProcessor(ctx, packageProcessorId); } private PerformanceMonitoringService getPerfMonService() { PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService; if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService) { performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr( PerformanceMonitoringService.class, NoopPerformanceMonitoringService.INSTANCE); } return performanceMonitoringService; } private IQueueProcessorEventDispatcher getEventDispatcher() { return queueProcessorFactory.getQueueProcessorEventDispatcher(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\AbstractQueueProcessor.java
1
请完成以下Java代码
public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) { } public void parseRootElement(Element rootElement, List<ProcessDefinitionEntity> processDefinitions) { } public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) { } public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) { } public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) { } public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) { } public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { } public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) { } public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { } public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { } public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl nestedActivity) {
} public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) { } public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) { } public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) { } public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) { } public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) { } public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) { } @Override public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) { } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\AbstractBpmnParseListener.java
1
请在Spring Boot框架中完成以下Java代码
final List<JsonTag> computeTags(@NonNull final Attachment attachment) { final ImmutableList.Builder<JsonTag> tags = ImmutableList.builder(); final AttachmentMetadata metadata = attachment.getMetadata(); final String id = attachment.getId(); if (!EmptyUtil.isEmpty(id)) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ID, id)); } final String uploadDate = attachment.getUploadDate(); if (!EmptyUtil.isEmpty(uploadDate)) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_UPLOAD_DATE, uploadDate)); }
final BigDecimal type = metadata.getType(); if (type != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_TYPE, String.valueOf(type))); } final OffsetDateTime createdAt = metadata.getCreatedAt(); if (createdAt != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_CREATEDAT, String.valueOf(createdAt))); } tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT, GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT_VALUE)); return tags.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\processor\AttachmentProcessor.java
2
请完成以下Java代码
private @NotNull ITranslatableString extractGTIN(final @NotNull DDOrderReference ddOrderReference) { return Optional.ofNullable(ddOrderReference.getProductId()) .flatMap(productService::getGTIN) .map(GTIN::getAsString) .map(TranslatableStrings::anyLanguage) .orElse(TranslatableStrings.empty()); } @NonNull private ITranslatableString extractSourceDoc(@NonNull final DDOrderReference ddOrderReference) { ImmutablePair<ITranslatableString, String> documentTypeAndNo; if (ddOrderReference.getSalesOrderId() != null) { documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getSalesOrderId()); } else if (ddOrderReference.getPpOrderId() != null)
{ documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getPpOrderId()); } else { return TranslatableStrings.empty(); } return TranslatableStrings.builder() .append(documentTypeAndNo.getLeft()) .append(" ") .append(documentTypeAndNo.getRight()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionLauncherCaptionProvider.java
1
请完成以下Java代码
public static void touch(String path, String... args) throws IOException, ParseException { File file = new File(path); if (!file.exists()) { file.createNewFile(); if (args.length == 0) { return; } } long timeMillis = args.length < 2 ? System.currentTimeMillis() : new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(args[1]).getTime(); if (args.length > 0) { // change access time only if ("a".equals(args[0])) { FileTime accessFileTime = FileTime.fromMillis(timeMillis); Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); return; } // change modification time only if ("m".equals(args[0])) {
file.setLastModified(timeMillis); return; } } // other cases will change both FileTime accessFileTime = FileTime.fromMillis(timeMillis); Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); file.setLastModified(timeMillis); } public static void touchWithApacheCommons(String path) throws IOException { FileUtils.touch(new File(path)); } public static void main(String[] args) throws IOException, ParseException { touch("test.txt"); } }
repos\tutorials-master\core-java-modules\core-java-io-4\src\main\java\com\baeldung\simulation\touch\command\Simulator.java
1
请完成以下Java代码
public Product getProductById(final ProductId productId) { return productsCache.computeIfAbsent(productId, this::retrieveProductById); } private Product retrieveProductById(final ProductId productId) { final I_M_Product productRecord = productsRepo.getByIdInTrx(productId); return new ProductsCache.Product(productRecord); } public Product newProduct(@NonNull final I_M_Product productRecord) { return new ProductsCache.Product(productRecord); } public void clear() { productsCache.clear(); } final class Product { @Getter private final I_M_Product record; private Product(@NonNull final I_M_Product record) { this.record = record; }
public ProductId getIdOrNull() { return ProductId.ofRepoIdOrNull(record.getM_Product_ID()); } public int getOrgId() { return record.getAD_Org_ID(); } public void save() { productsRepo.save(record); productsCache.put(getIdOrNull(), this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\ProductsCache.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if(ProcessUtil.isFlatFeeContract(context)) { return ProcessPreconditionsResolution.rejectWithInternalReason("Not supported for FlatFee contracts"); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() throws Exception { final I_C_Flatrate_Term term = createTermInOwnTrx(); // TODO check out and cleanup those different methods final int adWindowId = getProcessInfo().getAD_Window_ID(); if (adWindowId > 0 && !Ini.isSwingClient()) { // this works for the webui getResult().setRecordToOpen(TableRecordReference.of(term), adWindowId, OpenTarget.SingleDocument); } else { // this is the old code that works for swing getResult().setRecordToSelectAfterExecution(TableRecordReference.of(term)); } return MSG_OK; } private I_C_Flatrate_Term createTermInOwnTrx() { final TrxCallable<I_C_Flatrate_Term> callable = () -> { final I_C_Flatrate_Term term = PMMContractBuilder.newBuilder() .setCtx(getCtx()) .setFailIfNotCreated(true)
.setComplete(true) .setC_Flatrate_Conditions(p_C_Flatrate_Conditions) .setC_BPartner(p_C_BPartner) .setStartDate(p_StartDate) .setEndDate(p_EndDate) .setPMM_Product(p_PMM_Product) .setC_UOM(p_C_UOM) .setAD_User_InCharge(p_AD_User_Incharge) .setCurrencyId(p_CurrencyId) .setComplete(p_isComplete) // complete if flag on true, do not complete otherwise .build(); return term; }; // the default config is fine for us final ITrxRunConfig config = trxManager.newTrxRunConfigBuilder().build(); return trxManager.call(ITrx.TRXNAME_None, config, callable); } /** * If the given <code>parameterName</code> is {@value #PARAM_NAME_AD_USER_IN_CHARGE_ID},<br> * then the method returns the user from {@link IPMMContractsBL#getDefaultContractUserInCharge_ID(Properties)}. */ @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final String parameterName = parameter.getColumnName(); if (!PARAM_NAME_AD_USER_IN_CHARGE_ID.equals(parameterName)) { return DEFAULT_VALUE_NOTAVAILABLE; } final int adUserInChargeId = pmmContractsBL.getDefaultContractUserInCharge_ID(getCtx()); if (adUserInChargeId < 0) { return DEFAULT_VALUE_NOTAVAILABLE; } return adUserInChargeId; // we need to return the ID, not the actual record. Otherwise then lookup logic will be confused. } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\process\C_Flatrate_Term_Create_ProcurementContract.java
1
请完成以下Java代码
public void setRefundMode (java.lang.String RefundMode) { set_Value (COLUMNNAME_RefundMode, RefundMode); } /** Get Staffel-Modus. @return Staffel-Modus */ @Override public java.lang.String getRefundMode () { return (java.lang.String)get_Value(COLUMNNAME_RefundMode); } /** Set Rückvergütung %. @param RefundPercent Rückvergütung % */ @Override
public void setRefundPercent (java.math.BigDecimal RefundPercent) { set_Value (COLUMNNAME_RefundPercent, RefundPercent); } /** Get Rückvergütung %. @return Rückvergütung % */ @Override public java.math.BigDecimal getRefundPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RefundPercent); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_RefundConfig.java
1
请在Spring Boot框架中完成以下Java代码
public Result<Long> apiDeleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } FlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Exception e) { return Result.ofFail(-1, e.getMessage()); } try {
publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()); return Result.ofSuccess(id); } catch (Throwable t) { Throwable e = t instanceof ExecutionException ? t.getCause() : t; logger.error("Error when deleting flow rules, app={}, ip={}, id={}", oldEntity.getApp(), oldEntity.getIp(), id, e); return Result.ofFail(-1, e.getMessage()); } } private void publishRules(String app, String ip, Integer port) throws Exception { List<FlowRuleEntity> rules = repository.findAllByApp(app); rulePublisher.publish(app, rules); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\FlowControllerV1.java
2
请完成以下Java代码
public String getId() { return id; } public String getKey() { return key; } public String getCategory() { return category; } public String getDescription() { return description; } public String getName() { return name; } public int getVersion() { return version; }
public String getVersionTag() { return versionTag; } public String getResource() { return resource; } public String getDeploymentId() { return deploymentId; } public String getDiagram() { return diagram; } public boolean isSuspended() { return suspended; } public String getContextPath() { return contextPath; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\processDefinition\HalProcessDefinition.java
1
请完成以下Spring Boot application配置
########################################################## ################## 所有profile共有的配置 ################# ########################################################## ################### spring配置 ################### spring: profiles: active: dev server: port: 8092 --- ##################################################################### ######################## 开发环境profile ##########################
##################################################################### spring: profiles: dev logging: level: ROOT: INFO com: xncoding: DEBUG file: D:/logs/app.log
repos\SpringBootBucket-master\springboot-websocket\src\main\resources\application.yml
2
请完成以下Java代码
private void assertPhysicalInventory() { if (!getInventoryType().isPhysical()) { throw new AdempiereException("Expected Physical Inventory: " + this); } } public String getUOMSymbol() { return getUOM().getUOMSymbol(); } public I_C_UOM getUOM() { if (inventoryType.isPhysical()) { final Quantity qtyBook = getQtyBook(); final Quantity qtyCount = getQtyCount(); Quantity.assertSameUOM(qtyBook, qtyCount); return qtyBook.getUOM(); } else if (inventoryType.isInternalUse()) { return getQtyInternalUse().getUOM(); } else { throw new AdempiereException("Unknown inventory type: " + inventoryType); } } public Quantity getQtyInternalUse() { assertInternalUseInventory(); return qtyInternalUse; } public Quantity getQtyCount() { assertPhysicalInventory(); return qtyCount; } public Quantity getQtyBook() { assertPhysicalInventory(); return qtyBook; } public Quantity getQtyCountMinusBooked() { return getQtyCount().subtract(getQtyBook()); } /** * @param qtyCountToAdd needs to have the same UOM as this instance's current qtyCount. */ public InventoryLineHU withAddingQtyCount(@NonNull final Quantity qtyCountToAdd) { return withQtyCount(getQtyCount().add(qtyCountToAdd)); } public InventoryLineHU withZeroQtyCount() { return withQtyCount(getQtyCount().toZero()); } public InventoryLineHU withQtyCount(@NonNull final Quantity newQtyCount) { assertPhysicalInventory(); return toBuilder().qtyCount(newQtyCount).build(); } public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs) { return extractHuIds(lineHUs.stream()); } static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs)
{ return lineHUs .map(InventoryLineHU::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder { InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请在Spring Boot框架中完成以下Java代码
private void mapProperties(ThymeleafProperties properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getEncoding).to(resolver::setDefaultCharset); resolver.setExcludedViewNames(properties.getExcludedViewNames()); resolver.setViewNames(properties.getViewNames()); } private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).to(resolver::setSupportedMediaTypes); map.from(properties::getMaxChunkSize) .asInt(DataSize::toBytes) .when((size) -> size > 0) .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LayoutDialect.class) static class ThymeleafWebLayoutConfiguration { @Bean @ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean
@ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请完成以下Java代码
public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); }
/** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\pricing\model\X_C_PricingRule.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return C_BPartner_ID; } public int getM_Product_ID() { return M_Product_ID; } public int getM_AttributeSetInstance_ID() { return M_AttributeSetInstance_ID; } // public int getM_HU_PI_Item_Product_ID() // { // return M_HU_PI_Item_Product_ID; // } public int getC_Flatrate_DataEntry_ID() { return C_Flatrate_DataEntry_ID; } public static final class Builder { private Integer C_BPartner_ID; private Integer M_Product_ID; private int M_AttributeSetInstance_ID = 0; // private Integer M_HU_PI_Item_Product_ID; private int C_Flatrate_DataEntry_ID = -1; private Builder() { super(); } public PMMBalanceSegment build()
{ return new PMMBalanceSegment(this); } public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setM_Product_ID(final int M_Product_ID) { this.M_Product_ID = M_Product_ID; return this; } public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID; return this; } // public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID) // { // this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID; // return this; // } public Builder setC_Flatrate_DataEntry_ID(final int C_Flatrate_DataEntry_ID) { this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceSegment.java
1
请完成以下Java代码
public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder(String deviceRpcRequestProtoSchema) { return DynamicProtoUtils.getDynamicMessageBuilder(deviceRpcRequestProtoSchema, RPC_REQUEST_PROTO_SCHEMA); } public String getDeviceRpcResponseProtoSchema() { if (StringUtils.isNotEmpty(deviceRpcResponseProtoSchema)) { return deviceRpcResponseProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcResponseMsg {\n" + " optional string payload = 1;\n" + "}"; } }
public String getDeviceRpcRequestProtoSchema() { if (StringUtils.isNotEmpty(deviceRpcRequestProtoSchema)) { return deviceRpcRequestProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcRequestMsg {\n" + " optional string method = 1;\n" + " optional int32 requestId = 2;\n" + " optional string params = 3;\n" + "}"; } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\profile\ProtoTransportPayloadConfiguration.java
1
请完成以下Java代码
protected void paintThumb(final Graphics g, final JComponent c, final Rectangle r) { final Color color; if (!scrollbar.isEnabled()) { color = thumbColor; } else if (isDragging || isMouseButtonPressed) { color = thumbColorDragging; } else if (isThumbRollover()) { color = thumbColorMouseOver; } else { color = thumbColor; } g.setColor(color); g.fillRect(r.x, r.y, r.width, r.height); } @Override protected void paintTrack(final Graphics g, final JComponent c, final Rectangle r) { g.setColor(trackColor); g.fillRect(r.x, r.y, r.width, r.height); } @Override protected JButton createDecreaseButton(final int orientation) { return noButton; } @Override protected JButton createIncreaseButton(final int orientation) { return noButton; } @Override protected TrackListener createTrackListener() { return new MetasTrackListener();
} private class MetasTrackListener extends TrackListener { @Override public void mousePressed(MouseEvent e) { isMouseButtonPressed = true; super.mousePressed(e); scrollbar.repaint(getThumbBounds()); } @Override public void mouseReleased(MouseEvent e) { isMouseButtonPressed = false; super.mouseReleased(e); scrollbar.repaint(getThumbBounds()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshScrollBarUI.java
1
请完成以下Java代码
public VPanelFormFieldBuilder setMandatory(boolean mandatory) { this.mandatory = mandatory; return this; } private boolean isAutocomplete() { if (autocomplete != null) { return autocomplete; } // if Search, always auto-complete if (DisplayType.Search == displayType) { return true; } return false; } public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete) { this.autocomplete = autocomplete; return this; } private int getAD_Column_ID() { // not set is allowed return AD_Column_ID; } /** * @param AD_Column_ID Column for lookups. */ public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID)
{ this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener) { this.editorListener = listener; return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请完成以下Java代码
private BigDecimal computePriceDifference(@NonNull final ContextForCompesationOrder compensationOrderContext, @NonNull final I_C_Contract_Change contractChange) { final List<I_C_SubscriptionProgress> sps = compensationOrderContext.getSubscriptionProgress(); final Timestamp changeDate = compensationOrderContext.getChangeDate(); final List<I_C_SubscriptionProgress> deliveries = sps.stream() .filter(currentSP -> changeDate.after(currentSP.getEventDate()) && X_C_SubscriptionProgress.EVENTTYPE_Delivery.equals(currentSP.getEventType())) .collect(Collectors.toList()); if (deliveries.isEmpty()) { return BigDecimal.ZERO; } final ISubscriptionBL subscriptionBL = Services.get(ISubscriptionBL.class); final I_C_Flatrate_Term currentTerm = compensationOrderContext.getCurrentTerm(); final Properties ctx = InterfaceWrapperHelper.getCtx(currentTerm); final String trxName = InterfaceWrapperHelper.getTrxName(currentTerm); final PricingSystemId pricingSystemId = getPricingSystemId(currentTerm, contractChange); // compute the difference (see javaDoc of computePriceDifference for details) final BigDecimal difference = subscriptionBL.computePriceDifference(ctx, pricingSystemId, deliveries, trxName); logger.debug("The price difference to be applied on deliveries before the change is " + difference); return difference; }
private PricingSystemId getPricingSystemId(final I_C_Flatrate_Term currentTerm, final I_C_Contract_Change changeConditions) { final PricingSystemId pricingSystemId; if (changeConditions.getM_PricingSystem_ID() > 0) { pricingSystemId = PricingSystemId.ofRepoIdOrNull(changeConditions.getM_PricingSystem_ID()); } else { pricingSystemId = PricingSystemId.ofRepoIdOrNull(currentTerm.getC_Flatrate_Conditions().getM_PricingSystem_ID()); } return pricingSystemId; } @Override public void endContract(@NonNull final I_C_Flatrate_Term currentTerm) { currentTerm.setIsAutoRenew(false); currentTerm.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract); save(currentTerm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractChangeBL.java
1
请在Spring Boot框架中完成以下Java代码
public class BookController { private final BookRepository repository; public BookController(BookRepository repository) { this.repository = repository; } @Operation(summary = "Get a book by its id") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Found the book", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Book.class))}), @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), @ApiResponse(responseCode = "404", description = "Book not found", content = @Content)}) // @formatter:on @GetMapping("/{id}") public Book findById(@Parameter(description = "id of book to be searched") @PathVariable long id) { return repository.findById(id) .orElseThrow(BookNotFoundException::new); } @GetMapping("/") public Collection<Book> findBooks() { return repository.getBooks(); } @GetMapping("/filter") public Page<Book> filterBooks(@ParameterObject Pageable pageable) { return repository.getBooks(pageable); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.OK) public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) { return book; } @PatchMapping("/{id}") @ResponseStatus(HttpStatus.OK) public Book patchBook(@PathVariable("id") final String id, @RequestBody final Book book) { return book; }
@PostMapping("/") @ResponseStatus(HttpStatus.CREATED) public Book postBook(@NotNull @Valid @RequestBody final Book book) { return book; } @RequestMapping(method = RequestMethod.HEAD, value = "/") @ResponseStatus(HttpStatus.OK) public Book headBook() { return new Book(); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.OK) public long deleteBook(@PathVariable final long id) { return id; } @Operation(summary = "Create a new book") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Book created successfully", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Book.class)) }), @ApiResponse(responseCode = "400", description = "Invalid input provided") }) @PostMapping("/body-description") public Book createBook(@io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Book to create", required = true, content = @Content(mediaType = "application/json", schema = @Schema(implementation = Book.class), examples = @ExampleObject(value = "{ \"title\": \"New Book\", \"author\": \"Author Name\" }"))) @RequestBody Book book) { return null; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\springdoc\controller\BookController.java
2
请完成以下Java代码
private static DocumentFilterDescriptor createDefaultFilterDescriptor() { return DocumentFilterDescriptor.builder() .setFilterId(ProductsProposalViewFilter.FILTER_ID) .setFrequentUsed(true) .setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS) .setDisplayName(getDefaultFilterCaption()) .addParameter(newParamDescriptor(ProductsProposalViewFilter.PARAM_ProductName) .widgetType(DocumentFieldWidgetType.Text)) .build(); } private static ITranslatableString getDefaultFilterCaption() { return Services.get(IMsgBL.class).getTranslatableMsgText("Default"); } private static DocumentFilterParamDescriptor.Builder newParamDescriptor(final String fieldName) { return DocumentFilterParamDescriptor.builder() .fieldName(fieldName) .displayName(Services.get(IMsgBL.class).translatable(fieldName)); } public static ProductsProposalViewFilter extractPackageableViewFilterVO(@NonNull final JSONFilterViewRequest filterViewRequest) { final DocumentFilterList filters = filterViewRequest.getFiltersUnwrapped(getDescriptors()); return extractPackageableViewFilterVO(filters); } private static ProductsProposalViewFilter extractPackageableViewFilterVO(final DocumentFilterList filters) { return filters.getFilterById(ProductsProposalViewFilter.FILTER_ID) .map(filter -> toProductsProposalViewFilterValue(filter)) .orElse(ProductsProposalViewFilter.ANY); } private static ProductsProposalViewFilter toProductsProposalViewFilterValue(final DocumentFilter filter) { return ProductsProposalViewFilter.builder()
.productName(filter.getParameterValueAsString(ProductsProposalViewFilter.PARAM_ProductName, null)) .build(); } public static DocumentFilterList toDocumentFilters(final ProductsProposalViewFilter filter) { final DocumentFilter.DocumentFilterBuilder builder = DocumentFilter.builder() .setFilterId(ProductsProposalViewFilter.FILTER_ID) .setCaption(getDefaultFilterCaption()); if (!Check.isEmpty(filter.getProductName())) { builder.addParameter(DocumentFilterParam.ofNameEqualsValue(ProductsProposalViewFilter.PARAM_ProductName, filter.getProductName())); } if (!builder.hasParameters()) { return DocumentFilterList.EMPTY; } return DocumentFilterList.of(builder.build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\filters\ProductsProposalViewFilters.java
1
请在Spring Boot框架中完成以下Java代码
/* for testing */ static class GroupWeightConfig { String group; LinkedHashMap<String, Integer> weights = new LinkedHashMap<>(); LinkedHashMap<String, Double> normalizedWeights = new LinkedHashMap<>(); LinkedHashMap<Integer, String> rangeIndexes = new LinkedHashMap<>(); List<Double> ranges = new ArrayList<>(); GroupWeightConfig(String group) { this.group = group; } GroupWeightConfig(GroupWeightConfig other) {
this.group = other.group; this.weights = new LinkedHashMap<>(other.weights); this.normalizedWeights = new LinkedHashMap<>(other.normalizedWeights); this.rangeIndexes = new LinkedHashMap<>(other.rangeIndexes); } @Override public String toString() { return new ToStringCreator(this).append("group", group) .append("weights", weights) .append("normalizedWeights", normalizedWeights) .append("rangeIndexes", rangeIndexes) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\WeightCalculatorWebFilter.java
2
请完成以下Java代码
private void createAndHandleDataUpdateRequests( @NonNull final List<I_MD_Stock_From_HUs_V> huBasedDataRecords) { final ResetStockPInstanceId resetStockPInstanceId = ResetStockPInstanceId.ofPInstanceId(getProcessInfo().getPinstanceId()); final StockChangeSourceInfo info = StockChangeSourceInfo.ofResetStockPInstanceId(resetStockPInstanceId); for (final I_MD_Stock_From_HUs_V huBasedDataRecord : huBasedDataRecords) { final StockDataUpdateRequest dataUpdateRequest = createDataUpdatedRequest( huBasedDataRecord, info); addLog("Handling corrective dataUpdateRequest={}", dataUpdateRequest); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } } private StockDataUpdateRequest createDataUpdatedRequest( @NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord, @NonNull final StockChangeSourceInfo stockDataUpdateRequestSourceInfo) { final StockDataRecordIdentifier recordIdentifier = toStockDataRecordIdentifier(huBasedDataRecord); final ProductId productId = ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID()); final Quantity qtyInStorageUOM = Quantitys.of(huBasedDataRecord.getQtyOnHandChange(), UomId.ofRepoId(huBasedDataRecord.getC_UOM_ID())); final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(qtyInStorageUOM, productId);
return StockDataUpdateRequest.builder() .identifier(recordIdentifier) .onHandQtyChange(qtyInProductUOM.toBigDecimal()) .sourceInfo(stockDataUpdateRequestSourceInfo) .build(); } private static StockDataRecordIdentifier toStockDataRecordIdentifier(@NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord) { return StockDataRecordIdentifier.builder() .clientId(ClientId.ofRepoId(huBasedDataRecord.getAD_Client_ID())) .orgId(OrgId.ofRepoId(huBasedDataRecord.getAD_Org_ID())) .warehouseId(WarehouseId.ofRepoId(huBasedDataRecord.getM_Warehouse_ID())) .productId(ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID())) .storageAttributesKey(AttributesKey.ofString(huBasedDataRecord.getAttributesKey())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\process\MD_Stock_Update_From_M_HUs.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<List<Customer>> createCustomers(@RequestHeader(value = "X-ActionType") String actionType, @RequestBody @Valid @Size(min = 1, max = 20) List<Customer> customers) { List<Customer> customerList = actionType.equals("bulk") ? customerService.createCustomers(customers) : Collections.singletonList(customerService.createCustomer(customers.get(0)).orElse(null)); return new ResponseEntity<>(customerList, HttpStatus.CREATED); } @PostMapping(path = "/customers/bulk") public ResponseEntity<List<CustomerBulkResponse>> bulkProcessCustomers(@RequestBody @Valid @Size(min = 1, max = 20) List<CustomerBulkRequest> customerBulkRequests) { List<CustomerBulkResponse> customerBulkResponseList = new ArrayList<>(); customerBulkRequests.forEach(customerBulkRequest -> { List<Customer> customers = customerBulkRequest.getCustomers().stream() .map(bulkActionFuncMap.get(customerBulkRequest.getBulkActionType())) .filter(Optional::isPresent) .map(Optional::get) .collect(toList()); BulkStatus bulkStatus = getBulkStatus(customerBulkRequest.getCustomers(), customers); customerBulkResponseList.add(new CustomerBulkResponse(customers, customerBulkRequest.getBulkActionType(), bulkStatus));
}); return new ResponseEntity<>(customerBulkResponseList, HttpStatus.MULTI_STATUS); } private BulkStatus getBulkStatus(List<Customer> customersInRequest, List<Customer> customersProcessed) { if (!customersProcessed.isEmpty()) { return customersProcessed.size() == customersInRequest.size() ? BulkStatus.PROCESSED : BulkStatus.PARTIALLY_PROCESSED; } return BulkStatus.NOT_PROCESSED; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\controller\BulkController.java
2
请完成以下Java代码
private boolean isJetty10() { try { return CompletableFuture.class.equals(Connector.class.getMethod("shutdown").getReturnType()); } catch (Exception ex) { return false; } } private void awaitShutdown(GracefulShutdownCallback callback) { while (!this.aborted && this.activeRequests.get() > 0) { sleep(100); } 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); }
} private void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } void abort() { this.aborted = true; } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\GracefulShutdown.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Roo other = (Roo) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } public Long getId() { return id; } public String getName() { return name;
} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public void setId(final Long id) { this.id = id; } @Override public String toString() { return "Roo [id=" + id + ", name=" + name + "]"; } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Roo.java
1
请完成以下Java代码
private static final class Jackson2 { private static ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); ClassLoader classLoader = Jackson2.class.getClassLoader(); List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader); objectMapper.registerModules(securityModules); objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module()); return objectMapper; } } /** * Nested class used to get a common default instance of {@link JsonMapper}. It is in * a nested class to protect from getting {@link NoClassDefFoundError} when Jackson 3 * is not on the classpath. */ private static final class Jackson3 { private static JsonMapper createJsonMapper() {
List<JacksonModule> modules = SecurityJacksonModules.getModules(Jackson3.class.getClassLoader()); return JsonMapper.builder().addModules(modules).build(); } } static class JdbcRegisteredClientRepositoryRuntimeHintsRegistrar implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints.resources() .registerResource(new ClassPathResource( "org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\JdbcRegisteredClientRepository.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(REGEXP_KEY, REPLACEMENT_KEY); } @Override public GatewayFilter apply(Config config) { String replacementValue = Objects.requireNonNull(config.replacement, "replacement must not be null"); String replacement = replacementValue.replace("$\\", "$"); String regexpValue = Objects.requireNonNull(config.regexp, "regexp must not be null"); Pattern pattern = Pattern.compile(regexpValue); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest req = exchange.getRequest(); addOriginalRequestUrl(exchange, req.getURI()); String path = req.getURI().getRawPath(); String newPath = pattern.matcher(path).replaceAll(replacement); ServerHttpRequest request = req.mutate().path(newPath).build(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI()); return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { String regexp = config.getRegexp(); return filterToStringCreator(RewritePathGatewayFilterFactory.this) .append(regexp != null ? regexp : "", replacement) .toString(); }
}; } public static class Config { private @Nullable String regexp; private @Nullable String replacement; public @Nullable String getRegexp() { return regexp; } public Config setRegexp(String regexp) { Assert.hasText(regexp, "regexp must have a value"); this.regexp = regexp; return this; } public @Nullable String getReplacement() { return replacement; } public Config setReplacement(String replacement) { Objects.requireNonNull(replacement, "replacement must not be null"); this.replacement = replacement; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewritePathGatewayFilterFactory.java
1
请完成以下Java代码
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return getDbEntityManager().selectList("selectCommentsByProcessInstanceId", processInstanceId); } public CommentEntity findCommentByTaskIdAndCommentId(String taskId, String commentId) { checkHistoryEnabled(); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("taskId", taskId); parameters.put("id", commentId); return (CommentEntity) getDbEntityManager().selectOne("selectCommentByTaskIdAndCommentId", parameters); } public CommentEntity findCommentByProcessInstanceIdAndCommentId(String processInstanceId, String commentId) { checkHistoryEnabled(); Map<String, String> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("id", commentId); return (CommentEntity) getDbEntityManager().selectOne("selectCommentByProcessInstanceIdAndCommentId", parameters); } public DbOperation addRemovalTimeToCommentsByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(CommentEntity.class, "updateCommentsByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToCommentsByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(CommentEntity.class, "updateCommentsByProcessInstanceId", parameters); } public DbOperation deleteCommentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(CommentEntity.class, "deleteCommentsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentManager.java
1
请完成以下Java代码
public void setTaskCount(int taskCount) { this.taskCount = taskCount; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public static TaskCountByCandidateGroupResultDto fromTaskCountByCandidateGroupResultDto(TaskCountByCandidateGroupResult taskCountByCandidateGroupResult) { TaskCountByCandidateGroupResultDto dto = new TaskCountByCandidateGroupResultDto(); dto.groupName = taskCountByCandidateGroupResult.getGroupName();
dto.taskCount = taskCountByCandidateGroupResult.getTaskCount(); return dto; } public List<TaskCountByCandidateGroupResult> executeTaskCountByCandidateGroupReport(ProcessEngine engine) { TaskReport reportQuery = engine.getTaskService().createTaskReport(); try { return reportQuery.taskCountByCandidateGroup(); } catch( NotValidException e ) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, e, e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskCountByCandidateGroupResultDto.java
1
请完成以下Java代码
public org.compiere.model.I_C_Invoice getService_Fee_Invoice() { return get_ValueAsPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setService_Fee_Invoice(final org.compiere.model.I_C_Invoice Service_Fee_Invoice) { set_ValueFromPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class, Service_Fee_Invoice); } @Override public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID) { if (Service_Fee_Invoice_ID < 1) set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null); else set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID); } @Override public int getService_Fee_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID); } @Override public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate) { set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate); } @Override public BigDecimal getServiceFeeVatRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setService_Product_ID (final int Service_Product_ID) { if (Service_Product_ID < 1) set_Value (COLUMNNAME_Service_Product_ID, null); else set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID); } @Override public int getService_Product_ID() { return get_ValueAsInt(COLUMNNAME_Service_Product_ID); } @Override public void setService_Tax_ID (final int Service_Tax_ID) { if (Service_Tax_ID < 1) set_Value (COLUMNNAME_Service_Tax_ID, null); else set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID); } @Override public int getService_Tax_ID() { return get_ValueAsInt(COLUMNNAME_Service_Tax_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java
1
请在Spring Boot框架中完成以下Java代码
public class OrdersService { private final OrdersRepository repo; private final NotifierService notifier; private final Cache ordersCache; @Transactional public Order createOrder(OrderType orderType, String symbol, BigDecimal quantity, BigDecimal price) { Order order = new Order(); order.setOrderType(orderType); order.setSymbol(symbol); order.setQuantity(quantity); order.setPrice(price); order = repo.save(order); notifier.notifyOrderCreated(order); return order; } @Transactional(readOnly = true) public Optional<Order> findById(Long id) { Optional<Order> o = Optional.ofNullable(ordersCache.get(id, Order.class)); if ( o.isPresent() ) {
log.info("findById: cache hit, id={}",id); return o; } log.info("findById: cache miss, id={}",id); o = repo.findById(id); if ( !o.isPresent()) { return o; } ordersCache.put(id, o.get()); return o; } }
repos\tutorials-master\messaging-modules\postgres-notify\src\main\java\com\baeldung\messaging\postgresql\service\OrdersService.java
2
请完成以下Java代码
public int getAD_BoilerPlate_ID() { return get_ValueAsInt(COLUMNNAME_AD_BoilerPlate_ID); } @Override public void setC_Async_Batch_Type_ID (final int C_Async_Batch_Type_ID) { if (C_Async_Batch_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, C_Async_Batch_Type_ID); } @Override public int getC_Async_Batch_Type_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_Type_ID); } @Override public void setInternalName (final String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @Override public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours) { set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours); } @Override public String getKeepAliveTimeHours() { return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours); } /** * NotificationType AD_Reference_ID=540643 * Reference name: _NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643;
/** Async Batch Processed = ABP */ public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP"; /** Workpackage Processed = WPP */ public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP"; @Override public void setNotificationType (final @Nullable String NotificationType) { set_Value (COLUMNNAME_NotificationType, NotificationType); } @Override public String getNotificationType() { return get_ValueAsString(COLUMNNAME_NotificationType); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java
1
请完成以下Java代码
public static void clearQuickInputFieldsLater(final int windowNo, final GridTab mTab) { // clear the values in the inventory window // using invokeLater because at the time of this callout invocation we // are most probably in the mights of something that might prevent // changes to the actual swing component Services.get(IClientUI.class).invokeLater(windowNo, new Runnable() { @Override public void run() { clearQuickInputFields(mTab); } }); } /** * Reset quick input fieldsO * * @param mTab */ public static void clearQuickInputFields(final GridTab mTab) { final I_M_Inventory inventory = InterfaceWrapperHelper.create(mTab, I_M_Inventory.class);
inventory.setQuickInput_Product_ID(-1); inventory.setQuickInput_QtyInternalGain(null); // these changes will be propagated to the GUI component mTab.setValue(I_M_Inventory.COLUMNNAME_QuickInput_Product_ID, null); mTab.setValue(I_M_Inventory.COLUMNNAME_QuickInput_QtyInternalGain, null); mTab.dataSave(true); } /** * Refreshes given tab and all included tabs. * * @param gridTab */ private void refreshTabAndIncludedTabs(final GridTab gridTab) { gridTab.dataRefreshRecursively(); for (final GridTab includedTab : gridTab.getIncludedTabs()) { includedTab.dataRefreshAll(); } gridTab.dataRefresh(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\M_Inventory.java
1
请完成以下Java代码
public void setM_FreightCost_ID (int M_FreightCost_ID) { if (M_FreightCost_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCost_ID, Integer.valueOf(M_FreightCost_ID)); } /** Get Frachtkostenpauschale. @return Frachtkostenpauschale */ public int getM_FreightCost_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCost_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_FreightCost_includedTab. @param M_FreightCost_includedTab M_FreightCost_includedTab */ public void setM_FreightCost_includedTab (String M_FreightCost_includedTab) { set_ValueNoCheck (COLUMNNAME_M_FreightCost_includedTab, M_FreightCost_includedTab); } /** Get M_FreightCost_includedTab. @return M_FreightCost_includedTab */ public String getM_FreightCost_includedTab () { return (String)get_Value(COLUMNNAME_M_FreightCost_includedTab); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumerische Bezeichnung fuer diesen Eintrag */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Suchschluessel. @param Value Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschluessel. @return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java
1
请完成以下Java代码
public MRegistrationValue[] getValues (boolean onlySelfService) { createMissingValues(); // String sql = "SELECT * FROM A_RegistrationValue rv " + "WHERE A_Registration_ID=?"; if (onlySelfService) sql += " AND EXISTS (SELECT * FROM A_RegistrationAttribute ra WHERE rv.A_RegistrationAttribute_ID=ra.A_RegistrationAttribute_ID" + " AND ra.IsActive='Y' AND ra.IsSelfService='Y')"; // sql += " ORDER BY A_RegistrationAttribute_ID"; ArrayList<MRegistrationValue> list = new ArrayList<MRegistrationValue>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getA_Registration_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) list.add(new MRegistrationValue(getCtx(), rs, get_TrxName())); rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null; } // Convert and Sort MRegistrationValue[] retValue = new MRegistrationValue[list.size()]; list.toArray(retValue); Arrays.sort(retValue); return retValue; } // getValues /** * Create Missing Attribute Values */ private void createMissingValues() { String sql = "SELECT ra.A_RegistrationAttribute_ID " + "FROM A_RegistrationAttribute ra" + " LEFT OUTER JOIN A_RegistrationProduct rp ON (rp.A_RegistrationAttribute_ID=ra.A_RegistrationAttribute_ID)"
+ " LEFT OUTER JOIN A_Registration r ON (r.M_Product_ID=rp.M_Product_ID) " + "WHERE r.A_Registration_ID=?" // Not in Registration + " AND NOT EXISTS (SELECT A_RegistrationAttribute_ID FROM A_RegistrationValue v " + "WHERE ra.A_RegistrationAttribute_ID=v.A_RegistrationAttribute_ID AND r.A_Registration_ID=v.A_Registration_ID)"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, get_TrxName()); pstmt.setInt(1, getA_Registration_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { MRegistrationValue v = new MRegistrationValue (this, rs.getInt(1), "?"); v.save(); } rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.error(null, e); } try { if (pstmt != null) pstmt.close(); pstmt = null; } catch (Exception e) { pstmt = null; } } // createMissingValues } // MRegistration
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistration.java
1
请完成以下Java代码
public void beforeCreate(EntryEvent<ID, T> event) throws CacheWriterException { doRepositoryOp(event.getNewValue(), getRepository()::save); } @Override public void beforeUpdate(EntryEvent<ID, T> event) throws CacheWriterException { doRepositoryOp(event.getNewValue(), getRepository()::save); } @Override public void beforeDestroy(EntryEvent<ID, T> event) throws CacheWriterException { //doRepositoryOp(event.getOldValue(), FunctionUtils.toNullReturningFunction(getRepository()::delete)); doRepositoryOp(event.getKey(), FunctionUtils.toNullReturningFunction(getRepository()::deleteById)); } @Override public void beforeRegionClear(RegionEvent<ID, T> event) throws CacheWriterException {
if (isNukeAndPaveEnabled()) { doRepositoryOp(null, FunctionUtils.toNullReturningFunction(it -> getRepository().deleteAll())); } } @Override public void beforeRegionDestroy(RegionEvent<ID, T> event) throws CacheWriterException { // TODO: perhaps implement by releasing external data source resources // (i.e. destroy database object(s), e.g. DROP TABLE) } @Override protected CacheRuntimeException newCacheRuntimeException(Supplier<String> messageSupplier, Throwable cause) { return new CacheWriterException(messageSupplier.get(), cause); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryCacheWriter.java
1
请完成以下Java代码
public final String getText() { return textBox.getText(); } protected final int getTextCaretPosition() { return textBox.getCaretPosition(); } protected final void setTextCaretPosition(final int caretPosition) { textBox.setCaretPosition(caretPosition); } protected final void setText(final String text) { textBox.setText(text); }
public final boolean isEnabled() { final boolean textBoxHasFocus = textBox.isFocusOwner(); return textBoxHasFocus; } public void setPopupMinimumChars(final int popupMinimumChars) { m_popupMinimumChars = popupMinimumChars; } public int getPopupMinimumChars() { return m_popupMinimumChars; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FieldAutoCompleter.java
1
请完成以下Java代码
public void changedName(String old) { } @Override public void changedPath(String old) { } @Override public void addedChild(Resource child) { } @Override public void removedChild(Resource child) { } @Override public void addedObserveRelation(ObserveRelation relation) { Request request = relation.getExchange().getRequest(); String token = getTokenFromRequest(request); clients.registerObserveRelation(token, relation); log.trace("Added Observe relation for token: {}", token); } @Override public void removedObserveRelation(ObserveRelation relation) { Request request = relation.getExchange().getRequest(); String token = getTokenFromRequest(request); clients.deregisterObserveRelation(token); log.trace("Relation removed for token: {}", token); } } private TbCoapDtlsSessionInfo getCoapDtlsSessionInfo(EndpointContext endpointContext) { InetSocketAddress peerAddress = endpointContext.getPeerAddress(); String certPemStr = getCertPem(endpointContext); TbCoapDtlsSessionKey tbCoapDtlsSessionKey = StringUtils.isNotBlank(certPemStr) ? new TbCoapDtlsSessionKey(peerAddress, certPemStr) : null;
TbCoapDtlsSessionInfo tbCoapDtlsSessionInfo; if (tbCoapDtlsSessionKey != null) { tbCoapDtlsSessionInfo = dtlsSessionsMap .computeIfPresent(tbCoapDtlsSessionKey, (dtlsSessionIdStr, dtlsSessionInfo) -> { dtlsSessionInfo.setLastActivityTime(System.currentTimeMillis()); return dtlsSessionInfo; }); } else { tbCoapDtlsSessionInfo = null; } return tbCoapDtlsSessionInfo; } private String getCertPem(EndpointContext endpointContext) { try { X509CertPath certPath = (X509CertPath) endpointContext.getPeerIdentity(); X509Certificate x509Certificate = (X509Certificate) certPath.getPath().getCertificates().get(0); return Base64.getEncoder().encodeToString(x509Certificate.getEncoded()); } catch (Exception e) { log.error("Failed to get cert PEM: [{}]", endpointContext.getPeerAddress(), e); return null; } } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\CoapTransportResource.java
1
请完成以下Java代码
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } public ViewId getInitialViewId() { return initialViewId != null ? initialViewId : getViewId(); } @Override public ViewId getParentViewId() { return initialViewId; } public Optional<OrderId> getOrderId() { return rowsData.getOrder().map(Order::getOrderId); } public Optional<BPartnerId> getBpartnerId() { return rowsData.getBpartnerId(); } public SOTrx getSoTrx() { return rowsData.getSoTrx(); } public CurrencyId getCurrencyId() { return rowsData.getCurrencyId(); } public Set<ProductId> getProductIds() { return rowsData.getProductIds(); } public Optional<PriceListVersionId> getSinglePriceListVersionId() { return rowsData.getSinglePriceListVersionId(); }
public Optional<PriceListVersionId> getBasePriceListVersionId() { return rowsData.getBasePriceListVersionId(); } public PriceListVersionId getBasePriceListVersionIdOrFail() { return rowsData.getBasePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@")); } public List<ProductsProposalRow> getAllRows() { return ImmutableList.copyOf(getRows()); } public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests) { rowsData.addOrUpdateRows(requests); invalidateAll(); } public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request) { rowsData.patchRow(rowId, request); } public void removeRowsByIds(final Set<DocumentId> rowIds) { rowsData.removeRowsByIds(rowIds); invalidateAll(); } public ProductsProposalView filter(final ProductsProposalViewFilter filter) { rowsData.filter(filter); return this; } @Override public DocumentFilterList getFilters() { return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
1
请在Spring Boot框架中完成以下Java代码
public ItemProcessor<RecordSO, WriterSO> processor() { return new RecordProcessor(); } @Bean public ItemWriter<WriterSO> writer(DataSource dataSource, ItemPreparedStatementSetter<WriterSO> setter) { JdbcBatchItemWriter<WriterSO> writer = new JdbcBatchItemWriter<>(); writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()); writer.setItemPreparedStatementSetter(setter); writer.setSql("insert into writer (id, full_name, random_num) values (?,?,?)"); writer.setDataSource(dataSource); return writer; } @Bean public ItemPreparedStatementSetter<WriterSO> setter() { return (item, ps) -> { ps.setLong(1, item.getId()); ps.setString(2, item.getFullName()); ps.setString(3, item.getRandomNum()); }; } @Bean
public Job importUserJob(JobBuilderFactory jobs, Step s1, JobExecutionListener listener) { return jobs.get("importUserJob") .incrementer(new RunIdIncrementer()) .listener(listener) .flow(s1) .end() .build(); } @Bean public Step step1(StepBuilderFactory stepBuilderFactory, ItemReader<RecordSO> reader, ItemWriter<WriterSO> writer, ItemProcessor<RecordSO, WriterSO> processor) { return stepBuilderFactory.get("step1") .<RecordSO, WriterSO>chunk(5) .reader(reader) .processor(processor) .writer(writer) .build(); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
repos\spring-boot-quick-master\quick-batch\src\main\java\com\quick\batch\config\BatchConfiguration.java
2
请完成以下Java代码
public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() {
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_M_InOutLine_HU_IPA_SSCC18_v.java
1
请完成以下Java代码
public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID; return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID; return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) {
this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请完成以下Java代码
private static UserAuthToken fromRecord(final I_AD_User_AuthToken userAuthTokenPO) { return UserAuthToken.builder() .userId(UserId.ofRepoId(userAuthTokenPO.getAD_User_ID())) .authToken(userAuthTokenPO.getAuthToken()) .description(userAuthTokenPO.getDescription()) // Even if the record's AD_Client_ID is 0 (because we are the metasfresh-user with AD_User_ID=100), we return the metasfresh-client for our API access. //.clientId(ClientId.ofRepoId(userAuthTokenPO.getAD_Client_ID())) .clientId(ClientId.METASFRESH) .orgId(OrgId.ofRepoId(userAuthTokenPO.getAD_Org_ID())) .roleId(RoleId.ofRepoId(userAuthTokenPO.getAD_Role_ID())) .build(); } public UserAuthToken getOrCreateNew(@NonNull final CreateUserAuthTokenRequest request) { return getExisting(request).orElseGet(() -> createNew(request)); } private Optional<UserAuthToken> getExisting(@NonNull final CreateUserAuthTokenRequest request) { return queryBL .createQueryBuilder(I_AD_User_AuthToken.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_User_ID, request.getUserId()) .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Client_ID, request.getClientId()) .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Org_ID, request.getOrgId()) .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Role_ID, request.getRoleId()) .orderByDescending(I_AD_User_AuthToken.COLUMNNAME_AD_User_AuthToken_ID) .create() .firstOptional(I_AD_User_AuthToken.class) .map(UserAuthTokenRepository::fromRecord); } public UserAuthToken createNew(@NonNull final CreateUserAuthTokenRequest request) { final I_AD_User_AuthToken record = newInstanceOutOfTrx(I_AD_User_AuthToken.class); record.setAD_User_ID(request.getUserId().getRepoId());
InterfaceWrapperHelper.setValue(record, I_AD_User_AuthToken.COLUMNNAME_AD_Client_ID, request.getClientId().getRepoId()); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setAD_Role_ID(request.getRoleId().getRepoId()); record.setDescription(request.getDescription()); record.setAuthToken(generateAuthTokenString()); InterfaceWrapperHelper.saveRecord(record); return fromRecord(record); } public void deleteUserAuthTokenByUserId(@NonNull final UserId userId) { queryBL.createQueryBuilder(I_AD_User_AuthToken.class) .addEqualsFilter(I_AD_User_AuthToken.COLUMN_AD_User_ID, userId) .create() .delete(); } @NonNull public UserAuthToken getById(@NonNull final UserAuthTokenId id) { final I_AD_User_AuthToken record = queryBL.createQueryBuilder(I_AD_User_AuthToken.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_User_AuthToken_ID, id) .create() .firstOnlyNotNull(I_AD_User_AuthToken.class); return fromRecord(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserAuthTokenRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired private UserDetailsService jwtUserDetailsService; @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // configure AuthenticationManager so that it knows from where to load // user for matching credentials // Use BCryptPasswordEncoder auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example httpSecurity.csrf().disable() // dont authenticate this particular request .authorizeRequests().antMatchers("/authenticate").permitAll(). // all other requests need to be authenticated anyRequest().authenticated().and(). // make sure we use stateless session; session won't be used to // store user's state. exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Add a filter to validate the tokens with every request httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } }
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-boot-jwt-without-JPA\spring-boot-jwt\src\main\java\com\javainuse\config\WebSecurityConfig.java
2
请完成以下Java代码
public class DDOrderReferenceCollector implements DistributionOrderCollector<DDOrderReference> { @NonNull private final DistributionJobLoaderSupportingServices loadingSupportServices; private final ArrayList<DDOrderReference> _result = new ArrayList<>(); private final HashSet<DDOrderId> seenDDOrderIds = new HashSet<>(); private final ArrayList<I_DD_Order> collectedDDOrders = new ArrayList<>(); @Override public void collect(final I_DD_Order ddOrder) { final DDOrderId ddOrderId = extractDDOrderId(ddOrder); if (!seenDDOrderIds.add(ddOrderId)) { return; } collectedDDOrders.add(ddOrder); } @Override public List<DDOrderReference> getCollectedItems() { processPendingRequests(); return _result; } @NonNull private DistributionJobLoader newLoader() { return new DistributionJobLoader(loadingSupportServices); } private void processPendingRequests() { if (collectedDDOrders.isEmpty()) {return;} newLoader() .loadByRecords(collectedDDOrders) .stream() .map(DDOrderReferenceCollector::toDDOrderReference) .forEach(_result::add); collectedDDOrders.clear(); } @NonNull private static DDOrderReference toDDOrderReference(final DistributionJob job) {
return DDOrderReference.builder() .ddOrderId(job.getDdOrderId()) .documentNo(job.getDocumentNo()) .seqNo(job.getSeqNo()) .datePromised(job.getDateRequired()) .pickDate(job.getPickDate()) .fromWarehouseId(job.getPickFromWarehouse().getWarehouseId()) .toWarehouseId(job.getDropToWarehouse().getWarehouseId()) .salesOrderId(job.getSalesOrderRef() != null ? job.getSalesOrderRef().getId() : null) .ppOrderId(job.getManufacturingOrderRef() != null ? job.getManufacturingOrderRef().getId() : null) .isJobStarted(job.isJobAssigned()) .plantId(job.getPlantInfo() != null ? job.getPlantInfo().getResourceId() : null) .priority(job.getPriority()) .fromLocatorId(job.getSinglePickFromLocatorIdOrNull()) .toLocatorId(job.getSingleDropToLocatorIdOrNull()) .productId(job.getSingleProductIdOrNull()) .qty(job.getSingleUnitQuantityOrNull()) .isInTransit(job.isInTransit()) .build(); } @NonNull private static DDOrderId extractDDOrderId(final I_DD_Order ddOrder) {return DDOrderId.ofRepoId(ddOrder.getDD_Order_ID());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DDOrderReferenceCollector.java
1
请在Spring Boot框架中完成以下Java代码
public UUID getId() { return _id; } public void setId(UUID _id) { this._id = _id; } public PatientNoteMapping updatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } /** * Der Zeitstempel der letzten Änderung * @return updatedAt **/ @Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNoteMapping patientNoteMapping = (PatientNoteMapping) o; return Objects.equals(this._id, patientNoteMapping._id) && Objects.equals(this.updatedAt, patientNoteMapping.updatedAt); } @Override public int hashCode() { return Objects.hash(_id, updatedAt); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class PatientNoteMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientNoteMapping.java
2
请在Spring Boot框架中完成以下Java代码
public class CostClassificationCategoryId implements RepoIdAware { @JsonCreator public static CostClassificationCategoryId ofRepoId(final int repoId) { return new CostClassificationCategoryId(repoId); } @Nullable public static CostClassificationCategoryId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new CostClassificationCategoryId(repoId) : null; } public static int toRepoId(@Nullable final CostClassificationCategoryId costClassificationCategoryId) { return costClassificationCategoryId != null ? costClassificationCategoryId.getRepoId() : -1; }
int repoId; private CostClassificationCategoryId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CostClassificationCategoryId id1, @Nullable final CostClassificationCategoryId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\cost\classification\CostClassificationCategoryId.java
2
请完成以下Java代码
public void pushAllBPartners() { if (disabled.get()) { logger.info("Disabled is set to true in this thread; -> doing nothing"); return; } final IAgentSync agent = getAgentSync(); final List<SyncBPartner> allSyncBPartners = SyncObjectsFactory.newFactory().createAllSyncBPartners(); final PutBPartnersRequest request = PutBPartnersRequest.builder().bpartners(allSyncBPartners).build(); agent.syncBPartners(request); } @Override public void pushProduct(final I_PMM_Product pmmProduct) { if (disabled.get()) { logger.info("Disabled is set to true in this thread; -> doing nothing"); return; } final IAgentSync agent = getAgentSync(); final SyncProduct syncProduct = SyncObjectsFactory.newFactory().createSyncProduct(pmmProduct); final PutProductsRequest syncProductsRequest = PutProductsRequest.of(syncProduct); agent.syncProducts(syncProductsRequest); } @Override @ManagedOperation public void pushAllInfoMessages() { if (disabled.get()) { logger.info("Disabled is set to true in this thread; -> doing nothing"); return; } final IAgentSync agent = getAgentSync(); final String infoMessage = SyncObjectsFactory.newFactory().createSyncInfoMessage(); agent.syncInfoMessage(PutInfoMessageRequest.builder() .message(infoMessage) .build()); } @Override public void pushRfQs(@Nullable final List<SyncRfQ> syncRfqs) { if (disabled.get()) { logger.info("Disabled is set to true in this thread; -> doing nothing"); return; } if (syncRfqs == null || syncRfqs.isEmpty()) {
return; } final IAgentSync agent = getAgentSync(); agent.syncRfQs(syncRfqs); } @Override public void pushRfQCloseEvents( @Nullable final List<SyncRfQCloseEvent> syncRfQCloseEvents) { if (disabled.get()) { logger.info("Disabled is set to true in this thread; -> doing nothing"); return; } if (syncRfQCloseEvents == null || syncRfQCloseEvents.isEmpty()) { return; } final IAgentSync agent = getAgentSync(); agent.closeRfQs(syncRfQCloseEvents); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\WebuiPush.java
1
请在Spring Boot框架中完成以下Java代码
public class MainController { @Autowired private OrganizationRepository organizationRepository; // @PostAuthorize("hasPermission(returnObject, 'read')") @PreAuthorize("hasPermission(#id, 'Foo', 'read')") @GetMapping("/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo("Sample"); } @PreAuthorize("hasPermission(#foo, 'write')") @PostMapping("/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { return foo; } @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") @GetMapping("/foos") @ResponseBody public Foo findFooByName(@RequestParam final String name) {
return new Foo(name); } @PreAuthorize("isMember(#id)") @GetMapping("/organizations/{id}") @ResponseBody public Organization findOrgById(@PathVariable final long id) { return organizationRepository.findById(id) .orElse(null); } @PreAuthorize("hasPermission(#id, 'Foo', 'read')") @GetMapping("/user") @ResponseBody public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { return principal; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\web\MainController.java
2
请完成以下Java代码
public String objectToString(POInfoColumn columnInfo, Object value) { return objectToString(value, columnInfo.getDisplayType(), columnInfo.isMandatory()); } private String objectToString(final Object value, final int displayType, final boolean isMandatory) { if (value == null) { if (isMandatory) { logger.warn("Value is null even if is marked to be mandatory [Returning null]"); } return null; } // final String valueStr; if (DisplayType.isDate(displayType)) { valueStr = dateTimeFormat.format(value); } else if (DisplayType.YesNo == displayType) {
if (value instanceof Boolean) { valueStr = ((Boolean)value) ? "true" : "false"; } else { valueStr = "Y".equals(value) ? "true" : "false"; } return valueStr; } else { valueStr = value.toString(); } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\util\DefaultDataConverter.java
1
请在Spring Boot框架中完成以下Java代码
private Node addNode(TreeGraphNode treeGraphNode){ String nodeName = GraphUtil.getNodeValue(treeGraphNode); Node existNode = nodeRepository.findByName(nodeName); if (Objects.nonNull(existNode)) return existNode; Node node =new Node(); node.setName(nodeName); return nodeRepository.save(node); } @Override public List<Relation> parseAndBind(String sentence) { MainPart mp = MainPartExtractor.getMainPart(sentence); TreeGraphNode subject = mp.getSubject(); //主语 TreeGraphNode predicate = mp.getPredicate();//谓语 TreeGraphNode object = mp.getObject(); //宾语 if (Objects.isNull(subject) || Objects.isNull(object)) return null; Node startNode = addNode(subject); Node endNode = addNode(object);
String relationName = GraphUtil.getNodeValue(predicate);//关系词 List<Relation> oldRelation = relationRepository .findRelation(startNode, endNode,relationName); if (!oldRelation.isEmpty()) return oldRelation; Relation botRelation=new Relation(); botRelation.setStartNode(startNode); botRelation.setEndNode(endNode); botRelation.setRelation(relationName); Relation relation = relationRepository.save(botRelation); return Arrays.asList(relation); } }
repos\springboot-demo-master\neo4j\src\main\java\com\et\neo4j\service\NodeServiceImpl.java
2
请完成以下Java代码
public void setNewValue (java.lang.String NewValue) { set_Value (COLUMNNAME_NewValue, NewValue); } /** Get New Value. @return New field value */ @Override public java.lang.String getNewValue () { return (java.lang.String)get_Value(COLUMNNAME_NewValue); } /** Set Old Value. @param OldValue The old file data */
@Override public void setOldValue (java.lang.String OldValue) { set_Value (COLUMNNAME_OldValue, OldValue); } /** Get Old Value. @return The old file data */ @Override public java.lang.String getOldValue () { return (java.lang.String)get_Value(COLUMNNAME_OldValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationData.java
1
请完成以下Java代码
public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> deferredCsrfToken) { Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); Assert.notNull(deferredCsrfToken, "deferredCsrfToken cannot be null"); CsrfToken csrfToken = new SupplierCsrfToken(deferredCsrfToken); request.setAttribute(CsrfToken.class.getName(), csrfToken); String csrfAttrName = (this.csrfRequestAttributeName != null) ? this.csrfRequestAttributeName : csrfToken.getParameterName(); request.setAttribute(csrfAttrName, csrfToken); logger.trace(LogMessage.format("Wrote a CSRF token to the following request attributes: [%s, %s]", csrfAttrName, CsrfToken.class.getName())); } @SuppressWarnings("serial") private static final class SupplierCsrfToken implements CsrfToken { private final Supplier<CsrfToken> csrfTokenSupplier; private SupplierCsrfToken(Supplier<CsrfToken> csrfTokenSupplier) { this.csrfTokenSupplier = csrfTokenSupplier; } @Override public String getHeaderName() {
return getDelegate().getHeaderName(); } @Override public String getParameterName() { return getDelegate().getParameterName(); } @Override public String getToken() { return getDelegate().getToken(); } private CsrfToken getDelegate() { CsrfToken delegate = this.csrfTokenSupplier.get(); if (delegate == null) { throw new IllegalStateException("csrfTokenSupplier returned null delegate"); } return delegate; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfTokenRequestAttributeHandler.java
1
请完成以下Java代码
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesNodeConfiguration.class); keys = config.getKeys(); } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { List<String> keysToDelete = keys.stream() .map(keyPattern -> TbNodeUtils.processPattern(keyPattern, msg)) .distinct() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()); if (keysToDelete.isEmpty()) { ctx.tellSuccess(msg); } else { AttributeScope scope = getScope(msg.getMetaData().getValue(SCOPE)); ctx.getTelemetryService().deleteAttributes(AttributesDeleteRequest.builder() .tenantId(ctx.getTenantId()) .entityId(msg.getOriginator()) .scope(scope) .keys(keysToDelete) .notifyDevice(checkNotifyDevice(msg.getMetaData().getValue(NOTIFY_DEVICE_METADATA_KEY), scope)) .previousCalculatedFieldIds(msg.getPreviousCalculatedFieldIds()) .tbMsgId(msg.getId()) .tbMsgType(msg.getInternalType()) .callback(config.isSendAttributesDeletedNotification() ? new AttributesDeleteNodeCallback(ctx, msg, scope.name(), keysToDelete) : new TelemetryNodeCallback(ctx, msg))
.build()); } } private AttributeScope getScope(String mdScopeValue) { if (StringUtils.isNotEmpty(mdScopeValue)) { return AttributeScope.valueOf(mdScopeValue); } return AttributeScope.valueOf(config.getScope()); } private boolean checkNotifyDevice(String notifyDeviceMdValue, AttributeScope scope) { return (AttributeScope.SHARED_SCOPE == scope) && (config.isNotifyDevice() || Boolean.parseBoolean(notifyDeviceMdValue)); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\telemetry\TbMsgDeleteAttributesNode.java
1
请完成以下Java代码
public void setUnrealizedGain_A(org.compiere.model.I_C_ValidCombination UnrealizedGain_A) { set_ValueFromPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedGain_A); } /** Set Nicht realisierte Währungsgewinne. @param UnrealizedGain_Acct Konto für nicht realisierte Währungsgewinne */ @Override public void setUnrealizedGain_Acct (int UnrealizedGain_Acct) { set_Value (COLUMNNAME_UnrealizedGain_Acct, Integer.valueOf(UnrealizedGain_Acct)); } /** Get Nicht realisierte Währungsgewinne. @return Konto für nicht realisierte Währungsgewinne */ @Override public int getUnrealizedGain_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedGain_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A) { set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A); } /** Set Nicht realisierte Währungsverluste. @param UnrealizedLoss_Acct Konto für nicht realisierte Währungsverluste
*/ @Override public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct) { set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct)); } /** Get Nicht realisierte Währungsverluste. @return Konto für nicht realisierte Währungsverluste */ @Override public int getUnrealizedLoss_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_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_C_Currency_Acct.java
1
请完成以下Java代码
private EntityId getOriginatorId(TbContext ctx) throws TbNodeException { if (EntityType.RULE_NODE.equals(config.getOriginatorType())) { return ctx.getSelfId(); } if (EntityType.TENANT.equals(config.getOriginatorType())) { return ctx.getTenantId(); } if (StringUtils.isBlank(config.getOriginatorId())) { throw new TbNodeException("Originator entity must be selected.", true); } var entityId = EntityIdFactory.getByTypeAndUuid(config.getOriginatorType(), config.getOriginatorId()); ctx.checkTenantEntity(entityId); return entityId; } @Override public void destroy() { log.debug("[{}] Stopping generator", originatorId); initialized.set(false); prevMsg = null; nextTickId = null; lastScheduledTs = 0; if (scriptEngine != null) { scriptEngine.destroy(); scriptEngine = null; } } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: if (oldConfiguration.has(QUEUE_NAME)) { hasChanges = true; ((ObjectNode) oldConfiguration).remove(QUEUE_NAME); } case 1:
String originatorType = "originatorType"; String originatorId = "originatorId"; boolean hasType = oldConfiguration.hasNonNull(originatorType); boolean hasOriginatorId = oldConfiguration.hasNonNull(originatorId) && StringUtils.isNotBlank(oldConfiguration.get(originatorId).asText()); boolean hasOriginatorFields = hasType && hasOriginatorId; if (!hasOriginatorFields) { hasChanges = true; ((ObjectNode) oldConfiguration).put(originatorType, EntityType.RULE_NODE.name()); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\debug\TbMsgGeneratorNode.java
1
请完成以下Java代码
public class PrintArrayJava { // Print array content using a for loop public String printArrayUsingForLoop(String[] empArray) { StringBuilder result = new StringBuilder(); for (int i = 0; i < empArray.length; i++) { result.append(empArray[i]).append(" "); } return result.toString().trim(); } // Print array content using a for-each loop public String printArrayUsingForEachLoop(String[] empArray) { StringBuilder result = new StringBuilder(); for (String arr : empArray) { result.append(arr).append("\n"); } return result.toString().trim(); } // Print array content using Arrays.toString public String printArrayUsingToString(int[] empIDs) { return Arrays.toString(empIDs); }
// Print array content using Arrays.asList public String printArrayUsingAsList(String[] empArray) { return Arrays.asList(empArray).toString(); } // Print array content using Streams public String printArrayUsingStreams(String[] empArray) { StringBuilder result = new StringBuilder(); Arrays.stream(empArray).forEach(e -> result.append(e).append("\n")); return result.toString().trim(); } // Print array content using string.join() public String printArrayUsingJoin(String[] empArray) { return String.join("\n", empArray).trim(); } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\printarrays\PrintArrayJava.java
1
请完成以下Java代码
private static boolean isPossibleJdbcTimestamp(@NonNull final String s) { return s.length() == 21 && s.charAt(10) == ' '; } public static LocalDate fromObjectToLocalDate(final Object valueObj) { return fromObjectTo(valueObj, LocalDate.class, de.metas.util.converter.DateTimeConverters::fromJsonToLocalDate, TimeUtil::asLocalDate); } private static LocalTime fromObjectToLocalTime(final Object valueObj) { return fromObjectTo(valueObj, LocalTime.class, de.metas.util.converter.DateTimeConverters::fromJsonToLocalTime, TimeUtil::asLocalTime); } public static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj) { return fromObjectTo(valueObj, ZonedDateTime.class, de.metas.util.converter.DateTimeConverters::fromJsonToZonedDateTime, TimeUtil::asZonedDateTime); } public static Instant fromObjectToInstant(final Object valueObj) { return fromObjectTo(valueObj, Instant.class, de.metas.util.converter.DateTimeConverters::fromJsonToInstant, TimeUtil::asInstant); } @Nullable private static <T> T fromObjectTo( final Object valueObj, @NonNull final Class<T> type, @NonNull final Function<String, T> fromJsonConverer, @NonNull final Function<Object, T> fromObjectConverter) { if (valueObj == null || JSONNullValue.isNull(valueObj)) { return null;
} else if (type.isInstance(valueObj)) { return type.cast(valueObj); } else if (valueObj instanceof CharSequence) { final String json = valueObj.toString().trim(); if (json.isEmpty()) { return null; } if (isPossibleJdbcTimestamp(json)) { try { final Timestamp timestamp = fromPossibleJdbcTimestamp(json); return fromObjectConverter.apply(timestamp); } catch (final Exception e) { logger.warn("Error while converting possible JDBC Timestamp `{}` to java.sql.Timestamp", json, e); return fromJsonConverer.apply(json); } } else { return fromJsonConverer.apply(json); } } else if (valueObj instanceof StringLookupValue) { final String key = ((StringLookupValue)valueObj).getIdAsString(); if (Check.isEmpty(key)) { return null; } else { return fromJsonConverer.apply(key); } } else { return fromObjectConverter.apply(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\DateTimeConverters.java
1
请完成以下Java代码
private static class EventConverter { private static final String EVENTNAME = "DocumentPostRequest"; private static final String EVENT_PROPERTY_DocumentPostRequest = "DocumentPostRequest"; @NonNull private final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); @NonNull public DocumentPostRequest extractDocumentPostRequest(@NonNull final Event event) { final String requestStr = event.getProperty(EVENT_PROPERTY_DocumentPostRequest); return fromJson(requestStr); } @NonNull public Event createEventFromRequest(@NonNull final DocumentPostRequest request) { return Event.builder() .putProperty(EVENT_PROPERTY_DocumentPostRequest, toJsonString(request)) .setSourceRecordReference(request.getRecord()) .setEventName(EVENTNAME) .shallBeLogged() .build(); } @NonNull private String toJsonString(@NonNull final DocumentPostRequest request) { try { return jsonObjectMapper.writeValueAsString(request); } catch (Exception ex) { throw new AdempiereException("Failed converting to JSON: " + request, ex); } } @NonNull private DocumentPostRequest fromJson(@NonNull final String json) { try { return jsonObjectMapper.readValue(json, DocumentPostRequest.class); } catch (JsonProcessingException e) { throw new AdempiereException("Failed converting from JSON: " + json, e); } } }
// // // ------------------------------------------------------------------------- // // @lombok.Builder @lombok.ToString private static final class DocumentPostRequestHandlerAsEventListener implements IEventListener { @NonNull private final DocumentPostRequestHandler handler; @NonNull private final EventConverter eventConverter; @NonNull private final EventLogUserService eventLogUserService; @Override public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event) { final DocumentPostRequest request = eventConverter.extractDocumentPostRequest(event); try (final IAutoCloseable ignored = switchCtx(request); final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(request.getRecord()); final MDCCloseable ignored2 = MDC.putCloseable("eventHandler.className", handler.getClass().getName())) { eventLogUserService.invokeHandlerAndLog(InvokeHandlerAndLogRequest.builder() .handlerClass(handler.getClass()) .invokaction(() -> handleRequest(request)) .build()); } } private void handleRequest(@NonNull final DocumentPostRequest request) { handler.handleRequest(request); } private IAutoCloseable switchCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = createCtx(request); return Env.switchContext(ctx); } private Properties createCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, request.getClientId()); return ctx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingBusService.java
1
请完成以下Java代码
public InvoiceCandBLCreateInvoices setContext(final Properties ctx, final String trxName) { this._ctx = ctx; this._trxName = trxName; return this; } private Properties getCtx() { Check.assumeNotNull(_ctx, "_ctx not null"); return _ctx; } private String getTrxName() { return _trxName; } @Override public InvoiceCandBLCreateInvoices setIgnoreInvoiceSchedule(final boolean ignoreInvoiceSchedule) { this._ignoreInvoiceSchedule = ignoreInvoiceSchedule; return this; } private boolean isIgnoreInvoiceSchedule() { if (_ignoreInvoiceSchedule != null) { return _ignoreInvoiceSchedule; } final IInvoicingParams invoicingParams = getInvoicingParams(); if (invoicingParams != null) { return invoicingParams.isIgnoreInvoiceSchedule(); } return false; } @Override public InvoiceCandBLCreateInvoices setCollector(final IInvoiceGenerateResult collector) { this._collector = collector; return this;
} private IInvoiceGenerateResult getCollector() { if (_collector == null) { // note that we don't want to store the actual invoices in the result if there is a change to encounter memory problems _collector = invoiceCandBL.createInvoiceGenerateResult(_invoicingParams != null && _invoicingParams.isStoreInvoicesInResult()); } return _collector; } @Override public IInvoiceGenerator setInvoicingParams(final @NonNull IInvoicingParams invoicingParams) { this._invoicingParams = invoicingParams; return this; } private IInvoicingParams getInvoicingParams() { return _invoicingParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandBLCreateInvoices.java
1
请完成以下Java代码
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) { Map<String, Object> variablesMap = new HashMap<String, Object>(); // convert data objects to process variables if (dataObjects != null) { variablesMap = new HashMap<String, Object>(dataObjects.size()); for (ValuedDataObject dataObject : dataObjects) { variablesMap.put(dataObject.getName(), dataObject.getValue()); } } return variablesMap; } // Allow a subclass to override how variables are initialized. protected void initializeVariables(ExecutionEntity subProcessInstance, Map<String, Object> variables) { subProcessInstance.setVariables(variables); } protected Map<String, Object> calculateInboundVariables( DelegateExecution execution, ProcessDefinition processDefinition ) { return new HashMap<String, Object>(); } protected Map<String, Object> copyProcessVariables( DelegateExecution execution, ExpressionManager expressionManager, CallActivity callActivity, Map<String, Object> variables ) { for (IOParameter ioParameter : callActivity.getInParameters()) { Object value = null; if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) { Expression expression = expressionManager.createExpression(ioParameter.getSourceExpression().trim()); value = expression.getValue(execution);
} else { value = execution.getVariable(ioParameter.getSource()); } variables.put(ioParameter.getTarget(), value); } return variables; } protected DelegateExecution copyOutParameters(DelegateExecution execution, DelegateExecution subProcessInstance) { ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager(); ExecutionEntity executionEntity = (ExecutionEntity) execution; CallActivity callActivity = (CallActivity) executionEntity.getCurrentFlowElement(); for (IOParameter ioParameter : callActivity.getOutParameters()) { Object value = null; if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) { Expression expression = expressionManager.createExpression(ioParameter.getSourceExpression().trim()); value = expression.getValue(subProcessInstance); } else { value = subProcessInstance.getVariable(ioParameter.getSource()); } execution.setVariable(ioParameter.getTarget(), value); } return execution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\CallActivityBehavior.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(PriceCalculationApplication.class, args); } @Override public void run(String... args) throws Exception { List<String> params = Arrays.stream(args) .collect(Collectors.toList()); if (verifyArguments(params)) { double singlePrice = Double.valueOf(params.get(0)); int quantity = Integer.valueOf(params.get(1)); priceCalculationService.productTotalPrice(singlePrice, quantity); } else { logger.warn("Invalid arguments " + params.toString()); } }
private boolean verifyArguments(List<String> args) { boolean successful = true; if (args.size() != 2) { successful = false; return successful; } try { double singlePrice = Double.valueOf(args.get(0)); int quantity = Integer.valueOf(args.get(1)); } catch (NumberFormatException e) { successful = false; } return successful; } }
repos\tutorials-master\spring-boot-modules\spring-boot-environment\src\main\java\com\baeldung\environmentpostprocessor\PriceCalculationApplication.java
1
请完成以下Java代码
public boolean isTransient(DbEntity dbEntity) { CachedDbEntity cachedDbEntity = getCachedEntity(dbEntity); if(cachedDbEntity == null) { return false; } else { return cachedDbEntity.getEntityState() == TRANSIENT; } } public List<CachedDbEntity> getCachedEntities() { List<CachedDbEntity> result = new ArrayList<CachedDbEntity>(); for (Map<String, CachedDbEntity> typeCache : cachedEntites.values()) { result.addAll(typeCache.values()); } return result; } /** * Sets an object to a deleted state. It will not be removed from the cache but * transition to one of the DELETED states, depending on it's current state. * * @param dbEntity the object to mark deleted. */ public void setDeleted(DbEntity dbEntity) { CachedDbEntity cachedEntity = getCachedEntity(dbEntity); if(cachedEntity != null) { if(cachedEntity.getEntityState() == TRANSIENT) { cachedEntity.setEntityState(DELETED_TRANSIENT);
} else if(cachedEntity.getEntityState() == PERSISTENT){ cachedEntity.setEntityState(DELETED_PERSISTENT); } else if(cachedEntity.getEntityState() == MERGED){ cachedEntity.setEntityState(DELETED_MERGED); } } else { // put a deleted merged into the cache CachedDbEntity cachedDbEntity = new CachedDbEntity(); cachedDbEntity.setEntity(dbEntity); cachedDbEntity.setEntityState(DELETED_MERGED); putInternal(cachedDbEntity); } } public void undoDelete(DbEntity dbEntity) { CachedDbEntity cachedEntity = getCachedEntity(dbEntity); if (cachedEntity.getEntityState() == DbEntityState.DELETED_TRANSIENT) { cachedEntity.setEntityState(DbEntityState.TRANSIENT); } else { cachedEntity.setEntityState(DbEntityState.MERGED); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\cache\DbEntityCache.java
1
请完成以下Java代码
public IAllocationResult load(final IAllocationRequest request) { if (request.getQty().signum() == 0) { return AllocationUtils.nullResult(); } final IAllocationRequest requestActual = storage.addQty(request); // // Create Allocation result final boolean outTrx = false; final IAllocationResult result = createAllocationResult(request, requestActual, outTrx); // // Return the result return result; } @Override public IAllocationResult unload(final IAllocationRequest request) { final IAllocationRequest requestActual = storage.removeQty(request); final boolean outTrx = true; return createAllocationResult(request, requestActual, outTrx); } private IAllocationResult createAllocationResult( final IAllocationRequest request, final IAllocationRequest requestActual, final boolean outTrx) { final IHUTransactionCandidate trx = createHUTransaction(requestActual, outTrx); return AllocationUtils.createQtyAllocationResult( request.getQty(), // qtyToAllocate requestActual.getQty(), // qtyAllocated Arrays.asList(trx), // trxs Collections.<IHUTransactionAttribute> emptyList() // attributeTrxs ); } private IHUTransactionCandidate createHUTransaction(final IAllocationRequest request, final boolean outTrx) { final HUTransactionCandidate trx = new HUTransactionCandidate(getReferenceModel(), getM_HU_Item(), getVHU_Item(), request, outTrx); return trx; } public IProductStorage getStorage() { return storage; }
private I_M_HU_Item getM_HU_Item() { return huItem; } private I_M_HU_Item getVHU_Item() { // TODO: implement: get VHU Item or create it return huItem; } public Object getReferenceModel() { return referenceModel; } @Override public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { final IAllocationRequest request = AllocationUtils.createQtyRequest(huContext, storage.getProductId(), // product storage.getQty(), // qty huContext.getDate() // date ); final IAllocationResult result = unload(request); return Collections.singletonList(ImmutablePair.of(request, result)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractAllocationSourceDestination.java
1
请完成以下Java代码
public class HttpClient { private final String user; private final String password; public HttpClient(String user, String password) { this.user = user; this.password = password; } public int sendRequestWithAuthHeader(String url) throws IOException { HttpURLConnection connection = null; try { connection = createConnection(url); connection.setRequestProperty("Authorization", createBasicAuthHeaderValue()); return connection.getResponseCode(); } catch (URISyntaxException e) { throw new IOException(e); } finally { if (connection != null) { connection.disconnect(); } } } public int sendRequestWithAuthenticator(String url) throws IOException, URISyntaxException { setAuthenticator(); HttpURLConnection connection = null; try { connection = createConnection(url);
return connection.getResponseCode(); } finally { if (connection != null) { connection.disconnect(); } } } private HttpURLConnection createConnection(String urlString) throws MalformedURLException, IOException, URISyntaxException { URL url = new URI(String.format(urlString)).toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); return connection; } private String createBasicAuthHeaderValue() { String auth = user + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8)); String authHeaderValue = "Basic " + new String(encodedAuth); return authHeaderValue; } private void setAuthenticator() { Authenticator.setDefault(new BasicAuthenticator()); } private final class BasicAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password.toCharArray()); } } }
repos\tutorials-master\core-java-modules\core-java-networking-2\src\main\java\com\baeldung\url\auth\HttpClient.java
1
请在Spring Boot框架中完成以下Java代码
public void setC_POS_Payment_ID (final int C_POS_Payment_ID) { if (C_POS_Payment_ID < 1) set_Value (COLUMNNAME_C_POS_Payment_ID, null); else set_Value (COLUMNNAME_C_POS_Payment_ID, C_POS_Payment_ID); } @Override public int getC_POS_Payment_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); }
/** * Type AD_Reference_ID=541892 * Reference name: C_POS_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=541892; /** CashPayment = CASH_PAY */ public static final String TYPE_CashPayment = "CASH_PAY"; /** CardPayment = CARD_PAY */ public static final String TYPE_CardPayment = "CARD_PAY"; /** CashInOut = CASH_INOUT */ public static final String TYPE_CashInOut = "CASH_INOUT"; /** CashClosingDifference = CASH_DIFF */ public static final String TYPE_CashClosingDifference = "CASH_DIFF"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java
2
请完成以下Java代码
public int getPP_Product_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quality Specification. @param QM_Specification_ID Quality Specification */ public void setQM_Specification_ID (int QM_Specification_ID) { if (QM_Specification_ID < 1) set_ValueNoCheck (COLUMNNAME_QM_Specification_ID, null); else set_ValueNoCheck (COLUMNNAME_QM_Specification_ID, Integer.valueOf(QM_Specification_ID)); } /** Get Quality Specification. @return Quality Specification */ public int getQM_Specification_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_QM_Specification_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to.
@return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_QM_Specification.java
1
请完成以下Java代码
public <T extends Spin<?>> T createSpinFromSpin(T parameter) { ensureNotNull("parameter", parameter); return parameter; } public <T extends Spin<?>> T createSpinFromString(String parameter) { ensureNotNull("parameter", parameter); Reader input = SpinIoUtil.stringAsReader(parameter); return createSpin(input); } @SuppressWarnings("unchecked") public <T extends Spin<?>> T createSpinFromReader(Reader parameter) { ensureNotNull("parameter", parameter); RewindableReader rewindableReader = new RewindableReader(parameter, READ_SIZE); DataFormat<T> matchingDataFormat = null; for (DataFormat<?> format : DataFormats.getAvailableDataFormats()) { if (format.getReader().canRead(rewindableReader, rewindableReader.getRewindBufferSize())) { matchingDataFormat = (DataFormat<T>) format; } try { rewindableReader.rewind(); } catch (IOException e) { throw LOG.unableToReadFromReader(e); } } if (matchingDataFormat == null) { throw LOG.unrecognizableDataFormatException(); } return createSpin(rewindableReader, matchingDataFormat);
} /** * * @throws SpinDataFormatException in case the parameter cannot be read using this data format * @throws IllegalArgumentException in case the parameter is null or dd: */ public <T extends Spin<?>> T createSpinFromSpin(T parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); return parameter; } public <T extends Spin<?>> T createSpinFromString(String parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); Reader input = SpinIoUtil.stringAsReader(parameter); return createSpin(input, format); } public <T extends Spin<?>> T createSpinFromReader(Reader parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); DataFormatReader reader = format.getReader(); Object dataFormatInput = reader.readInput(parameter); return format.createWrapperInstance(dataFormatInput); } public <T extends Spin<?>> T createSpinFromObject(Object parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); DataFormatMapper mapper = format.getMapper(); Object dataFormatInput = mapper.mapJavaToInternal(parameter); return format.createWrapperInstance(dataFormatInput); } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\SpinFactoryImpl.java
1
请完成以下Java代码
public void setPrescriptionType (final @Nullable java.lang.String PrescriptionType) { set_Value (COLUMNNAME_PrescriptionType, PrescriptionType); } @Override public java.lang.String getPrescriptionType() { return get_ValueAsString(COLUMNNAME_PrescriptionType); } @Override public void setStartDate (final @Nullable java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } @Override public java.sql.Timestamp getStartDate() {
return get_ValueAsTimestamp(COLUMNNAME_StartDate); } @Override public void setTherapyTypeIds (final @Nullable java.lang.String TherapyTypeIds) { set_Value (COLUMNNAME_TherapyTypeIds, TherapyTypeIds); } @Override public java.lang.String getTherapyTypeIds() { return get_ValueAsString(COLUMNNAME_TherapyTypeIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_PrescriptionRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentRepository { private JdbcTemplate jdbcTemplate; private PlatformTransactionManager transactionManager; public PaymentRepository( JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager ) { this.jdbcTemplate = jdbcTemplate; this.transactionManager = transactionManager; } public void processPayment(long paymentId, long amount) { TransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus status =
transactionManager.getTransaction(definition); jdbcTemplate.update( "insert into payments(id, amount) values (?, ?)", paymentId, amount ); jdbcTemplate.update( "update accounts set balance = balance - ? where id = 1", amount ); transactionManager.commit(status); } }
repos\tutorials-master\spring-boot-modules\spring-boot-jdbc\src\main\java\com\baeldung\repository\PaymentRepository.java
2
请完成以下Java代码
private final JButton getArrowButton() { final ComboBoxUI ui = getUI(); if (ui instanceof org.adempiere.plaf.AdempiereComboBoxUI) { final JButton b = ((org.adempiere.plaf.AdempiereComboBoxUI)ui).getArrowButton(); return b; } return null; } /** * Add Mouse Listener - 1-4-0 Bug. * Bug in 1.4.0 Metal: arrowButton gets Mouse Events, so add the JComboBox * MouseListeners to the arrowButton - No context menu if right-click * @see AdempiereComboBoxUI#installUI(JComponent) * @param ml */ @Override public void addMouseListener (MouseListener ml) { super.addMouseListener(ml); final JButton arrowButton = getArrowButton(); if (arrowButton != null && !Trace.getCallerClass(1).startsWith("javax")) { arrowButton.addMouseListener(ml); } } /** * Remove Mouse Listener. * @param ml */ @Override public void removeMouseListener (MouseListener ml) { super.removeMouseListener(ml); final JButton arrowButton = getArrowButton(); if (arrowButton != null) { arrowButton.removeMouseListener(ml); } } // removeMouseListener /** * Set Action Command * @param actionCommand command */ @Override public void setActionCommand (String actionCommand) { super.setActionCommand (actionCommand); if (getName() == null && actionCommand != null && actionCommand.length() > 0) setName(actionCommand);
} // setActionCommand public boolean isSelectionNone() { final Object selectedItem = getSelectedItem(); if (selectedItem == null) { return true; } else { return Check.isEmpty(selectedItem.toString(), true); } } @Override public E getSelectedItem() { final Object selectedItemObj = super.getSelectedItem(); @SuppressWarnings("unchecked") final E selectedItem = (E)selectedItemObj; return selectedItem; } /** * Enables auto completion (while user writes) on this combobox. * * @return combobox's auto-completion instance for further configurations */ public final ComboBoxAutoCompletion<E> enableAutoCompletion() { return ComboBoxAutoCompletion.enable(this); } /** * Disable autocompletion on this combobox. * * If the autocompletion was not enabled, this method does nothing. */ public final void disableAutoCompletion() { ComboBoxAutoCompletion.disable(this); } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return JComboBoxCopyPasteSupportEditor.ofComponent(this); } } // CComboBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CComboBox.java
1
请完成以下Java代码
protected static Map<String, String> resolveModels(String sourceDirectory) { File modelsDir = new File(sourceDirectory + "/models"); Collection<File> modelFiles = FileUtils.listFiles( modelsDir, new RegexFileFilter("^(.*?)"), DirectoryFileFilter.DIRECTORY ); Map<String, String> models = new TreeMap<>(); for (File file : modelFiles) { String modelName = FilenameUtils.removeExtension(file.getName()); String filePath = file.getAbsolutePath(); String modelPackage = filePath .substring(filePath.lastIndexOf("org"), filePath.lastIndexOf(File.separator)); models.put(modelName, modelPackage); } return models; } /** * * @param sourceDirectory the template directory that stores the endpoints * @return a map of endpoint path and HTTP methods pairs, * the map is ordered lexicographically by the endpoint paths * the list of methods is ordered as well */ protected static Map<String, List<String>> resolvePaths(String sourceDirectory) { File endpointsDir = new File(sourceDirectory + "/paths"); int endpointStartAt = endpointsDir.getAbsolutePath().length(); Collection<File> endpointsFiles = FileUtils.listFiles( endpointsDir, new RegexFileFilter("^(.*?)"), DirectoryFileFilter.DIRECTORY
); Map<String, List<String>> endpoints = new TreeMap<>(); for (File file : endpointsFiles) { String endpointMethod = FilenameUtils.removeExtension(file.getName()); String filePath = file.getAbsolutePath(); String endpointPath = filePath .substring(endpointStartAt, filePath.lastIndexOf(File.separator)) .replace(File.separator, "/"); List<String> operations; if (endpoints.containsKey(endpointPath)) { operations = endpoints.get(endpointPath); operations.add(endpointMethod); } else { operations = new ArrayList<>(); operations.add(endpointMethod); endpoints.put(endpointPath, operations); } if(operations.size() > 1) { Collections.sort(operations); } } return endpoints; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest-openapi-generator\src\main\java\org\camunda\bpm\engine\rest\openapi\generator\impl\TemplateParser.java
1
请完成以下Java代码
protected void setJsonConverter(HttpMessageConverter<Object> converter) { this.jsonConverter = converter; } /** * Build the default transport-agnostic client that subclasses can then wrap * with {@link AbstractDelegatingGraphQlClient}. * @param transport the GraphQL transport to be used by the client */ protected GraphQlClient buildGraphQlClient(SyncGraphQlTransport transport) { if (jacksonPresent) { this.jsonConverter = (this.jsonConverter == null) ? DefaultJacksonConverter.initialize() : this.jsonConverter; } else if (jackson2Present) { this.jsonConverter = (this.jsonConverter == null) ? DefaultJackson2Converter.initialize() : this.jsonConverter; } return new DefaultGraphQlClient( this.documentSource, createExecuteChain(transport), this.scheduler, this.blockingTimeout); } /** * Return a {@code Consumer} to initialize new builders from "this" builder. */ protected Consumer<AbstractGraphQlClientSyncBuilder<?>> getBuilderInitializer() { return (builder) -> { builder.interceptors((interceptorList) -> interceptorList.addAll(this.interceptors)); builder.documentSource(this.documentSource); builder.setJsonConverter(getJsonConverter()); }; } private Chain createExecuteChain(SyncGraphQlTransport transport) { Encoder<?> encoder = HttpMessageConverterDelegate.asEncoder(getJsonConverter()); Decoder<?> decoder = HttpMessageConverterDelegate.asDecoder(getJsonConverter()); Chain chain = (request) -> { GraphQlResponse response = transport.execute(request); return new DefaultClientGraphQlResponse(request, response, encoder, decoder); }; return this.interceptors.stream() .reduce(SyncGraphQlClientInterceptor::andThen) .map((i) -> (Chain) (request) -> i.intercept(request, chain))
.orElse(chain); } private HttpMessageConverter<Object> getJsonConverter() { Assert.notNull(this.jsonConverter, "jsonConverter has not been set"); return this.jsonConverter; } private static final class DefaultJacksonConverter { static HttpMessageConverter<Object> initialize() { JsonMapper jsonMapper = JsonMapper.builder().addModule(new GraphQlJacksonModule()).build(); return new JacksonJsonHttpMessageConverter(jsonMapper); } } @SuppressWarnings("removal") private static final class DefaultJackson2Converter { static HttpMessageConverter<Object> initialize() { com.fasterxml.jackson.databind.ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .modulesToInstall(new GraphQlJackson2Module()).build(); return new MappingJackson2HttpMessageConverter(objectMapper); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientSyncBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public List<AppDeployment> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this); } // getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getKey() { return key; }
public boolean isLatest() { return latest; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
2
请完成以下Java代码
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) { this.securityContextHolderStrategy = () -> strategy; } /** * Filter the method argument specified in the {@link PreFilter} annotation that * {@link MethodInvocation} specifies. * @param mi the {@link MethodInvocation} to check */ @Override public @Nullable Object invoke(MethodInvocation mi) throws Throwable { PreFilterExpressionAttributeRegistry.PreFilterExpressionAttribute attribute = this.registry.getAttribute(mi); if (attribute == null) { return mi.proceed(); } MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler(); EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi); Object filterTarget = findFilterTarget(attribute.getFilterTarget(), ctx, mi); expressionHandler.filter(filterTarget, attribute.getExpression(), ctx); return mi.proceed(); } private Object findFilterTarget(String filterTargetName, EvaluationContext ctx, MethodInvocation methodInvocation) { Object filterTarget; if (StringUtils.hasText(filterTargetName)) { filterTarget = ctx.lookupVariable(filterTargetName); Assert.notNull(filterTarget, () -> "Filter target was null, or no argument with name '" + filterTargetName + "' found in method."); } else { Object[] arguments = methodInvocation.getArguments(); Assert.state(arguments.length == 1, "Unable to determine the method argument for filtering. Specify the filter target."); filterTarget = arguments[0]; Assert.notNull(filterTarget,
"Filter target was null. Make sure you passing the correct value in the method argument."); } Assert.state(!filterTarget.getClass().isArray(), "Pre-filtering on array types is not supported. Using a Collection will solve this problem."); return filterTarget; } private Authentication getAuthentication() { Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreFilterAuthorizationMethodInterceptor.java
1
请完成以下Java代码
public class SuperPublic { // Always available from anywhere static public void publicMethod() { System.out.println(SuperPublic.class.getName() + " publicMethod()"); } // Available within the same package static void defaultMethod() { System.out.println(SuperPublic.class.getName() + " defaultMethod()"); } // Available within the same package and subclasses static protected void protectedMethod() { System.out.println(SuperPublic.class.getName() + " protectedMethod()"); } // Available within the same class only static private void privateMethod() { System.out.println(SuperPublic.class.getName() + " privateMethod()"); }
// Method in the same class = has access to all members within the same class private void anotherPrivateMethod() { privateMethod(); defaultMethod(); protectedMethod(); publicMethod(); // Available in the same class only. } } // Only public or default access modifiers are permitted class SuperDefault { public void publicMethod() { System.out.println(this.getClass().getName() + " publicMethod()"); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\accessmodifiers\SuperPublic.java
1
请完成以下Java代码
public void setIsCreateBPartnerFolders (final boolean IsCreateBPartnerFolders) { set_Value (COLUMNNAME_IsCreateBPartnerFolders, IsCreateBPartnerFolders); } @Override public boolean isCreateBPartnerFolders() { return get_ValueAsBoolean(COLUMNNAME_IsCreateBPartnerFolders); } @Override public void setIsSyncBPartnersToRestEndpoint (final boolean IsSyncBPartnersToRestEndpoint) { set_Value (COLUMNNAME_IsSyncBPartnersToRestEndpoint, IsSyncBPartnersToRestEndpoint); } @Override public boolean isSyncBPartnersToRestEndpoint() { return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRestEndpoint); } @Override public void setIsSyncHUsOnMaterialReceipt (final boolean IsSyncHUsOnMaterialReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnMaterialReceipt, IsSyncHUsOnMaterialReceipt); } @Override public boolean isSyncHUsOnMaterialReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnMaterialReceipt); } @Override public void setIsSyncHUsOnProductionReceipt (final boolean IsSyncHUsOnProductionReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnProductionReceipt, IsSyncHUsOnProductionReceipt);
} @Override public boolean isSyncHUsOnProductionReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnProductionReceipt); } /** * TenantId AD_Reference_ID=276 * Reference name: AD_Org (all) */ public static final int TENANTID_AD_Reference_ID=276; @Override public void setTenantId (final java.lang.String TenantId) { set_Value (COLUMNNAME_TenantId, TenantId); } @Override public java.lang.String getTenantId() { return get_ValueAsString(COLUMNNAME_TenantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_GRSSignum.java
1
请完成以下Java代码
public class MapClear { public static Map returnCopyAndClearMap() { // Create a HashMap Map<String, Integer> scores = new HashMap<>(); Map<String, Integer> scores_copy; // Add some key-value pairs scores.put("Alice", 90); scores.put("Bob", 85); scores.put("Charlie", 95); scores_copy = scores; System.out.println("Before clearing: " + scores); // Clear the map scores.clear(); System.out.println("After clearing: " + scores); return scores_copy; }
public static Map returnCopyAndRewriteMap() { // Create a HashMap Map<String, Integer> scores = new HashMap<>(); Map<String, Integer> scores_copy; // Add some key-value pairs scores.put("Alice", 90); scores.put("Bob", 85); scores.put("Charlie", 95); scores_copy = scores; System.out.println("Before clearing: " + scores); // Create a new map scores = new HashMap<>(); System.out.println("After clearing: " + scores); return scores_copy; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\MapClear.java
1
请完成以下Java代码
public String toString () { StringBuffer sb = new StringBuffer ("MInterestArea[") .append (get_ID()).append(" - ").append(getName()) .append ("]"); return sb.toString (); } // toString /*************************************************************************/ private int m_AD_User_ID = -1; private MContactInterest m_ci = null; /** * Set Subscription info "constructor". * Create inactive Subscription * @param AD_User_ID contact */ public void setSubscriptionInfo (int AD_User_ID) { m_AD_User_ID = AD_User_ID; m_ci = MContactInterest.get(getCtx(), getR_InterestArea_ID(), AD_User_ID, false, get_TrxName()); } // setSubscription /** * Set AD_User_ID * @param AD_User_ID user */ public void setAD_User_ID (int AD_User_ID) { m_AD_User_ID = AD_User_ID; } /** * Get AD_User_ID * @return user */ public int getAD_User_ID () { return m_AD_User_ID; } /** * Get Subscribe Date * @return subscribe date */ public Timestamp getSubscribeDate () { if (m_ci != null) return m_ci.getSubscribeDate(); return null; }
/** * Get Opt Out Date * @return opt-out date */ public Timestamp getOptOutDate () { if (m_ci != null) return m_ci.getOptOutDate(); return null; } /** * Is Subscribed * @return true if sunscribed */ public boolean isSubscribed() { if (m_AD_User_ID <= 0 || m_ci == null) return false; // We have a BPartner Contact return m_ci.isSubscribed(); } // isSubscribed } // MInterestArea
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInterestArea.java
1