instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults()); http.formLogin(withDefaults()); } SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard {
static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请完成以下Java代码
public V get(K key) { V value = cache.get(key); if (value != null) { keys.remove(key); keys.add(key); } return value; } @Override public void put(K key, V value) { if (key == null || value == null) { throw new NullPointerException(); } V previousValue = cache.put(key, value); if (previousValue != null) { keys.remove(key); } keys.add(key); if (cache.size() > capacity) { K lruKey = keys.poll(); if (lruKey != null) { cache.remove(lruKey); // remove duplicated keys this.removeAll(lruKey); // queue may not contain any key of a possibly concurrently added entry of the same key in the cache if (cache.containsKey(lruKey)) { keys.add(lruKey); } } } } @Override public void remove(K key) { this.cache.remove(key); keys.remove(key); } @Override public void clear() { cache.clear(); keys.clear(); }
@Override public boolean isEmpty() { return cache.isEmpty(); } @Override public Set<K> keySet() { return cache.keySet(); } @Override public int size() { return cache.size(); } /** * Removes all instances of the given key within the keys queue. */ protected void removeAll(K key) { while (keys.remove(key)) { } } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\cache\ConcurrentLruCache.java
1
请在Spring Boot框架中完成以下Java代码
public SslCertificateAliasProperties getAlias() { return this.alias; } } public static class SslCertificateAliasProperties { private String all; private String cluster; private String defaultAlias; private String gateway; private String jmx; private String locator; private String server; private String web; public String getAll() { return this.all; } public void setAll(String all) { this.all = all; } public String getCluster() { return this.cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public String getDefaultAlias() { return this.defaultAlias; } public void setDefaultAlias(String defaultAlias) { this.defaultAlias = defaultAlias; } public String getGateway() { return this.gateway;
} public void setGateway(String gateway) { this.gateway = gateway; } public String getJmx() { return this.jmx; } public void setJmx(String jmx) { this.jmx = jmx; } public String getLocator() { return this.locator; } public void setLocator(String locator) { this.locator = locator; } public String getServer() { return this.server; } public void setServer(String server) { this.server = server; } public String getWeb() { return this.web; } public void setWeb(String web) { this.web = web; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java
2
请完成以下Java代码
public static int modSubtract(int a, int b) { return mod(minSymmetricMod(a) - minSymmetricMod(b)); } public static int modMultiply(int a, int b) { int result = minSymmetricMod((long) minSymmetricMod(a) * (long) minSymmetricMod(b)); return mod(result); } public static int modPower(int base, int exp) { int result = 1; int b = base; while (exp > 0) { if ((exp & 1) == 1) { result = minSymmetricMod((long) minSymmetricMod(result) * (long) minSymmetricMod(b)); } b = minSymmetricMod((long) minSymmetricMod(b) * (long) minSymmetricMod(b)); exp >>= 1; } return mod(result); } private static int[] extendedGcd(int a, int b) {
if (b == 0) { return new int[] { a, 1, 0 }; } int[] result = extendedGcd(b, a % b); int gcd = result[0]; int x = result[2]; int y = result[1] - (a / b) * result[2]; return new int[] { gcd, x, y }; } public static int modInverse(int a) { int[] result = extendedGcd(a, MOD); int x = result[1]; return mod(x); } public static int modDivide(int a, int b) { return modMultiply(minSymmetricMod(a), minSymmetricMod(modInverse(b))); } }
repos\tutorials-master\core-java-modules\core-java-lang-math-4\src\main\java\com\baeldung\math\moduloarithmetic\ModularArithmetic.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchPO.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserRepository repository; @Autowired private UserValidationService validationService; @GetMapping("/add") public String showAddUserForm(User user) { return "errors/addUser"; } @PostMapping("/add") public String addUser(@Valid User user, BindingResult result, Model model) { String err = validationService.validateUser(user);
if (!err.isEmpty()) { ObjectError error = new ObjectError("globalError", err); result.addError(error); } if (result.hasErrors()) { return "errors/addUser"; } repository.save(user); model.addAttribute("users", repository.findAll()); return "errors/home"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\errors\UserController.java
2
请完成以下Java代码
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createBatchUpdateEvent(batch); } }); } } protected void configureQuery(HistoricBatchQueryImpl query) { getAuthorizationManager().configureHistoricBatchQuery(query); getTenantManager().configureQuery(query); } @SuppressWarnings("unchecked") public List<CleanableHistoricBatchReportResult> findCleanableHistoricBatchesReportByCriteria(CleanableHistoricBatchReportImpl query, Page page, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); query.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TYPE_"), Direction.ASCENDING)); if (batchOperationsForHistoryCleanup.isEmpty()) { return getDbEntityManager().selectList("selectOnlyFinishedBatchesReportEntities", query, page); } else { return getDbEntityManager().selectList("selectFinishedBatchesReportEntities", query, page); } } public long findCleanableHistoricBatchesReportCountByCriteria(CleanableHistoricBatchReportImpl query, Map<String, Integer> batchOperationsForHistoryCleanup) { query.setCurrentTimestamp(ClockUtil.getCurrentTime()); query.setParameter(batchOperationsForHistoryCleanup); if (batchOperationsForHistoryCleanup.isEmpty()) { return (Long) getDbEntityManager().selectOne("selectOnlyFinishedBatchesReportEntitiesCount", query); } else { return (Long) getDbEntityManager().selectOne("selectFinishedBatchesReportEntitiesCount", query); } } public DbOperation deleteHistoricBatchesByRemovalTime(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(HistoricBatchEntity.class, "deleteHistoricBatchesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } public void addRemovalTimeById(String id, Date removalTime) { CommandContext commandContext = Context.getCommandContext(); commandContext.getHistoricIncidentManager() .addRemovalTimeToHistoricIncidentsByBatchId(id, removalTime); commandContext.getHistoricJobLogManager() .addRemovalTimeToJobLogByBatchId(id, removalTime); Map<String, Object> parameters = new HashMap<>(); parameters.put("id", id); parameters.put("removalTime", removalTime); getDbEntityManager() .updatePreserveOrder(HistoricBatchEntity.class, "updateHistoricBatchRemovalTimeById", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricBatchManager.java
1
请完成以下Java代码
public class OrderService { @Autowired private OrderRepository orderRepository; @Autowired private OrderProducer orderProducer; public Mono<Order> createOrder(Order order) { log.info("Create order invoked with: {}", order); return Mono.just(order) .map(o -> { return o.setLineItems(o.getLineItems() .stream() .filter(l -> l.getQuantity() > 0) .collect(Collectors.toList())); }) .flatMap(orderRepository::save) .map(o -> {
orderProducer.sendMessage(o.setOrderStatus(OrderStatus.INITIATION_SUCCESS)); return o; }) .onErrorResume(err -> { return Mono.just(order.setOrderStatus(OrderStatus.FAILURE) .setResponseMessage(err.getMessage())); }) .flatMap(orderRepository::save); } public Flux<Order> getOrders() { log.info("Get all orders invoked."); return orderRepository.findAll(); } }
repos\tutorials-master\reactive-systems\order-service\src\main\java\com\baeldung\reactive\service\OrderService.java
1
请在Spring Boot框架中完成以下Java代码
public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } public StatsdProtocol getProtocol() { return this.protocol; } public void setProtocol(StatsdProtocol protocol) { this.protocol = protocol; } public Integer getMaxPacketLength() { return this.maxPacketLength; } public void setMaxPacketLength(Integer maxPacketLength) { this.maxPacketLength = maxPacketLength; } public Duration getPollingFrequency() { return this.pollingFrequency; } public void setPollingFrequency(Duration pollingFrequency) { this.pollingFrequency = pollingFrequency; }
public Duration getStep() { return this.step; } public void setStep(Duration step) { this.step = step; } public boolean isPublishUnchangedMeters() { return this.publishUnchangedMeters; } public void setPublishUnchangedMeters(boolean publishUnchangedMeters) { this.publishUnchangedMeters = publishUnchangedMeters; } public boolean isBuffered() { return this.buffered; } public void setBuffered(boolean buffered) { this.buffered = buffered; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class PurchaseCandidateAdvisedEvent implements MaterialEvent { public static final String TYPE = "PurchaseCandidateAdvisedEvent"; EventDescriptor eventDescriptor; SupplyRequiredDescriptor supplyRequiredDescriptor; int productPlanningId; boolean directlyCreatePurchaseCandidate; int vendorId; @Builder @JsonCreator private PurchaseCandidateAdvisedEvent( @JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor, @JsonProperty("supplyRequiredDescriptor") @NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor, @JsonProperty("productPlanningId") final int productPlanningId, @JsonProperty("directlyCreatePurchaseCandidate") final boolean directlyCreatePurchaseCandidate,
@JsonProperty("vendorId") final int vendorId) { this.eventDescriptor = eventDescriptor; this.supplyRequiredDescriptor = supplyRequiredDescriptor; this.productPlanningId = Check.assumeGreaterThanZero(productPlanningId, "productPlanningId"); this.vendorId = vendorId; this.directlyCreatePurchaseCandidate = directlyCreatePurchaseCandidate; } @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.of(MD_CANDIDATE_TABLE_NAME, supplyRequiredDescriptor.getDemandCandidateId()); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\purchase\PurchaseCandidateAdvisedEvent.java
2
请完成以下Java代码
public void setExecution(ExecutionEntity execution) { super.setExecution(execution); execution.addJob(this); } @Override @SuppressWarnings("unchecked") public Object getPersistentState() { Map<String, Object> persistentState = (Map<String, Object>) super.getPersistentState(); persistentState.put("lockOwner", lockOwner); persistentState.put("lockExpirationTime", lockExpirationTime); return persistentState; } public String getLockOwner() { return lockOwner; }
public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } @Override public String toString() { return "JobEntity [id=" + id + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntity.java
1
请完成以下Java代码
public class DDOrderCandidateAllocList implements Iterable<DDOrderCandidateAlloc> { public static final DDOrderCandidateAllocList EMPTY = new DDOrderCandidateAllocList(ImmutableList.of()); @NonNull private final ImmutableList<DDOrderCandidateAlloc> list; private DDOrderCandidateAllocList(@NonNull final Collection<DDOrderCandidateAlloc> list) { this.list = ImmutableList.copyOf(list); } public static DDOrderCandidateAllocList of(@NonNull final Collection<DDOrderCandidateAlloc> list) { return list.isEmpty() ? EMPTY : new DDOrderCandidateAllocList(list); } public static Collector<DDOrderCandidateAlloc, ?, DDOrderCandidateAllocList> collect() { return GuavaCollectors.collectUsingListAccumulator(DDOrderCandidateAllocList::of); } public boolean isEmpty() {return list.isEmpty();} public Set<DDOrderCandidateId> getDDOrderCandidateIds() { return list.stream() .map(DDOrderCandidateAlloc::getDdOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } public Set<DDOrderId> getDDOrderIds() { return list.stream().map(DDOrderCandidateAlloc::getDdOrderId).collect(ImmutableSet.toImmutableSet()); } public Set<DDOrderLineId> getDDOrderLineIds() { return list.stream().map(DDOrderCandidateAlloc::getDdOrderLineId).collect(ImmutableSet.toImmutableSet()); } @Override @NonNull public Iterator<DDOrderCandidateAlloc> iterator() {
return list.iterator(); } public Map<DDOrderCandidateId, DDOrderCandidateAllocList> groupByCandidateId() { if (list.isEmpty()) { return ImmutableMap.of(); } return list.stream().collect(Collectors.groupingBy(DDOrderCandidateAlloc::getDdOrderCandidateId, collect())); } public Optional<Quantity> getQtySum() { return list.stream() .map(DDOrderCandidateAlloc::getQty) .reduce(Quantity::add); } public Set<Integer> getIds() { if (list.isEmpty()) { return ImmutableSet.of(); } return list.stream() .map(DDOrderCandidateAlloc::getId) .filter(id -> id > 0) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidateAllocList.java
1
请完成以下Spring Boot application配置
spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=create spring.jpa.defer-datasource-initialization=
true # Enabling H2 Console spring.h2.console.enabled=true # By default enabled for Embedded Databases #spring.sql.init.mode=always
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\resources\application-datasource.properties
2
请完成以下Java代码
public void onAfterSave_WhenNameOrColumnChanged(final I_AD_Field field) { updateTranslationsForElement(field); recreateElementLinkForField(field); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = { I_AD_Field.COLUMNNAME_AD_Name_ID, I_AD_Field.COLUMNNAME_AD_Column_ID }) public void onBeforeSave_WhenNameOrColumnChanged(final I_AD_Field field) { updateFieldFromElement(field); } private void updateFieldFromElement(final I_AD_Field field) { final AdElementId fieldElementId = getFieldElementIdOrNull(field); if (fieldElementId == null) { // Nothing to do. the element was not yet saved. return; } final I_AD_Element fieldElement = Services.get(IADElementDAO.class).getById(fieldElementId.getRepoId()); field.setName(fieldElement.getName()); field.setDescription(fieldElement.getDescription()); field.setHelp(fieldElement.getHelp()); } private void updateTranslationsForElement(final I_AD_Field field) { final AdElementId fieldElementId = getFieldElementIdOrNull(field); if (fieldElementId == null) { // Nothing to do. the element was not yet saved. return; } final IElementTranslationBL elementTranslationBL = Services.get(IElementTranslationBL.class); elementTranslationBL.updateFieldTranslationsFromAD_Name(fieldElementId); } private AdElementId getFieldElementIdOrNull(final I_AD_Field field) { if (field.getAD_Name_ID() > 0) { return AdElementId.ofRepoId(field.getAD_Name_ID()); } else if (field.getAD_Column_ID() > 0) { // the AD_Name_ID was set to null. Get back to the values from the AD_Column final I_AD_Column fieldColumn = field.getAD_Column();
return AdElementId.ofRepoId(fieldColumn.getAD_Element_ID()); } else { // Nothing to do. the element was not yet saved. return null; } } private void recreateElementLinkForField(final I_AD_Field field) { final AdFieldId adFieldId = AdFieldId.ofRepoIdOrNull(field.getAD_Field_ID()); if (adFieldId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.recreateADElementLinkForFieldId(adFieldId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeFieldDelete(final I_AD_Field field) { final AdFieldId adFieldId = AdFieldId.ofRepoId(field.getAD_Field_ID()); final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); adWindowDAO.deleteUIElementsByFieldId(adFieldId); final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.deleteExistingADElementLinkForFieldId(adFieldId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\field\model\interceptor\AD_Field.java
1
请在Spring Boot框架中完成以下Java代码
public String getRootScopeId() { return rootScopeId; } @Override public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } @Override public String getRootScopeType() { return rootScopeType; } @Override public void setRootScopeType(String rootScopeType) { this.rootScopeType = rootScopeType; } @Override public Date getCreateTime() { return createTime; }
@Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getHierarchyType() { return hierarchyType; } @Override public void setHierarchyType(String hierarchyType) { this.hierarchyType = hierarchyType; } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\EntityLinkEntityImpl.java
2
请完成以下Java代码
public void setIsWholeHU (final boolean IsWholeHU) { set_Value (COLUMNNAME_IsWholeHU, IsWholeHU); } @Override public boolean isWholeHU() { return get_ValueAsBoolean(COLUMNNAME_IsWholeHU); } @Override public de.metas.handlingunits.model.I_M_HU getM_HU() { return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Inventory_Candidate_ID (final int M_Inventory_Candidate_ID) { if (M_Inventory_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Inventory_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Inventory_Candidate_ID, M_Inventory_Candidate_ID); } @Override public int getM_Inventory_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_M_Inventory_Candidate_ID); } @Override
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToDispose (final BigDecimal QtyToDispose) { set_Value (COLUMNNAME_QtyToDispose, QtyToDispose); } @Override public BigDecimal getQtyToDispose() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDispose); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Inventory_Candidate.java
1
请完成以下Java代码
public boolean isEmpty() { return false; } public T getElement() { return value; } public void detach() { this.prev.setNext(this.getNext()); this.next.setPrev(this.getPrev()); } @Override public DoublyLinkedList<T> getListReference() { return this.list; } @Override public LinkedListNode<T> setPrev(LinkedListNode<T> prev) { this.prev = prev; return this;
} @Override public LinkedListNode<T> setNext(LinkedListNode<T> next) { this.next = next; return this; } @Override public LinkedListNode<T> getPrev() { return this.prev; } @Override public LinkedListNode<T> getNext() { return this.next; } @Override public LinkedListNode<T> search(T value) { return this.getElement() == value ? this : this.getNext().search(value); } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\Node.java
1
请完成以下Java代码
public String docValidate(PO po, int timing) { final int clientId = instance.getType().getAD_Client_ID(); if (clientId != 0 && clientId != po.getAD_Client_ID()) { // this validator does not applies for current tenant return null; } if (timing == TIMING_AFTER_COMPLETE) { referenceNoBL.linkReferenceNo(po, instance); } else if (timing == TIMING_AFTER_VOID || timing == TIMING_AFTER_REACTIVATE || timing == TIMING_AFTER_REVERSEACCRUAL || timing == TIMING_AFTER_REVERSECORRECT) { referenceNoBL.unlinkReferenceNo(po, instance); } return null; } /** * Register table doc validators. Private because it is called automatically on {@link #initialize(ModelValidationEngine, MClient)}. */ private void register() { for (int tableId : instance.getAssignedTableIds()) { final String tableName = adTableDAO.retrieveTableName(tableId); if (documentBL.isDocumentTable(tableName)) { engine.addDocValidate(tableName, this); logger.debug("Registered docValidate " + this); } else { engine.addModelChange(tableName, this);
logger.debug("Registered modelChange " + this); } } } public void unregister() { for (int tableId : instance.getAssignedTableIds()) { final String tableName = adTableDAO.retrieveTableName(tableId); engine.removeModelChange(tableName, this); engine.removeDocValidate(tableName, this); } logger.debug("Unregistered " + this); } public IReferenceNoGeneratorInstance getInstance() { return instance; } @Override public String toString() { return "ReferenceNoGeneratorInstanceValidator [instance=" + instance + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\ReferenceNoGeneratorInstanceValidator.java
1
请完成以下Java代码
public void list() { System.out.println(toString()); if (m_columnSet != null) m_columnSet.list(); System.out.println(); if (m_lineSet != null) m_lineSet.list(); } // dump /** * Get Where Clause for Report * @return Where Clause for Report */ public String getWhereClause() { // AD_Client indirectly via AcctSchema StringBuffer sb = new StringBuffer(); // Mandatory AcctSchema sb.append("C_AcctSchema_ID=").append(getC_AcctSchema_ID()); // return sb.toString(); } // getWhereClause /*************************************************************************/ /** * String Representation * @return Info */ public String toString () { StringBuffer sb = new StringBuffer ("MReport[") .append(get_ID()).append(" - ").append(getName()); if (getDescription() != null) sb.append("(").append(getDescription()).append(")"); sb.append(" - C_AcctSchema_ID=").append(getC_AcctSchema_ID()) .append(", C_Calendar_ID=").append(getC_Calendar_ID()); sb.append ("]"); return sb.toString (); } // toString
/** * Get Column Set * @return Column Set */ public MReportColumnSet getColumnSet() { return m_columnSet; } /** * Get Line Set * @return Line Set */ public MReportLineSet getLineSet() { return m_lineSet; } } // MReport
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReport.java
1
请完成以下Java代码
public class ContactWithJavaUtilDate { private String name; private String address; private String phone; @JsonFormat(pattern="yyyy-MM-dd") private Date birthday; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date lastUpdate; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) {
this.phone = phone; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } public ContactWithJavaUtilDate() { } public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { this.name = name; this.address = address; this.phone = phone; this.birthday = birthday; this.lastUpdate = lastUpdate; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\jsondateformat\ContactWithJavaUtilDate.java
1
请完成以下Java代码
public static final class Builder { private final String name; private String returnType; private int modifiers; private Object value; private boolean initialized; private Builder(String name) { this.name = name; } /** * Sets the modifiers. * @param modifiers the modifiers * @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /**
* Sets the value. * @param value the value * @return this for method chaining */ public Builder value(Object value) { this.value = value; this.initialized = true; return this; } /** * Sets the return type. * @param returnType the return type * @return the field */ public GroovyFieldDeclaration returning(String returnType) { this.returnType = returnType; return new GroovyFieldDeclaration(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyFieldDeclaration.java
1
请完成以下Java代码
private static class CachesGroup { private final CacheLabel label; private final ConcurrentMap<Long, CacheInterface> caches = new MapMaker().weakValues().makeMap(); public CachesGroup(@NonNull final CacheLabel label) { this.label = label; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("label", label) .add("size", caches.size()) .toString(); } public void addCache(@NonNull final CacheInterface cache) { try (final IAutoCloseable ignored = CacheMDC.putCache(cache)) { caches.put(cache.getCacheId(), cache); } } public void removeCache(@NonNull final CacheInterface cache) { try (final IAutoCloseable ignored = CacheMDC.putCache(cache)) { caches.remove(cache.getCacheId()); } } private Stream<CacheInterface> streamCaches() { return caches.values().stream().filter(Objects::nonNull); } private long invalidateAllNoFail() { return streamCaches() .mapToLong(CachesGroup::invalidateNoFail) .sum(); } private long invalidateForRecordNoFail(final TableRecordReference recordRef) { return streamCaches()
.mapToLong(cache -> invalidateNoFail(cache, recordRef)) .sum(); } private static long invalidateNoFail(@Nullable final CacheInterface cacheInstance) { try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance)) { if (cacheInstance == null) { return 0; } return cacheInstance.reset(); } catch (final Exception ex) { // log but don't fail logger.warn("Error while resetting {}. Ignored.", cacheInstance, ex); return 0; } } private static long invalidateNoFail(final CacheInterface cacheInstance, final TableRecordReference recordRef) { try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance)) { return cacheInstance.resetForRecordId(recordRef); } catch (final Exception ex) { // log but don't fail logger.warn("Error while resetting {} for {}. Ignored.", cacheInstance, recordRef, ex); return 0; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheMgt.java
1
请完成以下Java代码
private void cleanupPartitions(EventType eventType, long eventExpTime) { partitioningRepository.dropPartitionsBefore(eventType.getTable(), eventExpTime, partitionConfiguration.getPartitionSizeInMs(eventType)); } private void cleanupPartitionsCache(long expTime, boolean isDebug) { for (EventType eventType : EventType.values()) { if (eventType.isDebug() == isDebug) { partitioningRepository.cleanupPartitionsCache(eventType.getTable(), expTime, partitionConfiguration.getPartitionSizeInMs(eventType)); } } } private void parseUUID(String src, String paramName) { if (!StringUtils.isEmpty(src)) { try { UUID.fromString(src); } catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to convert " + paramName + " to UUID!"); } } } private EventRepository<? extends EventEntity<?>, ?> getEventRepository(EventType eventType) { var repository = repositories.get(eventType); if (repository == null) { throw new RuntimeException("Event type: " + eventType + " is not supported!"); } return repository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\JpaBaseEventDao.java
1
请完成以下Java代码
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) {
this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\param\UserParam.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId;
} public void setStartTime(Date startTime) { this.startTime = startTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntityImpl.java
1
请完成以下Java代码
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return ""; // shall not happen, see constructor } final String str; if (ignoreCase) { // will return the uppercase version of both operands str = ((String)value).toUpperCase(); } else { str = (String)value; } return supplementWildCards(str); }
@Override public String toString() { return "Modifier[ignoreCase=" + ignoreCase + "]"; } } public StringLikeFilter( @NonNull final String columnName, @NonNull final String substring, final boolean ignoreCase) { super(columnName, ignoreCase ? Operator.STRING_LIKE_IGNORECASE : Operator.STRING_LIKE, substring, new StringLikeQueryFilterModifier(ignoreCase)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringLikeFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonExternalSystemShopware6ConfigMapping { @NonNull Integer seqNo; @Nullable String docTypeOrder; @Nullable String paymentRule; @NonNull SyncAdvise bPartnerSyncAdvice; @NonNull SyncAdvise bPartnerLocationSyncAdvice; @Nullable Boolean invoiceEmailEnabled; @Nullable String paymentTermValue; @Nullable String sw6CustomerGroup; @Nullable String sw6PaymentMethod; @Nullable String description; @Builder @JsonCreator public JsonExternalSystemShopware6ConfigMapping( @JsonProperty("seqNo") @NonNull final Integer seqNo, @JsonProperty("docTypeOrder") @Nullable final String docTypeOrder, @JsonProperty("paymentRule") @Nullable final String paymentRule, @JsonProperty("bpartnerSyncAdvice") @NonNull final SyncAdvise bPartnerSyncAdvice, @JsonProperty("bpartnerLocationSyncAdvice") @NonNull final SyncAdvise bPartnerLocationSyncAdvice, @JsonProperty("invoiceEmailEnabled") @Nullable final Boolean invoiceEmailEnabled, @JsonProperty("paymentTerm") @Nullable final String paymentTermValue, @JsonProperty("sw6CustomerGroup") @Nullable final String sw6CustomerGroup, @JsonProperty("sw6PaymentMethod") @Nullable final String sw6PaymentMethod,
@JsonProperty("description") @Nullable final String description) { this.seqNo = seqNo; this.docTypeOrder = docTypeOrder; this.paymentRule = paymentRule; this.bPartnerSyncAdvice = bPartnerSyncAdvice; this.bPartnerLocationSyncAdvice = bPartnerLocationSyncAdvice; this.invoiceEmailEnabled = invoiceEmailEnabled; this.paymentTermValue = paymentTermValue; this.sw6CustomerGroup = sw6CustomerGroup; this.sw6PaymentMethod = sw6PaymentMethod; this.description = description; } public boolean isGroupMatching(@NonNull final String sw6CustomerGroup) { return Check.isBlank(this.sw6CustomerGroup) || this.sw6CustomerGroup.trim().equals(sw6CustomerGroup.trim()); } public boolean isPaymentMethodMatching(@NonNull final String sw6PaymentMethod) { return Check.isBlank(this.sw6PaymentMethod) || this.sw6PaymentMethod.trim().equals(sw6PaymentMethod.trim()); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalsystem\src\main\java\de\metas\common\externalsystem\JsonExternalSystemShopware6ConfigMapping.java
2
请完成以下Java代码
public Integer getHandAddStatus() { return handAddStatus; } public void setHandAddStatus(Integer handAddStatus) { this.handAddStatus = handAddStatus; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName());
sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", selectType=").append(selectType); sb.append(", inputType=").append(inputType); sb.append(", inputList=").append(inputList); sb.append(", sort=").append(sort); sb.append(", filterType=").append(filterType); sb.append(", searchType=").append(searchType); sb.append(", relatedStatus=").append(relatedStatus); sb.append(", handAddStatus=").append(handAddStatus); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java
1
请完成以下Java代码
private void resetVendor(final IHUContext huContext, final I_M_HU hu) { // // Get the HU's BPartner. // We will need it to set the SubProducer. final int bpartnerId = hu.getC_BPartner_ID(); // // Reset HU's BPartner & BP Location hu.setC_BPartner_ID(-1); hu.setC_BPartner_Location_ID(-1); // // If there was no partner, we have nothing to set if (bpartnerId <= 0) { return; } // // If HU does not support the SubProducer attribute, we have nothing to do
final IAttributeStorage huAttributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final org.compiere.model.I_M_Attribute attribute_subProducer = huAttributeStorage.getAttributeByValueKeyOrNull(HUAttributeConstants.ATTR_SubProducerBPartner_Value); if (attribute_subProducer == null) { return; } // // Don't override existing value final int subproducerBPartnerId = huAttributeStorage.getValueAsInt(attribute_subProducer); if (subproducerBPartnerId > 0) { return; } // // Sets the ex-Vendor BPartner ID as SubProducer. huAttributeStorage.setValue(attribute_subProducer, bpartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\ReceiptInOutLineHUAssignmentListener.java
1
请在Spring Boot框架中完成以下Java代码
public class SchoolNotification { @Autowired Grader grader; private String name; private Collection<Integer> marks; public SchoolNotification(String name) { this.name = name; this.marks = new ArrayList<Integer>(); } public String addMark(Integer mark) { this.marks.add(mark); return this.grader.grade(this.marks); } public String getName() {
return name; } public void setName(String name) { this.name = name; } public Collection<Integer> getMarks() { return marks; } public void setMarks(Collection<Integer> marks) { this.marks = marks; } }
repos\tutorials-master\spring-core\src\main\java\com\baeldung\methodinjections\SchoolNotification.java
2
请完成以下Spring Boot application配置
http.port=8080 server.port=8443 server.ssl.enabled=true # The format used for the keystore server.ssl.key-store-type=PKCS12 # The path to the keystore containing the certificate server.ssl.key-store=classpath:keystore/baeldung.p12 # The password used to generate the certificate server.ssl.key-store-password=password # The alias mapped to the certifi
cate server.ssl.key-alias=baeldung #trust store location trust.store=classpath:keystore/baeldung.p12 #trust store password trust.store.password=password
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\resources\application-ssl.properties
2
请完成以下Java代码
public void setDeleteGroupAuthoritySql(String deleteGroupAuthoritySql) { Assert.hasText(deleteGroupAuthoritySql, "deleteGroupAuthoritySql should have text"); this.deleteGroupAuthoritySql = deleteGroupAuthoritySql; } /** * Optionally sets the UserCache if one is in use in the application. This allows the * user to be removed from the cache after updates have taken place to avoid stale * data. * @param userCache the cache used by the AuthenticationManager. */ public void setUserCache(UserCache userCache) { Assert.notNull(userCache, "userCache cannot be null"); this.userCache = userCache; } /** * Sets whether the {@link #updatePassword(UserDetails, String)} method should * actually update the password. * <p> * Defaults to {@code false} to prevent accidental password updates that might produce * passwords that are too large for the current database schema. Users must explicitly * set this to {@code true} to enable password updates. * @param enableUpdatePassword {@code true} to enable password updates, {@code false} * otherwise. * @since 7.0 */ public void setEnableUpdatePassword(boolean enableUpdatePassword) { this.enableUpdatePassword = enableUpdatePassword; } private void validateUserDetails(UserDetails user) { Assert.hasText(user.getUsername(), "Username may not be empty or null"); validateAuthorities(user.getAuthorities()); } private void validateAuthorities(Collection<? extends GrantedAuthority> authorities) { Assert.notNull(authorities, "Authorities list must not be null"); for (GrantedAuthority authority : authorities) {
Assert.notNull(authority, "Authorities list contains a null entry"); Assert.hasText(authority.getAuthority(), "getAuthority() method must return a non-empty string"); } } /** * Conditionally updates password based on the setting from * {@link #setEnableUpdatePassword(boolean)}. {@inheritDoc} * @since 7.0 */ @Override public UserDetails updatePassword(UserDetails user, @Nullable String newPassword) { if (this.enableUpdatePassword) { // @formatter:off UserDetails updated = User.withUserDetails(user) .password(newPassword) .build(); // @formatter:on updateUser(updated); return updated; } return user; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\JdbcUserDetailsManager.java
1
请完成以下Java代码
public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; }
@Override public Rule toRule() { return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDefinitionEntity entity = (ApiDefinitionEntity) o; return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) && Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) && Objects.equals(predicateItems, entity.predicateItems); } @Override public int hashCode() { return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); } @Override public String toString() { return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + ", predicateItems=" + predicateItems + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiDefinitionEntity.java
1
请完成以下Java代码
public class DBDeadLockDetectedException extends DBException { /** * */ private static final long serialVersionUID = -1436774241410586947L; private String ownBackEndId; /** * * @param e the "orginal" exception from which we know that it is a deadlock. Note that this is usually a SQLException. * @param connection the connection that was used. may be <code>null</code>. */ public DBDeadLockDetectedException(@Nullable final Throwable e, @Nullable final Connection connection) { super(e); setDeadLockInfo(connection); } private void setDeadLockInfo(@Nullable final Connection connection) { if (DB.isPostgreSQL() && connection != null) { final boolean throwDBException = false; // in case of e.g. a closed connection or other problems, don't make a fuss and throw further exceptions ownBackEndId = DB.getDatabase().getConnectionBackendId(connection, throwDBException);
} else { // FIXME implement for Oracle } resetMessageBuilt(); } @Override protected ITranslatableString buildMessage() { // NOTE: completely override super's message because it's not relevant for our case final TranslatableStringBuilder message = TranslatableStrings.builder(); message.append("Own Backend/Process ID ="); message.append(ownBackEndId); message.append("; ExceptionMessage: "); message.append(getOriginalMessage()); return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\DBDeadLockDetectedException.java
1
请完成以下Java代码
public boolean isFullyConfirmed() { return getTargetQty().compareTo(getConfirmedQty()) == 0; } // isFullyConfirmed /** * Before Delete - do not delete * @return false */ @Override protected boolean beforeDelete () { throw new AdempiereException("@CannotDelete@"); } // beforeDelete /** * Before Save * @param newRecord new
* @return true */ @Override protected boolean beforeSave (boolean newRecord) { // Calculate Difference = Target - Confirmed - Scrapped BigDecimal difference = getTargetQty(); difference = difference.subtract(getConfirmedQty()); difference = difference.subtract(getScrappedQty()); setDifferenceQty(difference); // return true; } // beforeSave } // MInOutLineConfirm
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInOutLineConfirm.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } @Override public String toString() { return this.getClass().getSimpleName() + "[" + "count=" + count + ", processDefinitionKey='" + processDefinitionKey + '\'' + ", processDefinitionId='" + processDefinitionId + '\'' + ", processDefinitionName='" + processDefinitionName + '\'' + ", taskName='" + taskName + '\'' + ", tenantId='" + tenantId + '\'' + ']'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskReportResultEntity.java
1
请完成以下Java代码
public int getHR_Payroll_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Payroll Year. @param HR_Year_ID Payroll Year */ public void setHR_Year_ID (int HR_Year_ID) { if (HR_Year_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Year_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Year_ID, Integer.valueOf(HR_Year_ID)); } /** Get Payroll Year. @return Payroll Year */ public int getHR_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Net Days. @param NetDays Net Days in which payment is due */ public void setNetDays (int NetDays) { set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays)); } /** Get Net Days. @return Net Days in which payment is due */ public int getNetDays () { Integer ii = (Integer)get_Value(COLUMNNAME_NetDays); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); }
/** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (int Qty) { set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty)); } /** Get Quantity. @return Quantity */ public int getQty () { Integer ii = (Integer)get_Value(COLUMNNAME_Qty); if (ii == null) return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Year.java
1
请完成以下Java代码
public Todo syncGson() throws Exception { String response = sampleApiRequest(); List<Todo> todo = gson.fromJson(response, new TypeToken<List<Todo>>() { }.getType()); return todo.get(1); } public Todo syncJackson() throws Exception { String response = sampleApiRequest(); Todo[] todo = objectMapper.readValue(response, Todo[].class); return todo[1]; } public Todo asyncJackson() throws Exception { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/todos")) .build(); TodoAppClient todoAppClient = new TodoAppClient(); List<Todo> todo = HttpClient.newHttpClient() .sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenApply(todoAppClient::readValueJackson) .get(); return todo.get(1); } public Todo asyncGson() throws Exception { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/todos")) .build(); TodoAppClient todoAppClient = new TodoAppClient(); List<Todo> todo = HttpClient.newHttpClient() .sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenApply(todoAppClient::readValueGson) .get();
return todo.get(1); } List<Todo> readValueJackson(String content) { try { return objectMapper.readValue(content, new TypeReference<List<Todo>>() { }); } catch (IOException ioe) { throw new CompletionException(ioe); } } List<Todo> readValueGson(String content) { return gson.fromJson(content, new TypeToken<List<Todo>>() { }.getType()); } }
repos\tutorials-master\core-java-modules\core-java-11-3\src\main\java\com\baeldung\httppojo\TodoAppClient.java
1
请完成以下Java代码
public static BPartnerCompositeLookupKey ofCode(@NonNull final String code) { assumeNotEmpty(code, "Given parameter 'code' may not be empty"); return new BPartnerCompositeLookupKey(null, null, code.trim(), null, null); } public static BPartnerCompositeLookupKey ofGln(@NonNull final GLN gln) { return new BPartnerCompositeLookupKey(null, null, null, gln, null); } public static BPartnerCompositeLookupKey ofGlnWithLabel(@NonNull final GlnWithLabel glnWithLabel) { return new BPartnerCompositeLookupKey(null, null, null, null, glnWithLabel); } public static BPartnerCompositeLookupKey ofIdentifierString(@NonNull final IdentifierString bpartnerIdentifier) { switch (bpartnerIdentifier.getType()) { case EXTERNAL_ID: return BPartnerCompositeLookupKey.ofJsonExternalId(bpartnerIdentifier.asJsonExternalId()); case VALUE: return BPartnerCompositeLookupKey.ofCode(bpartnerIdentifier.asValue()); case GLN: return BPartnerCompositeLookupKey.ofGln(bpartnerIdentifier.asGLN()); case GLN_WITH_LABEL: return BPartnerCompositeLookupKey.ofGlnWithLabel(bpartnerIdentifier.asGlnWithLabel()); case METASFRESH_ID:
return BPartnerCompositeLookupKey.ofMetasfreshId(bpartnerIdentifier.asMetasfreshId()); default: throw new AdempiereException("Unexpected type=" + bpartnerIdentifier.getType()); } } MetasfreshId metasfreshId; JsonExternalId jsonExternalId; String code; GLN gln; GlnWithLabel glnWithLabel; private BPartnerCompositeLookupKey( @Nullable final MetasfreshId metasfreshId, @Nullable final JsonExternalId jsonExternalId, @Nullable final String code, @Nullable final GLN gln, @Nullable final GlnWithLabel glnWithLabel) { this.metasfreshId = metasfreshId; this.jsonExternalId = jsonExternalId; this.code = code; this.gln = gln; this.glnWithLabel = glnWithLabel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerCompositeLookupKey.java
1
请完成以下Java代码
public MessageCorrelationResultImpl execute(final CommandContext commandContext) { ensureAtLeastOneNotNull( "At least one of the following correlation criteria has to be present: " + "messageName, businessKey, correlationKeys, processInstanceId", messageName, builder.getBusinessKey(), builder.getCorrelationProcessInstanceVariables(), builder.getProcessInstanceId()); final CorrelationHandler correlationHandler = Context.getProcessEngineConfiguration().getCorrelationHandler(); final CorrelationSet correlationSet = new CorrelationSet(builder); CorrelationHandlerResult correlationResult = null; if (startMessageOnly) { List<CorrelationHandlerResult> correlationResults = commandContext.runWithoutAuthorization(new Callable<List<CorrelationHandlerResult>>() { public List<CorrelationHandlerResult> call() throws Exception { return correlationHandler.correlateStartMessages(commandContext, messageName, correlationSet); } }); if (correlationResults.isEmpty()) { throw new MismatchingMessageCorrelationException(messageName, "No process definition matches the parameters"); } else if (correlationResults.size() > 1) { throw LOG.exceptionCorrelateMessageToSingleProcessDefinition(messageName, correlationResults.size(), correlationSet); } else { correlationResult = correlationResults.get(0);
} } else { correlationResult = commandContext.runWithoutAuthorization(new Callable<CorrelationHandlerResult>() { public CorrelationHandlerResult call() throws Exception { return correlationHandler.correlateMessage(commandContext, messageName, correlationSet); } }); if (correlationResult == null) { throw new MismatchingMessageCorrelationException(messageName, "No process definition or execution matches the parameters"); } } // check authorization checkAuthorization(correlationResult); return createMessageCorrelationResult(commandContext, correlationResult); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CorrelateMessageCmd.java
1
请在Spring Boot框架中完成以下Java代码
public void setTechnologies(List<Technology> technologies) { this.technologies = technologies; } public String getInputText() { return inputText; } public void setInputText(String inputText) { this.inputText = inputText; } public String getOutputText() { return outputText; } public void setOutputText(String outputText) { this.outputText = outputText; } public class Technology { private String name; private String currentVersion; public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getCurrentVersion() { return currentVersion; } public void setCurrentVersion(String currentVersion) { this.currentVersion = currentVersion; } } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\HelloPFBean.java
2
请在Spring Boot框架中完成以下Java代码
public LDAPConfiguration ldapConfiguration() { LDAPConfiguration ldapConfiguration = new LDAPConfiguration(); properties.customize(ldapConfiguration); if (ldapQueryBuilder != null) { ldapConfiguration.setLdapQueryBuilder(ldapQueryBuilder); } if (ldapGroupCacheListener != null) { ldapConfiguration.setGroupCacheListener(ldapGroupCacheListener); } return ldapConfiguration; } @Bean public EngineConfigurationConfigurer<SpringIdmEngineConfiguration> ldapIdmEngineConfigurer(LDAPConfiguration ldapConfiguration) { return idmEngineConfiguration -> idmEngineConfiguration .setIdmIdentityService(new LDAPIdentityServiceImpl(ldapConfiguration, createCache(idmEngineConfiguration, ldapConfiguration), idmEngineConfiguration)); } // We need a custom AuthenticationProvider for the LDAP Support // since the default (DaoAuthenticationProvider) from Spring Security // uses a Password encoder to perform the matching and we need to use
// the IdmIdentityService for LDAP @Bean @ConditionalOnMissingBean(AuthenticationProvider.class) public FlowableAuthenticationProvider flowableAuthenticationProvider(IdmIdentityService idmIdentitySerivce, UserDetailsService userDetailsService) { return new FlowableAuthenticationProvider(idmIdentitySerivce, userDetailsService); } protected LDAPGroupCache createCache(SpringIdmEngineConfiguration engineConfiguration, LDAPConfiguration ldapConfiguration) { LDAPGroupCache ldapGroupCache = null; if (ldapConfiguration.getGroupCacheSize() > 0) { // We need to use a supplier for the clock as the clock would be created later ldapGroupCache = new LDAPGroupCache(ldapConfiguration.getGroupCacheSize(), ldapConfiguration.getGroupCacheExpirationTime(), engineConfiguration::getClock); if (ldapConfiguration.getGroupCacheListener() != null) { ldapGroupCache.setLdapCacheListener(ldapConfiguration.getGroupCacheListener()); } } return ldapGroupCache; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ldap\FlowableLdapAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if(null== configAttributes || configAttributes.size() <=0) { return; } ConfigAttribute c; String needRole; for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) { c = iter.next(); needRole = c.getAttribute(); for(GrantedAuthority ga : authentication.getAuthorities()) { if(needRole.trim().equals(ga.getAuthority())) { return; } } }
throw new AccessDeniedException("no right"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\service\MyAccessDecisionManager.java
2
请在Spring Boot框架中完成以下Java代码
public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() {
return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public AuthStatusEnum getAuthStatusEnum() { return authStatusEnum; } public void setAuthStatusEnum(AuthStatusEnum authStatusEnum) { this.authStatusEnum = authStatusEnum; } public String getAuthMsg() { return authMsg; } public void setAuthMsg(String authMsg) { this.authMsg = authMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthResultVo.java
2
请完成以下Java代码
public int getC_Currency_ID() { return 0; } @Override public String getProcessMsg() { return null; } @Override public String getSummary() { return getDocumentNo() + "/" + getDatePromised(); } @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateOrdered()); } @Override public File createPDF() { final DocumentReportService documentReportService = SpringContextHolder.instance.getBean(DocumentReportService.class); final ReportResultData report = documentReportService.createStandardDocumentReportData(getCtx(), StandardDocumentReportType.MANUFACTURING_ORDER, getPP_Order_ID()); return report.writeToTemporaryFile(get_TableName() + get_ID()); } @Override public String getDocumentInfo() { final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); final DocTypeId docTypeId = DocTypeId.ofRepoId(getC_DocType_ID()); final ITranslatableString docTypeName = docTypeBL.getNameById(docTypeId); return docTypeName.translate(Env.getADLanguageOrBaseLanguage()) + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return Services.get(IPPOrderRoutingRepository.class).getByOrderId(orderId); } @Override public String toString() { return "MPPOrder[ID=" + get_ID() + "-DocumentNo=" + getDocumentNo() + ",IsSOTrx=" + isSOTrx() + ",C_DocType_ID=" + getC_DocType_ID() + "]"; } /** * Auto report the first Activity and Sub contracting if are Milestone Activity */ private void autoReportActivities() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { if (activity.isMilestone() && (activity.isSubcontracting() || orderRouting.isFirstActivity(activity))) {
ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder() .order(this) .orderActivity(activity) .qtyMoved(activity.getQtyToDeliver()) .durationSetup(Duration.ZERO) .duration(Duration.ZERO) .build()); } } } private void createVariances() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); // for (final I_PP_Order_BOMLine bomLine : getLines()) { ppCostCollectorBL.createMaterialUsageVariance(this, bomLine); } // final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { ppCostCollectorBL.createResourceUsageVariance(this, activity); } } } // MPPOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java
1
请完成以下Java代码
default boolean isNoSelection() { return getSelectionSize().isNoSelection(); } default boolean isSingleSelection() { return getSelectionSize().isSingleSelection(); } default boolean isMoreThanOneSelected() { return getSelectionSize().isMoreThanOneSelected(); } default boolean isMoreThanAllowedSelected(final int maxAllowedSelectionSize) { return getSelectionSize().getSize() > maxAllowedSelectionSize; } /** * @return selected included rows of current single selected document */ default Set<TableRecordReference> getSelectedIncludedRecords() { return ImmutableSet.of(); } default boolean isSingleIncludedRecordSelected() { return getSelectedIncludedRecords().size() == 1;
} <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass); default ProcessPreconditionsResolution acceptIfSingleSelection() { if (isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } else { return ProcessPreconditionsResolution.accept(); } } default OptionalBoolean isExistingDocument() {return OptionalBoolean.UNKNOWN;} default OptionalBoolean isProcessedDocument() { return OptionalBoolean.UNKNOWN; }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\IProcessPreconditionsContext.java
1
请完成以下Java代码
public java.lang.String getDataEntry_RecordData () { return (java.lang.String)get_Value(COLUMNNAME_DataEntry_RecordData); } @Override public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class); } @Override public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab) { set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab); } /** Set Unterregister. @param DataEntry_SubTab_ID Unterregister */ @Override public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); } /** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Indication. @param M_Indication_ID Indication */ @Override public void setM_Indication_ID (int M_Indication_ID) { if (M_Indication_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Indication_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Indication_ID, Integer.valueOf(M_Indication_ID)); } /** Get Indication. @return Indication */ @Override public int getM_Indication_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Indication_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_Indication.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getType() { return type; } public void setType(BigDecimal type) { this.type = type; } public Payer ikNumber(String ikNumber) { this.ikNumber = ikNumber; return this; } /** * Get ikNumber * @return ikNumber **/ @Schema(example = "108534160", description = "") public String getIkNumber() { return ikNumber; } public void setIkNumber(String ikNumber) { this.ikNumber = ikNumber; } public Payer timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
Payer payer = (Payer) o; return Objects.equals(this._id, payer._id) && Objects.equals(this.name, payer.name) && Objects.equals(this.type, payer.type) && Objects.equals(this.ikNumber, payer.ikNumber) && Objects.equals(this.timestamp, payer.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, type, ikNumber, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Payer {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Payer.java
2
请完成以下Java代码
public org.compiere.model.I_C_ValidCombination getPayment_WriteOff_A() { return get_ValueAsPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPayment_WriteOff_A(final org.compiere.model.I_C_ValidCombination Payment_WriteOff_A) { set_ValueFromPO(COLUMNNAME_Payment_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, Payment_WriteOff_A); } @Override public void setPayment_WriteOff_Acct (final int Payment_WriteOff_Acct) { set_Value (COLUMNNAME_Payment_WriteOff_Acct, Payment_WriteOff_Acct); } @Override public int getPayment_WriteOff_Acct() { return get_ValueAsInt(COLUMNNAME_Payment_WriteOff_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedGain_A() { return get_ValueAsPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedGain_A(final org.compiere.model.I_C_ValidCombination RealizedGain_A) { set_ValueFromPO(COLUMNNAME_RealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedGain_A); } @Override public void setRealizedGain_Acct (final int RealizedGain_Acct) { set_Value (COLUMNNAME_RealizedGain_Acct, RealizedGain_Acct); }
@Override public int getRealizedGain_Acct() { return get_ValueAsInt(COLUMNNAME_RealizedGain_Acct); } @Override public org.compiere.model.I_C_ValidCombination getRealizedLoss_A() { return get_ValueAsPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setRealizedLoss_A(final org.compiere.model.I_C_ValidCombination RealizedLoss_A) { set_ValueFromPO(COLUMNNAME_RealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, RealizedLoss_A); } @Override public void setRealizedLoss_Acct (final int RealizedLoss_Acct) { set_Value (COLUMNNAME_RealizedLoss_Acct, RealizedLoss_Acct); } @Override public int getRealizedLoss_Acct() { return get_ValueAsInt(COLUMNNAME_RealizedLoss_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public R<Notice> detail(Notice notice) { Notice detail = noticeService.getOne(Condition.getQueryWrapper(notice)); return R.data(detail); } /** * 分页 */ @GetMapping("/list") @Parameters({ @Parameter(name = "category", description = "公告类型", in = ParameterIn.QUERY, schema = @Schema(type = "integer")), @Parameter(name = "title", description = "公告标题", in = ParameterIn.QUERY, schema = @Schema(type = "string")) }) @ApiOperationSupport(order = 2) @Operation(summary = "分页", description = "传入notice") public R<IPage<Notice>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> notice, Query query) { IPage<Notice> pages = noticeService.page(Condition.getPage(query), Condition.getQueryWrapper(notice, Notice.class)); return R.data(pages); } /** * 新增 */ @PostMapping("/save") @ApiOperationSupport(order = 3) @Operation(summary = "新增", description = "传入notice") public R save(@RequestBody Notice notice) { return R.status(noticeService.save(notice)); } /** * 修改
*/ @PostMapping("/update") @ApiOperationSupport(order = 4) @Operation(summary = "修改", description = "传入notice") public R update(@RequestBody Notice notice) { return R.status(noticeService.updateById(notice)); } /** * 新增或修改 */ @PostMapping("/submit") @ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入notice") public R submit(@RequestBody Notice notice) { return R.status(noticeService.saveOrUpdate(notice)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "逻辑删除", description = "传入notice") public R remove(@Parameter(description = "主键集合") @RequestParam String ids) { boolean temp = noticeService.deleteLogic(Func.toLongList(ids)); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-demo\src\main\java\com\example\demo\controller\NoticeController.java
2
请完成以下Java代码
public Optional<Boolean> getBooleanValue() { return kv.getBooleanValue(); } @Override public Optional<Double> getDoubleValue() { return kv.getDoubleValue(); } @Override public Optional<String> getJsonValue() { return kv.getJsonValue(); } @Override public Object getValue() { return kv.getValue(); } @Override public String getValueAsString() { return kv.getValueAsString(); } @Override public int getDataPoints() {
int length; switch (getDataType()) { case STRING: length = getStrValue().get().length(); break; case JSON: length = getJsonValue().get().length(); break; default: return 1; } return Math.max(1, (length + MAX_CHARS_PER_DATA_POINT - 1) / MAX_CHARS_PER_DATA_POINT); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicTsKvEntry.java
1
请完成以下Java代码
public Set<Integer> getAffectedInOutLinesId() { return affectedInOutLinesId; } private final I_M_InOut getM_InOut() { return _inoutRef.getValue(); } public EmptiesInOutLinesProducer addSource(final I_M_HU_PackingMaterial packingMaterial, final int qty) { addSource(PlainPackingMaterialDocumentLineSource.of(packingMaterial, qty)); return this; } @Override protected void assertValid(final IPackingMaterialDocumentLineSource source) { Check.assumeInstanceOf(source, PlainPackingMaterialDocumentLineSource.class, "source"); } @Override protected IPackingMaterialDocumentLine createPackingMaterialDocumentLine(@NonNull final ProductId productId) { final I_M_InOut inout = getM_InOut(); final I_M_InOutLine inoutLine = inOutBL.newInOutLine(inout, I_M_InOutLine.class); final UomId uomId = productBL.getStockUOMId(ProductId.toRepoId( productId)); inoutLine.setM_Product_ID(ProductId.toRepoId( productId)); inoutLine.setC_UOM_ID(uomId.getRepoId()); // prevent the system from picking its default-UOM; there might be no UOM-conversion to/from the product's UOM // NOTE: don't save it return new EmptiesInOutLinePackingMaterialDocumentLine(inoutLine); } private final EmptiesInOutLinePackingMaterialDocumentLine toImpl(final IPackingMaterialDocumentLine pmLine) { return (EmptiesInOutLinePackingMaterialDocumentLine)pmLine; } @Override protected void removeDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine) { final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine); final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine(); if (!InterfaceWrapperHelper.isNew(inoutLine)) { InterfaceWrapperHelper.delete(inoutLine); } } @Override
protected void createDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine) { final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine); final I_M_InOut inout = getM_InOut(); InterfaceWrapperHelper.save(inout); // make sure inout header is saved final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine(); inoutLine.setM_InOut(inout); // make sure inout line is linked to our M_InOut_ID (in case it was just saved) inoutLine.setIsActive(true); // just to be sure // task FRESH-273 inoutLine.setIsPackagingMaterial(true); final boolean wasNew = InterfaceWrapperHelper.isNew(inoutLine); InterfaceWrapperHelper.save(inoutLine); if (wasNew) { affectedInOutLinesId.add(inoutLine.getM_InOutLine_ID()); } } @Override protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source, final IPackingMaterialDocumentLine pmLine) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\EmptiesInOutLinesProducer.java
1
请完成以下Java代码
static AddReturnAddress builder() { return returnAddress -> closing -> dateOfLetter -> insideAddress -> salutation -> body -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); } interface AddReturnAddress { Letter.AddClosing withReturnAddress(String returnAddress); } interface AddClosing { Letter.AddDateOfLetter withClosing(String closing); } interface AddDateOfLetter {
Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter); } interface AddInsideAddress { Letter.AddSalutation withInsideAddress(String insideAddress); } interface AddSalutation { Letter.AddBody withSalutation(String salutation); } interface AddBody { Letter withBody(String body); } }
repos\tutorials-master\patterns-modules\design-patterns-functional\src\main\java\com\baeldung\currying\Letter.java
1
请完成以下Java代码
public int getAD_Org_ID() { return AD_Org_ID; } @Override public void setAD_Org_ID(final int aD_Org_ID) { AD_Org_ID = aD_Org_ID; } @Override public int getAD_User_ID() { return AD_User_ID; } @Override public void setAD_User_ID(final int aD_User_ID) { AD_User_ID = aD_User_ID; } @Override public int getIgnoreC_Printing_Queue_ID() { return ignoreC_Printing_Queue_ID; } @Override public void setIgnoreC_Printing_Queue_ID(final int ignoreC_Printing_Queue_ID) { this.ignoreC_Printing_Queue_ID = ignoreC_Printing_Queue_ID; } @Override public int getModelTableId() { return modelTableId; } @Override public void setModelTableId(int modelTableId) { this.modelTableId = modelTableId; } @Override public int getModelFromRecordId() { return modelFromRecordId; } @Override public void setModelFromRecordId(int modelFromRecordId) { this.modelFromRecordId = modelFromRecordId; } @Override public int getModelToRecordId() { return modelToRecordId; } @Override public void setModelToRecordId(int modelToRecordId) { this.modelToRecordId = modelToRecordId; }
@Override public ISqlQueryFilter getFilter() { return filter; } @Override public void setFilter(ISqlQueryFilter filter) { this.filter = filter; } @Override public ISqlQueryFilter getModelFilter() { return modelFilter; } @Override public void setModelFilter(ISqlQueryFilter modelFilter) { this.modelFilter = modelFilter; } @Override public Access getRequiredAccess() { return requiredAccess; } @Override public void setRequiredAccess(final Access requiredAccess) { this.requiredAccess = requiredAccess; } @Override public Integer getCopies() { return copies; } @Override public void setCopies(int copies) { this.copies = copies; } @Override public String getAggregationKey() { return aggregationKey; } @Override public void setAggregationKey(final String aggregationKey) { this.aggregationKey=aggregationKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java
1
请完成以下Java代码
private final Object aggregateNewParentValue(final IAttributeAggregationStrategy aggregationStrategy, final IAttributeStorage parentAttributeSet, final Object parentValueInitial, final IAttributeStorage attributeSet, final Object value, final I_M_Attribute attribute) { Object parentValueNew = parentValueInitial; // Run through all current level attribute sets (including the one from parameters) and aggregate each to the current value final boolean loadIfNeeded = true; final Collection<IAttributeStorage> sameLevelAttributeSets = parentAttributeSet.getChildAttributeStorages(loadIfNeeded); for (final IAttributeStorage levelAttributeSet : sameLevelAttributeSets) { // // Do not try to aggregate from a storage which doesn't have that attribute. instead, try it's children if (!levelAttributeSet.hasAttribute(attribute)) { parentValueNew = aggregateNewParentValue(aggregationStrategy, levelAttributeSet, parentValueNew, attributeSet, value, attribute); continue; } // // For the same-level attribute set, aggregate the given value and skip recalculation if (levelAttributeSet.getId().equals(attributeSet.getId())) {
parentValueNew = aggregationStrategy.aggregate(attribute, parentValueNew, value); } // // For the others, just aggregate their value else { final Object levelAttributeValue = levelAttributeSet.getValue(attribute); parentValueNew = aggregationStrategy.aggregate(attribute, parentValueNew, levelAttributeValue); } } return parentValueNew; } @Override public String toString() { return "BottomUpHUAttributePropagator []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\BottomUpHUAttributePropagator.java
1
请在Spring Boot框架中完成以下Java代码
class CurrencyConversionTypeRouting { @NonNull ClientId clientId; @NonNull OrgId orgId; @NonNull Instant validFrom; @NonNull CurrencyConversionTypeId conversionTypeId; public boolean isMatching( @NonNull final ClientId clientId, @NonNull final OrgId orgId, @NonNull final Instant date) { return (this.clientId.isSystem() || ClientId.equals(this.clientId, clientId)) && (this.orgId.isAny() || OrgId.equals(this.orgId, orgId)) && this.validFrom.compareTo(date) <= 0; } public static Comparator<CurrencyConversionTypeRouting> moreSpecificFirstComparator() { return (routing1, routing2) -> { if (Objects.equals(routing1, routing2)) { return 0;
} else if (routing1.isMoreSpecificThan(routing2)) { return -1; } else { return +1; } }; } public boolean isMoreSpecificThan(@NonNull final CurrencyConversionTypeRouting other) { if (!ClientId.equals(this.getClientId(), other.getClientId())) { return this.getClientId().isRegular(); } if (!OrgId.equals(this.getOrgId(), other.getOrgId())) { return this.getOrgId().isRegular(); } return this.getValidFrom().compareTo(other.getValidFrom()) > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyConversionTypeRouting.java
2
请在Spring Boot框架中完成以下Java代码
public class MailController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private MailService mailService; @RequestMapping("/sendSimpleMail") public MailResult sendSimpleMail(String to, String subject, String content) { MailResult result=new MailResult(); if(StringUtils.isEmpty(to) || !to.contains("@")){ result.setRspCode("01"); result.setRspCode("手机人邮件格式不正确"); } if(StringUtils.isEmpty(content) ){ result.setRspCode("03");
result.setRspCode("邮件正文不能为空"); } try { mailService.sendSimpleMail(to,subject,content); logger.info("简单邮件已经发送。"); } catch (Exception e) { result.setRspCode("04"); result.setRspCode("邮件发送出现异常"); logger.error("sendSimpleMail Exception ", e); } return result; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 4-10 课:使用 Spring Boot 开发邮件系统\spring-boot-mail\src\main\java\com\neo\web\MailController.java
2
请完成以下Java代码
public abstract class AbstractTransactionInterceptor extends CommandInterceptor { protected final boolean requiresNew; protected ProcessEngineConfigurationImpl processEngineConfiguration; public AbstractTransactionInterceptor(boolean requiresNew, ProcessEngineConfigurationImpl processEngineConfiguration) { this.requiresNew = requiresNew; this.processEngineConfiguration = processEngineConfiguration; } @Override public <T> T execute(Command<T> command) { Object oldTx = null; try { boolean existing = isExisting(); boolean isNew = !existing || requiresNew; if (existing && requiresNew) { oldTx = doSuspend(); } if (isNew) { doBegin(); } T result; try { result = next.execute(command); } catch (RuntimeException ex) { doRollback(isNew); throw ex; } catch (Error err) { doRollback(isNew); throw err; } catch (Exception ex) { doRollback(isNew); throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception"); } if (isNew) { doCommit(); }
return result; } finally { doResume(oldTx); } } protected void handleRollbackException(Exception rollbackException) { throw new TransactionException("Unable to commit transaction", rollbackException); } protected abstract void doResume(Object oldTx); protected abstract void doCommit(); protected abstract void doRollback(boolean isNew); protected abstract void doBegin(); protected abstract Object doSuspend(); protected abstract boolean isExisting(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\AbstractTransactionInterceptor.java
1
请完成以下Java代码
public void setVersion (final int Version) { set_Value (COLUMNNAME_Version, Version); } @Override public int getVersion() { return get_ValueAsInt(COLUMNNAME_Version); } @Override public void setWaitingTime (final int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public int getWaitingTime() { return get_ValueAsInt(COLUMNNAME_WaitingTime); } /** * WorkflowType AD_Reference_ID=328 * Reference name: AD_Workflow Type */ public static final int WORKFLOWTYPE_AD_Reference_ID=328; /** General = G */ public static final String WORKFLOWTYPE_General = "G"; /** Document Process = P */ public static final String WORKFLOWTYPE_DocumentProcess = "P"; /** Document Value = V */ public static final String WORKFLOWTYPE_DocumentValue = "V"; /** Manufacturing = M */ public static final String WORKFLOWTYPE_Manufacturing = "M"; /** Quality = Q */ public static final String WORKFLOWTYPE_Quality = "Q"; /** Repair = R */ public static final String WORKFLOWTYPE_Repair = "R"; @Override public void setWorkflowType (final java.lang.String WorkflowType) { set_Value (COLUMNNAME_WorkflowType, WorkflowType); } @Override public java.lang.String getWorkflowType() { return get_ValueAsString(COLUMNNAME_WorkflowType); }
@Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow.java
1
请完成以下Java代码
public void setP_Msg (final @Nullable java.lang.String P_Msg) { set_ValueNoCheck (COLUMNNAME_P_Msg, P_Msg); } @Override public java.lang.String getP_Msg() { return get_ValueAsString(COLUMNNAME_P_Msg); } @Override public void setP_Number (final @Nullable BigDecimal P_Number) { set_ValueNoCheck (COLUMNNAME_P_Number, P_Number); } @Override public BigDecimal getP_Number() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_P_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override
public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setWarnings (final @Nullable java.lang.String Warnings) { set_Value (COLUMNNAME_Warnings, Warnings); } @Override public java.lang.String getWarnings() { return get_ValueAsString(COLUMNNAME_Warnings); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Log.java
1
请完成以下Java代码
public TenantRestService getTenantRestService(@PathParam("name") String engineName) { return super.getTenantRestService(engineName); } @Override @Path("/{name}" + SignalRestService.PATH) public SignalRestService getSignalRestService(@PathParam("name") String engineName) { return super.getSignalRestService(engineName); } @Override @Path("/{name}" + ConditionRestService.PATH) public ConditionRestService getConditionRestService(@PathParam("name") String engineName) { return super.getConditionRestService(engineName); } @Path("/{name}" + OptimizeRestService.PATH) public OptimizeRestService getOptimizeRestService(@PathParam("name") String engineName) { return super.getOptimizeRestService(engineName); } @Path("/{name}" + VersionRestService.PATH) public VersionRestService getVersionRestService(@PathParam("name") String engineName) { return super.getVersionRestService(engineName); } @Path("/{name}" + SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) { return super.getSchemaLogRestService(engineName); } @Override @Path("/{name}" + EventSubscriptionRestService.PATH) public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) { return super.getEventSubscriptionRestService(engineName); } @Override @Path("/{name}" + TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) { return super.getTelemetryRestService(engineName); }
@GET @Produces(MediaType.APPLICATION_JSON) public List<ProcessEngineDto> getProcessEngineNames() { ProcessEngineProvider provider = getProcessEngineProvider(); Set<String> engineNames = provider.getProcessEngineNames(); List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>(); for (String engineName : engineNames) { ProcessEngineDto dto = new ProcessEngineDto(); dto.setName(engineName); results.add(dto); } return results; } @Override protected URI getRelativeEngineUri(String engineName) { return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public Optional<LocatorId> suggestAfterPickingLocatorId(@NonNull final WarehouseId warehouseId) { for (final I_M_Locator huCurrentLocator : warehouseDAO.getLocators(warehouseId, I_M_Locator.class)) { if (!huCurrentLocator.isActive()) { continue; } if (huCurrentLocator.isAfterPickingLocator()) { return Optional.of(LocatorId.ofRepoId(huCurrentLocator.getM_Warehouse_ID(), huCurrentLocator.getM_Locator_ID())); } } // no after-picking locator was found => return null return Optional.empty(); } @Override @NonNull public WarehouseId retrieveFirstQualityReturnWarehouseId() { final Set<WarehouseId> warehouseIds = retrieveQualityReturnWarehouseIds();
return warehouseIds.iterator().next(); } private Set<WarehouseId> retrieveQualityReturnWarehouseIds() { final Set<WarehouseId> warehouseIds = queryBL.createQueryBuilderOutOfTrx(de.metas.handlingunits.model.I_M_Warehouse.class) .addEqualsFilter(de.metas.handlingunits.model.I_M_Warehouse.COLUMNNAME_IsQualityReturnWarehouse, true) .addOnlyActiveRecordsFilter() .create() .idsAsSet(WarehouseId::ofRepoId); if (warehouseIds.isEmpty()) { throw new AdempiereException(MSG_NoQualityWarehouse); } return warehouseIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUWarehouseDAO.java
1
请完成以下Java代码
private static Object getProperty( @NonNull final MultiBucketsAggregation.Bucket bucket, @NonNull final String containingAggName, @NonNull final List<String> path) { Check.assumeNotEmpty(path, "path shall not be empty"); final Aggregations aggregations = bucket.getAggregations(); final String aggName = path.get(0); final Aggregation aggregation = aggregations.get(aggName); if (aggregation == null) { throw new InvalidAggregationPathException("Cannot find an aggregation named [" + aggName + "] in [" + containingAggName + "]"); } else if (aggregation instanceof InternalAggregation) { final InternalAggregation internalAggregation = (InternalAggregation)aggregation; return internalAggregation.getProperty(path.subList(1, path.size())); } else if (aggregation instanceof NumericMetricsAggregation.SingleValue) { final NumericMetricsAggregation.SingleValue singleValue = (NumericMetricsAggregation.SingleValue)aggregation; final List<String> subPath = path.subList(1, path.size()); if (subPath.size() == 1 && "value".equals(subPath.get(0)))
{ return singleValue.value(); } else { throw new AdempiereException("Cannot extract " + path + " from " + singleValue); } } else { throw new AdempiereException("Unknown aggregation type " + aggregation.getClass() + " for " + aggregation); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\elasticsearch\ElasticsearchDatasourceFieldDescriptor.java
1
请完成以下Java代码
public void setCopy(final boolean isCopy) { m_isCopy = isCopy; } // setCopy /************************************************************************** * Get the doc flavor (Doc Interface) * * @return SERVICE_FORMATTED.PAGEABLE */ @Override public DocFlavor getDocFlavor() { return DocFlavor.SERVICE_FORMATTED.PAGEABLE; } // getDocFlavor /** * Get Print Data (Doc Interface) * * @return this * @throws IOException */ @Override public Object getPrintData() throws IOException { return this; } // getPrintData /** * Get Document Attributes (Doc Interface) * * @return null to obtain all attribute values from the * job's attribute set. */ @Override public DocAttributeSet getAttributes() { return null; } // getAttributes /** * Obtains a reader for extracting character print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public Reader getReaderForText() throws IOException { return null; } // getReaderForText
/** * Obtains an input stream for extracting byte print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public InputStream getStreamForBytes() throws IOException { return null; } // getStreamForBytes public void setPrintInfo(final ArchiveInfo info) { m_PrintInfo = info; } /** * @return PrintInfo */ public ArchiveInfo getPrintInfo() { return m_PrintInfo; } } // LayoutEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\LayoutEngine.java
1
请完成以下Java代码
public Set<OrderDetail> eagerLoaded() { final Session sessionEager = HibernateUtil.getHibernateSession(); // data should be loaded in the following line // also note the queries generated List<UserEager> user = sessionEager.createQuery("From UserEager").list(); UserEager userEagerLoaded = user.get(0); return userEagerLoaded.getOrderDetail(); } // creates test data // call this method to create the data in the database public void createTestData() { final Session session = HibernateUtil.getHibernateSession("lazy"); Transaction tx = session.beginTransaction(); final UserLazy user1 = new UserLazy(); final UserLazy user2 = new UserLazy(); final UserLazy user3 = new UserLazy(); session.save(user1); session.save(user2); session.save(user3);
final OrderDetail order1 = new OrderDetail(); final OrderDetail order2 = new OrderDetail(); final OrderDetail order3 = new OrderDetail(); final OrderDetail order4 = new OrderDetail(); final OrderDetail order5 = new OrderDetail(); session.saveOrUpdate(order1); session.saveOrUpdate(order2); session.saveOrUpdate(order3); session.saveOrUpdate(order4); session.saveOrUpdate(order5); tx.commit(); session.close(); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\fetching\view\FetchingAppView.java
1
请完成以下Java代码
public void setTabEnabled(final int tabIndex, final boolean enabled) { tabEnabledMap.put(tabIndex, enabled); } @Override public boolean isTabEnabled(final int tabIndex) { final Boolean enabled = tabEnabledMap.get(tabIndex); return enabled == Boolean.TRUE || enabled == null; // null is also true } @Override public int getTabIndexEffective(final int tabIndex) { int tabIndexToUse = tabIndex; for (final Integer tabIndexEnabled : tabEnabledMap.keySet()) { if (tabIndexEnabled > tabIndex) // note that we must go one additional step (i.e first tab) { return tabIndexToUse; // we shall not go over the tab we're searching for
} if (!isTabEnabled(tabIndexEnabled)) // if tab is not enabled before, then assume an earlier tab (one position before)) { tabIndexToUse--; } } return tabIndexToUse; } @Override public void initializeTab(final Runnable initializeTabRunnable, final int tabIndex) { final Boolean enabled = isTabEnabled(tabIndex); if (enabled) { initializeTabRunnable.run(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\history\impl\DefaultInvoiceHistoryTabHandler.java
1
请完成以下Java代码
public void onSuccess(TbQueueMsgMetadata metadata) { log.trace("Submitted Housekeeper task"); } @Override public void onFailure(Throwable t) { log.error("Failed to submit Housekeeper task", t); } }; } @Override public void submitTask(HousekeeperTask task) { HousekeeperTaskType taskType = task.getTaskType(); if (config.getDisabledTaskTypes().contains(taskType)) { log.trace("Task type {} is disabled, ignoring {}", taskType, task); return; } log.debug("[{}][{}][{}] Submitting task: {}", task.getTenantId(), task.getEntityId().getEntityType(), task.getEntityId(), task); /* * using msg key as entity id so that msgs related to certain entity are pushed to same partition,
* e.g. on tenant deletion (entity id is tenant id), we need to clean up tenant entities in certain order * */ try { producer.send(submitTpi, new TbProtoQueueMsg<>(task.getEntityId().getId(), ToHousekeeperServiceMsg.newBuilder() .setTask(TransportProtos.HousekeeperTaskProto.newBuilder() .setValue(JacksonUtil.toString(task)) .setTs(task.getTs()) .setAttempt(0) .build()) .build()), submitCallback); } catch (Throwable t) { log.error("Failed to submit Housekeeper task {}", task, t); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\housekeeper\DefaultHousekeeperClient.java
1
请完成以下Java代码
public boolean supports(AuthenticationToken token) { return token instanceof JWTToken; } /** * ` * 授权模块,获取用户角色和权限 * * @param token token * @return AuthorizationInfo 权限信息 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) { String username = JWTUtil.getUsername(token.toString()); User user = SystemUtils.getUser(username); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); // 获取用户角色集(模拟值,实际从数据库获取) simpleAuthorizationInfo.setRoles(user.getRole()); // 获取用户权限集(模拟值,实际从数据库获取) simpleAuthorizationInfo.setStringPermissions(user.getPermission()); return simpleAuthorizationInfo; } /** * 用户认证 * * @param authenticationToken 身份认证 token * @return AuthenticationInfo 身份认证信息 * @throws AuthenticationException 认证相关异常 */
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的,已经经过了解密 String token = (String) authenticationToken.getCredentials(); String username = JWTUtil.getUsername(token); if (StringUtils.isBlank(username)) throw new AuthenticationException("token校验不通过"); // 通过用户名查询用户信息 User user = SystemUtils.getUser(username); if (user == null) throw new AuthenticationException("用户名或密码错误"); if (!JWTUtil.verify(token, username, user.getPassword())) throw new AuthenticationException("token校验不通过"); return new SimpleAuthenticationInfo(token, token, "shiro_realm"); } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\ShiroRealm.java
1
请在Spring Boot框架中完成以下Java代码
public class ManufacturingJobActivityId implements RepoIdAware { int repoId; private ManufacturingJobActivityId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } @JsonCreator @NonNull public static ManufacturingJobActivityId ofRepoId(final int repoId) {return new ManufacturingJobActivityId(repoId);} @Nullable public static ManufacturingJobActivityId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? ofRepoId(repoId) : null;}
public static ManufacturingJobActivityId of(final PPOrderRoutingActivityId ppOrderRoutingActivityId) {return ofRepoId(ppOrderRoutingActivityId.getRepoId());} public static int toRepoId(@Nullable final ManufacturingJobActivityId id) {return id != null ? id.getRepoId() : -1;} @Override @JsonValue public int getRepoId() {return repoId;} public static boolean equals(@Nullable final ManufacturingJobActivityId id1, @Nullable final ManufacturingJobActivityId id2) {return Objects.equals(id1, id2);} public PPOrderRoutingActivityId toPPOrderRoutingActivityId(final PPOrderId ppOrderId) { return PPOrderRoutingActivityId.ofRepoId(ppOrderId, getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobActivityId.java
2
请完成以下Java代码
public String getStringRepresentation() { return stringRepresentation; } public void setStringRepresentation(String stringRepresentation) { this.stringRepresentation = stringRepresentation; } @Override public boolean equals(Object obj) { if (! (obj instanceof GeodbObject)) return false; if (this == obj) return true;
// GeodbObject go = (GeodbObject)obj; return this.geodb_loc_id == go.geodb_loc_id && this.zip.equals(go.zip) ; } @Override public String toString() { String str = getStringRepresentation(); if (str != null) return str; return city+", "+zip+" - "+countryName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\GeodbObject.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Form getAD_Form() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Form_ID, org.compiere.model.I_AD_Form.class); } @Override public void setAD_Form(org.compiere.model.I_AD_Form AD_Form) { set_ValueFromPO(COLUMNNAME_AD_Form_ID, org.compiere.model.I_AD_Form.class, AD_Form); } /** Set Special Form. @param AD_Form_ID Special Form */ @Override public void setAD_Form_ID (int AD_Form_ID) { if (AD_Form_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Form_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Form_ID, Integer.valueOf(AD_Form_ID)); } /** Get Special Form. @return Special Form */ @Override public int getAD_Form_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Form_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class); } @Override public void setAD_Role(org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } /** Set Rolle. @param AD_Role_ID Responsibility Role */ @Override public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form_Access.java
1
请在Spring Boot框架中完成以下Java代码
public GetAuth createGetAuth() { return new GetAuth(); } /** * Create an instance of {@link GetAuthResponse } * */ public GetAuthResponse createGetAuthResponse() { return new GetAuthResponse(); } /** * Create an instance of {@link LoginException } * */ public LoginException createLoginException() { return new LoginException(); } /** * Create an instance of {@link Login } * */ public Login createLogin() { return new Login(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAuth }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link GetAuth }{@code >} */
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "getAuth") public JAXBElement<GetAuth> createGetAuth(GetAuth value) { return new JAXBElement<GetAuth>(_GetAuth_QNAME, GetAuth.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetAuthResponse }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link GetAuthResponse }{@code >} */ @XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "getAuthResponse") public JAXBElement<GetAuthResponse> createGetAuthResponse(GetAuthResponse value) { return new JAXBElement<GetAuthResponse>(_GetAuthResponse_QNAME, GetAuthResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LoginException }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link LoginException }{@code >} */ @XmlElementDecl(namespace = "http://dpd.com/common/service/types/LoginService/2.0", name = "LoginException") public JAXBElement<LoginException> createLoginException(LoginException value) { return new JAXBElement<LoginException>(_LoginException_QNAME, LoginException.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\ObjectFactory.java
2
请完成以下Java代码
public class JarFilePathResolver { public String getJarFilePath(Class clazz) { try { return byGetProtectionDomain(clazz); } catch (Exception e) { // cannot get jar file path using byGetProtectionDomain // Exception handling omitted } return byGetResource(clazz); } String byGetProtectionDomain(Class clazz) throws URISyntaxException { URL url = clazz.getProtectionDomain().getCodeSource().getLocation(); return Paths.get(url.toURI()).toString(); } String byGetResource(Class clazz) {
final URL classResource = clazz.getResource(clazz.getSimpleName() + ".class"); if (classResource == null) { throw new RuntimeException("class resource is null"); } final String url = classResource.toString(); if (url.startsWith("jar:file:")) { // extract 'file:......jarName.jar' part from the url string String path = url.replaceAll("^jar:(file:.*[.]jar)!/.*", "$1"); try { return Paths.get(new URI(path)).toString(); } catch (Exception e) { throw new RuntimeException("Invalid Jar File URL String"); } } throw new RuntimeException("Invalid Jar File URL String"); } }
repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\jarfile\JarFilePathResolver.java
1
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { if (!success) { return success; } if (newRecord) { // Info Services.get(IOrgDAO.class).createOrUpdateOrgInfo(OrgInfoUpdateRequest.builder() .orgId(OrgId.ofRepoId(getAD_Org_ID())) .build()); // TreeNode // insert_Tree(MTree_Base.TREETYPE_Organization); } // Value/Name change if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) { MAccount.updateValueDescription(getCtx(), "AD_Org_ID=" + getAD_Org_ID(), get_TrxName()); final String elementOrgTrx = Env.CTXNAME_AcctSchemaElementPrefix + X_C_AcctSchema_Element.ELEMENTTYPE_OrgTrx; if ("Y".equals(Env.getContext(getCtx(), elementOrgTrx))) { MAccount.updateValueDescription(getCtx(), "AD_OrgTrx_ID=" + getAD_Org_ID(), get_TrxName()); } } return true; } // afterSave /**
* Get Linked BPartner * @return C_BPartner_ID */ public int getLinkedC_BPartner_ID(String trxName) { if (m_linkedBPartner == null) { int C_BPartner_ID = DB.getSQLValue(trxName, "SELECT C_BPartner_ID FROM C_BPartner WHERE AD_OrgBP_ID=?", getAD_Org_ID()); if (C_BPartner_ID < 0) { C_BPartner_ID = 0; } m_linkedBPartner = new Integer (C_BPartner_ID); } return m_linkedBPartner.intValue(); } // getLinkedC_BPartner_ID } // MOrg
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MOrg.java
1
请在Spring Boot框架中完成以下Java代码
public RecordMessageConverter multiTypeConverter() { StringJsonMessageConverter converter = new StringJsonMessageConverter(); DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); typeMapper.setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence.TYPE_ID); typeMapper.addTrustedPackages("com.baeldung.spring.kafka"); Map<String, Class<?>> mappings = new HashMap<>(); mappings.put("greeting", Greeting.class); mappings.put("farewell", Farewell.class); typeMapper.setIdClassMapping(mappings); converter.setTypeMapper(typeMapper); return converter; } @Bean public ConsumerFactory<String, Object> multiTypeConsumerFactory() { HashMap<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); props.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id_test"); return new DefaultKafkaConsumerFactory<>(props); } @Bean
@Primary public ConcurrentKafkaListenerContainerFactory<String, Object> greetingKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(multiTypeConsumerFactory()); factory.setCommonErrorHandler(errorHandler()); factory.getContainerProperties() .setAckMode(ContainerProperties.AckMode.RECORD); return factory; } @Bean public DefaultErrorHandler errorHandler() { BackOff fixedBackOff = new FixedBackOff(interval, maxAttempts); DefaultErrorHandler errorHandler = new DefaultErrorHandler((consumerRecord, e) -> { System.out.println(String.format("consumed record %s because this exception was thrown",consumerRecord.toString(),e.getClass().getName())); }, fixedBackOff); //Commented because of the test //errorHandler.addRetryableExceptions(SocketTimeoutException.class,RuntimeException.class); errorHandler.addNotRetryableExceptions(NullPointerException.class); return errorHandler; } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\retryable\KafkaConsumerConfig.java
2
请完成以下Java代码
public BatchDto getBatch() { Batch batch = processEngine.getManagementService() .createBatchQuery() .batchId(batchId) .singleResult(); if (batch == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Batch with id '" + batchId + "' does not exist"); } return BatchDto.fromBatch(batch); } public void updateSuspensionState(SuspensionStateDto suspensionState) { if (suspensionState.getSuspended()) { suspendBatch(); } else { activateBatch(); } } protected void suspendBatch() { try { processEngine.getManagementService().suspendBatchById(batchId); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to suspend batch with id '" + batchId + "'"); } } protected void activateBatch() {
try { processEngine.getManagementService().activateBatchById(batchId); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to activate batch with id '" + batchId + "'"); } } public void deleteBatch(boolean cascade) { try { processEngine.getManagementService() .deleteBatch(batchId, cascade); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to delete batch with id '" + batchId + "'"); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\batch\impl\BatchResourceImpl.java
1
请完成以下Java代码
private static Properties propertiesDecode (String data) { String result = null; // System.out.println("String=" + data); try { result = URLDecoder.decode(data, WebEnv.ENCODING); } catch (UnsupportedEncodingException e) { log.error("decode" + WebEnv.ENCODING, e); String enc = System.getProperty("file.encoding"); // Windows default is Cp1252 try { result = URLEncoder.encode(data, enc); log.error("decode: " + enc); } catch (Exception ex) { log.error("decode", ex); } }
// System.out.println("String-Decoded=" + result); ByteArrayInputStream bis = new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)); Properties pp = new Properties(); try { pp.load(bis); } catch (IOException e) { log.error("load", e); } return pp; } // propertiesDecode }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\util\WebUtil.java
1
请完成以下Java代码
public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } @Override public String getCaseDefinitionKey() { return caseDefinitionKey; } @Override public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } @Override public String getCaseDefinitionName() { return caseDefinitionName; } @Override public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName; } @Override public Integer getCaseDefinitionVersion() { return caseDefinitionVersion; }
@Override public void setCaseDefinitionVersion(Integer caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } @Override public String getCaseDefinitionDeploymentId() { return caseDefinitionDeploymentId; } @Override public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) { this.caseDefinitionDeploymentId = caseDefinitionDeploymentId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricCaseInstance[id=").append(id) .append(", caseDefinitionId=").append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public ClientSecurityProperties getClient() { return this.client; } public SecurityLogProperties getLog() { return this.securityLogProperties; } public SecurityManagerProperties getManager() { return this.securityManagerProperties; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public PeerSecurityProperties getPeer() { return this.peer; } public SecurityPostProcessorProperties getPostProcessor() { return this.securityPostProcessorProperties; } public String getPropertiesFile() { return this.propertiesFile; } public void setPropertiesFile(String propertiesFile) { this.propertiesFile = propertiesFile; } public ApacheShiroProperties getShiro() { return this.apacheShiroProperties; } public SslProperties getSsl() { return this.ssl; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public static class ApacheShiroProperties { private String iniResourcePath; public String getIniResourcePath() { return this.iniResourcePath; } public void setIniResourcePath(String iniResourcePath) { this.iniResourcePath = iniResourcePath; } } public static class SecurityLogProperties {
private static final String DEFAULT_SECURITY_LOG_LEVEL = "config"; private String file; private String level = DEFAULT_SECURITY_LOG_LEVEL; public String getFile() { return this.file; } public void setFile(String file) { this.file = file; } public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } } public static class SecurityManagerProperties { private String className; public String getClassName() { return this.className; } public void setClassName(String className) { this.className = className; } } public static class SecurityPostProcessorProperties { private String className; public String getClassName() { return this.className; } public void setClassName(String className) { this.className = className; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SecurityProperties.java
2
请完成以下Java代码
private Stream<AdArchive> streamArchivesForFilter() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { // shall not happen return Stream.empty(); } else if (selectedRowIds.isAll()) { final Stream<? extends IViewRow> rowIdsStream = getView().streamByIds(selectedRowIds, getViewOrderBys(), QueryLimit.NO_LIMIT); return StreamUtils.dice(rowIdsStream, CHUNK_SIZE) // take CHUNK_SIZE Ids at one time and load their archives .flatMap(this::streamArchivesForRows); } else { final ImmutableList<DocOutboundLogId> ids = selectedRowIds.toIdsList(DocOutboundLogId::ofRepoId); return streamArchivesForLogIds(ids); } } private Stream<AdArchive> streamArchivesForRows(final List<? extends IViewRow> rows) { final ImmutableList<DocOutboundLogId> logIds = rows.stream() .map(row -> row.getId().toId(DocOutboundLogId::ofRepoId)) .collect(ImmutableList.toImmutableList()); return streamArchivesForLogIds(logIds); } private Stream<AdArchive> streamArchivesForLogIds(final ImmutableList<DocOutboundLogId> logIds) { return docOutboundDAO.streamByIdsInOrder(logIds) .filter(I_C_Doc_Outbound_Log::isActive) .map(log -> getLastArchive(log).orElse(null)) .filter(Objects::nonNull); } @NonNull private Optional<AdArchive> getLastArchive(final I_C_Doc_Outbound_Log log) { return archiveBL.getLastArchive(TableRecordReference.ofReferenced(log)); } private void appendCurrentPdf(final PdfCopy targetPdf, final AdArchive currentLog, final Collection<ArchiveId> printedIds, final AtomicInteger errorCount) { PdfReader pdfReaderToAdd = null; try { pdfReaderToAdd = new PdfReader(currentLog.getArchiveStream());
for (int page = 0; page < pdfReaderToAdd.getNumberOfPages(); ) { targetPdf.addPage(targetPdf.getImportedPage(pdfReaderToAdd, ++page)); } targetPdf.freeReader(pdfReaderToAdd); } catch (final BadPdfFormatException | IOException e) { errorCount.incrementAndGet(); } finally { if (pdfReaderToAdd != null) { pdfReaderToAdd.close(); } printedIds.add(currentLog.getId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.webui\src\main\java\de\metas\archive\process\MassConcatenateOutboundPdfs.java
1
请在Spring Boot框架中完成以下Java代码
public boolean meterNameEventTypeEnabled() { return obtain(NewRelicProperties::isMeterNameEventTypeEnabled, NewRelicConfig.super::meterNameEventTypeEnabled); } @Override public String eventType() { return obtain(NewRelicProperties::getEventType, NewRelicConfig.super::eventType); } @Override public ClientProviderType clientProviderType() { return obtain(NewRelicProperties::getClientProviderType, NewRelicConfig.super::clientProviderType); } @Override
public @Nullable String apiKey() { return get(NewRelicProperties::getApiKey, NewRelicConfig.super::apiKey); } @Override public @Nullable String accountId() { return get(NewRelicProperties::getAccountId, NewRelicConfig.super::accountId); } @Override public String uri() { return obtain(NewRelicProperties::getUri, NewRelicConfig.super::uri); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicPropertiesConfigAdapter.java
2
请完成以下Java代码
public static void main(String[] args) throws IOException { PdfReader reader = new PdfReader(SOURCE); PdfWriter writer = new PdfWriter(DESTINATION); PdfDocument pdfDocument = new PdfDocument(reader, writer); addContentToDocument(pdfDocument); } private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException { // 4.1. add form PdfFormField personal = PdfFormField.createEmptyField(pdfDocument); personal.setFieldName("information"); PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", ""); personal.addKid(name); PdfAcroForm.getAcroForm(pdfDocument, true) .addField(personal, pdfDocument.getFirstPage()); // 4.2. add new page pdfDocument.addNewPage(1); // 4.3. add annotation PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name")) .setContents("Your name"); pdfDocument.getPage(2) .addAnnotation(ann); // create document form pdf document Document document = new Document(pdfDocument); // 4.4. add an image ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png"); Image image = new Image(imageData).scaleAbsolute(550, 100)
.setFixedPosition(1, 10, 50); document.add(image); // 4.5. add a paragraph Text title = new Text("This is a demo").setFontSize(16); Text author = new Text("Baeldung tutorials."); Paragraph p = new Paragraph().setFontSize(8) .add(title) .add(" from ") .add(author); document.add(p); // 4.6. add a table Table table = new Table(UnitValue.createPercentArray(2)); table.addHeaderCell("#"); table.addHeaderCell("company"); table.addCell("name"); table.addCell("baeldung"); document.add(table); // close the document // this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter document.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf-2\src\main\java\com\baeldung\pdfedition\PdfEditor.java
1
请完成以下Java代码
public void addQtyToAllMatchingGroups(@NonNull final AddToResultGroupRequest request) { if (!isMatching(request)) { return; } boolean addedToAtLeastOneGroup = false; for (final AvailableForSaleResultGroupBuilder group : groups) { if (!isGroupMatching(group, request)) { continue; } if (!group.isAlreadyIncluded(request)) { group.addQty(request); } addedToAtLeastOneGroup = true; } if (!addedToAtLeastOneGroup) { final AttributesKey storageAttributesKey = storageAttributesKeyMatcher.toAttributeKeys(request.getStorageAttributesKey()); final AvailableForSaleResultGroupBuilder group = newGroup(request, storageAttributesKey); group.addQty(request); } } private boolean isGroupAttributesKeyMatching( @NonNull final AvailableForSaleResultGroupBuilder group, @NonNull final AttributesKey requestStorageAttributesKey) { final AttributesKey groupAttributesKey = group.getStorageAttributesKey(); if (groupAttributesKey.isAll()) { return true; } else if (groupAttributesKey.isOther()) { // accept it. We assume that the actual matching was done on Bucket level and not on Group level return true; } else if (groupAttributesKey.isNone()) { // shall not happen return false; } else { final AttributesKeyPattern groupAttributePattern = AttributesKeyPatternsUtil.ofAttributeKey(groupAttributesKey); return groupAttributePattern.matches(requestStorageAttributesKey); } } private AvailableForSaleResultGroupBuilder newGroup( @NonNull final AddToResultGroupRequest request, @NonNull final AttributesKey storageAttributesKey) { final AvailableForSaleResultGroupBuilder group = AvailableForSaleResultGroupBuilder.builder() .productId(request.getProductId()) .storageAttributesKey(storageAttributesKey) .warehouseId(request.getWarehouseId()) .build(); groups.add(group); return group;
} public void addDefaultEmptyGroupIfPossible() { if (product.isAny()) { return; } final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null); if (defaultAttributesKey == null) { return; } final WarehouseId warehouseId = warehouse.getWarehouseId(); if (warehouseId == null) { return; } final AvailableForSaleResultGroupBuilder group = AvailableForSaleResultGroupBuilder.builder() .productId(ProductId.ofRepoId(product.getProductId())) .storageAttributesKey(defaultAttributesKey) .warehouseId(warehouseId) .build(); groups.add(group); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSaleResultBucket.java
1
请完成以下Java代码
public void onSuccess(@Nullable Void result) { ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }; Futures.addCallback(future, futureCallback, ctx.getDbCallbackExecutor()); } else { List<ListenableFuture<Void>> futures = new ArrayList<>(); PageDataIterableByTenantIdEntityId<EdgeId> edgeIds = new PageDataIterableByTenantIdEntityId<>( ctx.getEdgeService()::findRelatedEdgeIdsByEntityId, ctx.getTenantId(), msg.getOriginator(), RELATED_EDGES_CACHE_ITEMS); for (EdgeId edgeId : edgeIds) { EdgeEvent edgeEvent = buildEvent(msg, ctx); futures.add(notifyEdge(ctx, edgeEvent, edgeId)); } if (futures.isEmpty()) { // ack in case no edges are related to provided entity ctx.ack(msg); } else { Futures.addCallback(Futures.allAsList(futures), new FutureCallback<>() {
@Override public void onSuccess(@Nullable List<Void> voids) { ctx.tellSuccess(msg); } @Override public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } }, ctx.getDbCallbackExecutor()); } } } catch (Exception e) { log.error("Failed to build edge event", e); ctx.tellFailure(msg, e); } } private ListenableFuture<Void> notifyEdge(TbContext ctx, EdgeEvent edgeEvent, EdgeId edgeId) { edgeEvent.setEdgeId(edgeId); return ctx.getEdgeEventService().saveAsync(edgeEvent); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\edge\TbMsgPushToEdgeNode.java
1
请完成以下Java代码
public void setEXP_ReplicationTrxLine_ID (int EXP_ReplicationTrxLine_ID) { if (EXP_ReplicationTrxLine_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrxLine_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_ReplicationTrxLine_ID, Integer.valueOf(EXP_ReplicationTrxLine_ID)); } /** Get Replikationstransaktionszeile. @return Replikationstransaktionszeile */ @Override public int getEXP_ReplicationTrxLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_ReplicationTrxLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue();
} /** * ReplicationTrxStatus AD_Reference_ID=540491 * Reference name: EXP_ReplicationTrxStatus */ public static final int REPLICATIONTRXSTATUS_AD_Reference_ID=540491; /** Vollständig = Completed */ public static final String REPLICATIONTRXSTATUS_Vollstaendig = "Completed"; /** Nicht vollständig importiert = ImportedWithIssues */ public static final String REPLICATIONTRXSTATUS_NichtVollstaendigImportiert = "ImportedWithIssues"; /** Fehler = Failed */ public static final String REPLICATIONTRXSTATUS_Fehler = "Failed"; /** Set Replikationsstatus. @param ReplicationTrxStatus Replikationsstatus */ @Override public void setReplicationTrxStatus (java.lang.String ReplicationTrxStatus) { set_Value (COLUMNNAME_ReplicationTrxStatus, ReplicationTrxStatus); } /** Get Replikationsstatus. @return Replikationsstatus */ @Override public java.lang.String getReplicationTrxStatus () { return (java.lang.String)get_Value(COLUMNNAME_ReplicationTrxStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrxLine.java
1
请完成以下Java代码
/* package */class ReceiptScheduleASIAware implements IAttributeSetInstanceAware { final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class); private final I_M_ReceiptSchedule rs; public ReceiptScheduleASIAware(@NonNull final I_M_ReceiptSchedule rs) { this.rs = rs; } @Override public I_M_Product getM_Product() { return loadOutOfTrx(rs.getM_Product_ID(), I_M_Product.class); } @Override public int getM_Product_ID() { return rs.getM_Product_ID(); } @Override public I_M_AttributeSetInstance getM_AttributeSetInstance() {
return Services.get(IReceiptScheduleBL.class).getM_AttributeSetInstance_Effective(rs); } @Override public int getM_AttributeSetInstance_ID() { return Services.get(IReceiptScheduleBL.class).getM_AttributeSetInstance_Effective_ID(rs); } @Override public void setM_AttributeSetInstance(@Nullable final I_M_AttributeSetInstance asi) { AttributeSetInstanceId asiId = asi == null ? AttributeSetInstanceId.NONE : AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID()); receiptScheduleBL.setM_AttributeSetInstance_Effective(rs, asiId); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(M_AttributeSetInstance_ID); receiptScheduleBL.setM_AttributeSetInstance_Effective(rs, asiId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleASIAware.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public String getOperateMan() { return operateMan; } public void setOperateMan(String operateMan) { this.operateMan = operateMan; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getOrderStatus() { return orderStatus; } public void setOrderStatus(Integer orderStatus) { this.orderStatus = orderStatus; } public String getNote() { return note;
} public void setNote(String note) { this.note = note; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", orderId=").append(orderId); sb.append(", operateMan=").append(operateMan); sb.append(", createTime=").append(createTime); sb.append(", orderStatus=").append(orderStatus); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderOperateHistory.java
1
请完成以下Java代码
public void setDistrict (final @Nullable java.lang.String District) { set_Value (COLUMNNAME_District, District); } @Override public java.lang.String getDistrict() { return get_ValueAsString(COLUMNNAME_District); } @Override public void setIsManual (final boolean IsManual) { set_Value (COLUMNNAME_IsManual, IsManual); } @Override public boolean isManual() { return get_ValueAsBoolean(COLUMNNAME_IsManual); } @Override public void setIsValidDPD (final boolean IsValidDPD) { set_Value (COLUMNNAME_IsValidDPD, IsValidDPD); } @Override public boolean isValidDPD() { return get_ValueAsBoolean(COLUMNNAME_IsValidDPD); } @Override public void setNonStdAddress (final boolean NonStdAddress) { set_Value (COLUMNNAME_NonStdAddress, NonStdAddress); } @Override public boolean isNonStdAddress() { return get_ValueAsBoolean(COLUMNNAME_NonStdAddress); } @Override public void setPostal (final @Nullable java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); }
@Override public void setPostal_Add (final @Nullable java.lang.String Postal_Add) { set_Value (COLUMNNAME_Postal_Add, Postal_Add); } @Override public java.lang.String getPostal_Add() { return get_ValueAsString(COLUMNNAME_Postal_Add); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setTownship (final @Nullable java.lang.String Township) { set_Value (COLUMNNAME_Township, Township); } @Override public java.lang.String getTownship() { return get_ValueAsString(COLUMNNAME_Township); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Postal.java
1
请完成以下Java代码
public void configure(TypeDefinitionRegistry registry) { Set<String> typeNames = findConnectionTypeNames(registry); if (!typeNames.isEmpty()) { registry.add(ObjectTypeDefinition.newObjectTypeDefinition() .name(PAGE_INFO_TYPE.getName()) .fieldDefinition(initFieldDefinition("hasPreviousPage", new NonNullType(BOOLEAN_TYPE))) .fieldDefinition(initFieldDefinition("hasNextPage", new NonNullType(BOOLEAN_TYPE))) .fieldDefinition(initFieldDefinition("startCursor", STRING_TYPE)) .fieldDefinition(initFieldDefinition("endCursor", STRING_TYPE)) .build()); typeNames.forEach((typeName) -> { String connectionTypeName = typeName + "Connection"; String edgeTypeName = typeName + "Edge"; registry.add(ObjectTypeDefinition.newObjectTypeDefinition() .name(connectionTypeName) .fieldDefinition(initFieldDefinition("edges", new ListType(new TypeName(edgeTypeName)))) .fieldDefinition(initFieldDefinition("pageInfo", new NonNullType(PAGE_INFO_TYPE))) .build()); registry.add(ObjectTypeDefinition.newObjectTypeDefinition() .name(edgeTypeName) .fieldDefinition(initFieldDefinition("cursor", new NonNullType(STRING_TYPE))) .fieldDefinition(initFieldDefinition("node", new NonNullType(new TypeName(typeName)))) .build()); }); } }
private static Set<String> findConnectionTypeNames(TypeDefinitionRegistry registry) { return Stream.concat( registry.types().values().stream(), registry.objectTypeExtensions().values().stream().flatMap(Collection::stream)) .filter((definition) -> definition instanceof ImplementingTypeDefinition) .flatMap((definition) -> { ImplementingTypeDefinition<?> typeDefinition = (ImplementingTypeDefinition<?>) definition; return typeDefinition.getFieldDefinitions().stream() .map((fieldDefinition) -> { Type<?> type = fieldDefinition.getType(); return (type instanceof NonNullType) ? ((NonNullType) type).getType() : type; }) .filter((type) -> type instanceof TypeName) .map((type) -> ((TypeName) type).getName()) .filter((name) -> name.endsWith("Connection")) .filter((name) -> registry.getTypeOrNull(name) == null) .map((name) -> name.substring(0, name.length() - "Connection".length())); }) .collect(Collectors.toCollection(LinkedHashSet::new)); } private FieldDefinition initFieldDefinition(String name, Type<?> returnType) { return FieldDefinition.newFieldDefinition().name(name).type(returnType).build(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\ConnectionTypeDefinitionConfigurer.java
1
请完成以下Java代码
public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; }
public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\UpdateTaskPayload.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(bestFitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(bestPosition); result = prime * result + Arrays.hashCode(particles); result = prime * result + ((random == null) ? 0 : random.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Swarm other = (Swarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness)) return false; if (!Arrays.equals(bestPosition, other.bestPosition)) return false; if (!Arrays.equals(particles, other.particles)) return false; if (random == null) { if (other.random != null) return false; } else if (!random.equals(other.random)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + ", random=" + random + "]"; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Swarm.java
1
请完成以下Java代码
public static class None extends Jar { @Override public @Nullable String getLauncherClassName() { return null; } @Override public boolean isExecutable() { return false; } } /** * Executable WAR layout. */ public static class War implements Layout { private static final Map<LibraryScope, String> SCOPE_LOCATION; static { Map<LibraryScope, String> locations = new HashMap<>(); locations.put(LibraryScope.COMPILE, "WEB-INF/lib/"); locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/"); locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/"); locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/"); SCOPE_LOCATION = Collections.unmodifiableMap(locations); } @Override public String getLauncherClassName() { return "org.springframework.boot.loader.launch.WarLauncher";
} @Override public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) { return SCOPE_LOCATION.get(scope); } @Override public String getClassesLocation() { return "WEB-INF/classes/"; } @Override public String getClasspathIndexFileLocation() { return "WEB-INF/classpath.idx"; } @Override public String getLayersIndexFileLocation() { return "WEB-INF/layers.idx"; } @Override public boolean isExecutable() { return true; } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(legacyItemId, legacyTransactionId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LegacyReference {\n"); sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n"); sb.append(" legacyTransactionId: ").append(toIndentedString(legacyTransactionId)).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(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\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LegacyReference.java
2
请完成以下Java代码
public class CompletePlanItemInstanceOperation extends AbstractMovePlanItemInstanceToTerminalStateOperation { public CompletePlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { super(commandContext, planItemInstanceEntity); } @Override public String getNewState() { return PlanItemInstanceState.COMPLETED; } @Override public String getLifeCycleTransition() { return PlanItemTransition.COMPLETE; } @Override public boolean isEvaluateRepetitionRule() { return true; } @Override protected boolean shouldAggregateForSingleInstance() { return true; } @Override protected boolean shouldAggregateForMultipleInstances() { return true; } @Override protected void internalExecute() { if (isStage(planItemInstanceEntity)) { // terminate any remaining child plan items (e.g. in enabled / available state), but don't complete them as it might lead
// into wrong behavior resulting from it (e.g. triggering some follow-up actions on that completion event) and it will leave // such implicitly completed plan items in complete state, although they were never explicitly completed exitChildPlanItemInstances(PlanItemTransition.COMPLETE, null, null); // create stage ended with completion state event FlowableEventDispatcher eventDispatcher = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableCmmnEventBuilder.createStageEndedEvent(getCaseInstance(), planItemInstanceEntity, FlowableCaseStageEndedEvent.ENDING_STATE_COMPLETED), EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } } planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext)); planItemInstanceEntity.setCompletedTime(planItemInstanceEntity.getEndedTime()); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceCompleted(planItemInstanceEntity); } @Override protected Map<String, String> getAsyncLeaveTransitionMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId()); return metadata; } @Override public String getOperationName() { return "[Complete plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\CompletePlanItemInstanceOperation.java
1
请完成以下Java代码
public void setW_Inventory_Acct (int W_Inventory_Acct) { set_Value (COLUMNNAME_W_Inventory_Acct, Integer.valueOf(W_Inventory_Acct)); } /** Get (Not Used). @return Warehouse Inventory Asset Account - Currently not used */ public int getW_Inventory_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Inventory_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getW_Revaluation_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getW_Revaluation_Acct(), get_TrxName()); } /** Set Inventory Revaluation. @param W_Revaluation_Acct
Account for Inventory Revaluation */ public void setW_Revaluation_Acct (int W_Revaluation_Acct) { set_Value (COLUMNNAME_W_Revaluation_Acct, Integer.valueOf(W_Revaluation_Acct)); } /** Get Inventory Revaluation. @return Account for Inventory Revaluation */ public int getW_Revaluation_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Acct.java
1
请在Spring Boot框架中完成以下Java代码
static class OracleUcp { @Bean static OracleUcpJdbcConnectionDetailsBeanPostProcessor oracleUcpJdbcConnectionDetailsBeanPostProcessor( ObjectProvider<JdbcConnectionDetails> connectionDetailsProvider) { return new OracleUcpJdbcConnectionDetailsBeanPostProcessor(connectionDetailsProvider); } @Bean @ConfigurationProperties("spring.datasource.oracleucp") PoolDataSourceImpl dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) throws SQLException { PoolDataSourceImpl dataSource = createDataSource(connectionDetails, PoolDataSourceImpl.class, properties.getClassLoader()); if (StringUtils.hasText(properties.getName())) { dataSource.setConnectionPoolName(properties.getName()); } return dataSource; } }
/** * Generic DataSource configuration. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(DataSource.class) @ConditionalOnProperty(name = "spring.datasource.type") static class Generic { @Bean DataSource dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) { return createDataSource(connectionDetails, properties.getType(), properties.getClassLoader()); } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceConfiguration.java
2
请完成以下Java代码
String getGeoLocation(String remoteAddr) { try { CityResponse city = this.reader.city(InetAddress.getByName(remoteAddr)); String cityName = city.getCity().getName(); String countryName = city.getCountry().getName(); if (cityName == null && countryName == null) { return null; } else if (cityName == null) { return countryName; } else if (countryName == null) { return cityName; } return cityName + ", " + countryName; } catch (Exception ex) {
return UNKNOWN; } } private String getRemoteAddress(HttpServletRequest request) { String remoteAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteAddr == null) { remoteAddr = request.getRemoteAddr(); } else if (remoteAddr.contains(",")) { remoteAddr = remoteAddr.split(",")[0]; } return remoteAddr; } } // end::class[]
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-findbyusername\src\main\java\sample\session\SessionDetailsFilter.java
1
请完成以下Java代码
public class X_AD_User_MKTG_Channels extends org.compiere.model.PO implements I_AD_User_MKTG_Channels, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1439654629L; /** Standard Constructor */ public X_AD_User_MKTG_Channels (final Properties ctx, final int AD_User_MKTG_Channels_ID, @Nullable final String trxName) { super (ctx, AD_User_MKTG_Channels_ID, trxName); } /** Load Constructor */ public X_AD_User_MKTG_Channels (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_MKTG_Channels_ID (final int AD_User_MKTG_Channels_ID) { if (AD_User_MKTG_Channels_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, AD_User_MKTG_Channels_ID); }
@Override public int getAD_User_MKTG_Channels_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_MKTG_Channels_ID); } @Override public de.metas.marketing.base.model.I_MKTG_Channel getMKTG_Channel() { return get_ValueAsPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class); } @Override public void setMKTG_Channel(final de.metas.marketing.base.model.I_MKTG_Channel MKTG_Channel) { set_ValueFromPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class, MKTG_Channel); } @Override public void setMKTG_Channel_ID (final int MKTG_Channel_ID) { if (MKTG_Channel_ID < 1) set_Value (COLUMNNAME_MKTG_Channel_ID, null); else set_Value (COLUMNNAME_MKTG_Channel_ID, MKTG_Channel_ID); } @Override public int getMKTG_Channel_ID() { return get_ValueAsInt(COLUMNNAME_MKTG_Channel_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_AD_User_MKTG_Channels.java
1
请在Spring Boot框架中完成以下Java代码
public void setDirectory(DirectoryProperties[] directoryProperties) { this.directoryProperties = directoryProperties; } public float getDiskUsageCriticalPercentage() { return this.diskUsageCriticalPercentage; } public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) { this.diskUsageCriticalPercentage = diskUsageCriticalPercentage; } public float getDiskUsageWarningPercentage() { return this.diskUsageWarningPercentage; } public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) { this.diskUsageWarningPercentage = diskUsageWarningPercentage; } public long getMaxOplogSize() { return this.maxOplogSize; } public void setMaxOplogSize(long maxOplogSize) { this.maxOplogSize = maxOplogSize; }
public int getQueueSize() { return this.queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public long getTimeInterval() { return this.timeInterval; } public void setTimeInterval(long timeInterval) { this.timeInterval = timeInterval; } public int getWriteBufferSize() { return this.writeBufferSize; } public void setWriteBufferSize(int writeBufferSize) { this.writeBufferSize = writeBufferSize; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java
2