instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public BatchQuery tenantIdLike(String tenantIdLike) { if (tenantIdLike == null) { throw new FlowableIllegalArgumentException("Provided tenant id is null"); } this.tenantIdLike = tenantIdLike; return this; } @Override public BatchQuery withoutTenantId() { this.withoutTenantId = true; return this; } // sorting ////////////////////////////////////////// @Override public BatchQuery orderByBatchCreateTime() { return orderBy(BatchQueryProperty.CREATETIME); } @Override public BatchQuery orderByBatchId() { return orderBy(BatchQueryProperty.BATCH_ID); } @Override public BatchQuery orderByBatchTenantId() { return orderBy(BatchQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return batchServiceConfiguration.getBatchEntityManager().findBatchCountByQueryCriteria(this); } @Override public List<Batch> executeList(CommandContext commandContext) { return batchServiceConfiguration.getBatchEntityManager().findBatchesByQueryCriteria(this); } @Override public void delete() { if (commandExecutor != null) { commandExecutor.execute(context -> { executeDelete(context); return null; }); } else { executeDelete(Context.getCommandContext()); } } protected void executeDelete(CommandContext commandContext) { batchServiceConfiguration.getBatchEntityManager().deleteBatches(this);
} @Override @Deprecated public void deleteWithRelatedData() { delete(); } // getters ////////////////////////////////////////// @Override public String getId() { return id; } public String getBatchType() { return batchType; } public Collection<String> getBatchTypes() { return batchTypes; } public String getSearchKey() { return searchKey; } public String getSearchKey2() { return searchKey2; } public Date getCreateTimeHigherThan() { return createTimeHigherThan; } public Date getCreateTimeLowerThan() { return createTimeLowerThan; } public String getStatus() { return status; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
2
请完成以下Java代码
private void assertValueIsTypeMatch(BeanWrapper beanWrapper, String fieldName, Object value) { PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName); Supplier<String> typeMismatchExceptionMessageSupplier = () -> String.format("Value [%1$s] of type [%2$s] does not match field [%3$s] of type [%4$s] on Object [%5$s]", value, ObjectUtils.nullSafeClassName(value), fieldName, property.getPropertyType().getName(), getClassName()); assertCondition(isTypeMatch(property, value), () -> new PdxFieldTypeMismatchException(typeMismatchExceptionMessageSupplier.get())); } private boolean isTypeMatch(PropertyDescriptor property, Object value) { return value == null || property.getPropertyType().isInstance(value); } @Override public String getClassName() { return getParent().getClassName(); } @Override public boolean isDeserializable() { return getParent().isDeserializable(); } @Override public boolean isEnum() { return getParent().isEnum(); } @Override public Object getField(String fieldName) { return getParent().getField(fieldName); } @Override public List<String> getFieldNames() { return getParent().getFieldNames(); } @Override public boolean isIdentityField(String fieldName) { return getParent().isIdentityField(fieldName); }
@Override public Object getObject() { return getParent().getObject(); } @Override public WritablePdxInstance createWriter() { return this; } @Override public boolean hasField(String fieldName) { return getParent().hasField(fieldName); } }; } /** * Determines whether the given {@link String field name} is a {@link PropertyDescriptor property} * on the underlying, target {@link Object}. * * @param fieldName {@link String} containing the name of the field to match against * a {@link PropertyDescriptor property} from the underlying, target {@link Object}. * @return a boolean value that determines whether the given {@link String field name} * is a {@link PropertyDescriptor property} on the underlying, target {@link Object}. * @see #getFieldNames() */ @Override public boolean hasField(String fieldName) { return getFieldNames().contains(fieldName); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public static class Embedded { private static final AtomicInteger serverIdCounter = new AtomicInteger(); /** * Server ID. By default, an auto-incremented counter is used. */ private int serverId = serverIdCounter.getAndIncrement(); /** * Whether to enable embedded mode if the Artemis server APIs are available. */ private boolean enabled = true; /** * Whether to enable persistent store. */ private boolean persistent; /** * Journal file directory. Not necessary if persistence is turned off. */ private @Nullable String dataDirectory; /** * List of queues to create on startup. */ private String[] queues = new String[0]; /** * List of topics to create on startup. */ private String[] topics = new String[0]; /** * Cluster password. Randomly generated on startup by default. */ private String clusterPassword = UUID.randomUUID().toString(); private boolean defaultClusterPassword = true; public int getServerId() { return this.serverId; } public void setServerId(int serverId) { this.serverId = serverId; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isPersistent() { return this.persistent; }
public void setPersistent(boolean persistent) { this.persistent = persistent; } public @Nullable String getDataDirectory() { return this.dataDirectory; } public void setDataDirectory(@Nullable String dataDirectory) { this.dataDirectory = dataDirectory; } public String[] getQueues() { return this.queues; } public void setQueues(String[] queues) { this.queues = queues; } public String[] getTopics() { return this.topics; } public void setTopics(String[] topics) { this.topics = topics; } public String getClusterPassword() { return this.clusterPassword; } public void setClusterPassword(String clusterPassword) { this.clusterPassword = clusterPassword; this.defaultClusterPassword = false; } public boolean isDefaultClusterPassword() { return this.defaultClusterPassword; } /** * Creates the minimal transport parameters for an embedded transport * configuration. * @return the transport parameters * @see TransportConstants#SERVER_ID_PROP_NAME */ public Map<String, Object> generateTransportParameters() { Map<String, Object> parameters = new HashMap<>(); parameters.put(TransportConstants.SERVER_ID_PROP_NAME, getServerId()); return parameters; } } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisProperties.java
2
请完成以下Java代码
public List<InvoiceCandidateGenerateRequest> expandRequest(@NonNull final InvoiceCandidateGenerateRequest request) { final I_M_Inventory inventory = request.getModel(I_M_Inventory.class); // // Retrieve inventory lines final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); final List<I_M_InventoryLine> linesForInventory = inventoryDAO.retrieveLinesForInventoryId(inventoryId); if (linesForInventory.isEmpty()) { return ImmutableList.of(); } // // Retrieve inventory line handlers final Properties ctx = InterfaceWrapperHelper.getCtx(inventory); final List<IInvoiceCandidateHandler> inventoryLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, I_M_InventoryLine.Table_Name); // // Create the inventory line requests return InvoiceCandidateGenerateRequest.ofAll(inventoryLineHandlers, linesForInventory); } @Override public Iterator<?> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { throw new IllegalStateException("Not supported"); } @Override public void invalidateCandidatesFor(final Object model) { final I_M_Inventory inventory = InterfaceWrapperHelper.create(model, I_M_Inventory.class); invalidateCandidatesForInventory(inventory); } private void invalidateCandidatesForInventory(final I_M_Inventory inventory) { final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID()); // // Retrieve inventory line handlers final Properties ctx = InterfaceWrapperHelper.getCtx(inventory); final List<IInvoiceCandidateHandler> inventoryLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, I_M_InventoryLine.Table_Name); for (final IInvoiceCandidateHandler handler : inventoryLineHandlers)
{ for (final I_M_InventoryLine line : inventoryDAO.retrieveLinesForInventoryId(inventoryId)) { handler.invalidateCandidatesFor(line); } } } @Override public String getSourceTable() { return I_M_Inventory.Table_Name; } @Override public boolean isUserInChargeUserEditable() { return false; } @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\M_Inventory_Handler.java
1
请完成以下Java代码
protected void setInternalValueNumberInitial(final BigDecimal value) { throw new UnsupportedOperationException("Setting initial value not supported"); } @Override public boolean isNew() { return isGeneratedAttribute; } @Override protected void setInternalValueDate(Date value) { attributeInstance.setValueDate(TimeUtil.asTimestamp(value)); } @Override protected Date getInternalValueDate() { return attributeInstance.getValueDate(); } @Override protected void setInternalValueDateInitial(Date value) { throw new UnsupportedOperationException("Setting initial value not supported");
} @Override protected Date getInternalValueDateInitial() { return null; } @Override public boolean isOnlyIfInProductAttributeSet() { // FIXME tsa: figure out why this returns false instead of using the flag from M_HU_PI_Attribute?! return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AIWithHUPIAttributeValue.java
1
请完成以下Java代码
default @Nullable TaskExecutor getTaskExecutor() { return null; } /** * Called by the container factory with the factory's batchListener property. * @param batchListener the batchListener to set. * @since 2.2 */ default void setBatchListener(boolean batchListener) { } /** * Whether this endpoint is for a batch listener. * @return {@link Boolean#TRUE} if batch. * @since 3.0 */ @Nullable Boolean getBatchListener(); /** * Set a {@link BatchingStrategy} to use when debatching messages. * @param batchingStrategy the batching strategy. * @since 2.2 * @see #setBatchListener(boolean) */ default void setBatchingStrategy(BatchingStrategy batchingStrategy) { } /** * Return this endpoint's batching strategy, or null. * @return the strategy. * @since 2.4.7 */ default @Nullable BatchingStrategy getBatchingStrategy() { return null; } /** * Override the container factory's {@link AcknowledgeMode}. * @return the acknowledgment mode. * @since 2.2 */ default @Nullable AcknowledgeMode getAckMode() {
return null; } /** * Return a {@link ReplyPostProcessor} to post process a reply message before it is * sent. * @return the post processor. * @since 2.2.5 */ default @Nullable ReplyPostProcessor getReplyPostProcessor() { return null; } /** * Get the reply content type. * @return the content type. * @since 2.3 */ default @Nullable String getReplyContentType() { return null; } /** * Return whether the content type set by a converter prevails or not. * @return false to always apply the reply content type. * @since 2.3 */ default boolean isConverterWinsContentType() { return true; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\RabbitListenerEndpoint.java
1
请完成以下Java代码
public void setPage_Offset (int Page_Offset) { set_ValueNoCheck (COLUMNNAME_Page_Offset, Integer.valueOf(Page_Offset)); } /** Get Page_Offset. @return Page_Offset */ @Override public int getPage_Offset () { Integer ii = (Integer)get_Value(COLUMNNAME_Page_Offset); if (ii == null) return 0; return ii.intValue(); } /** Set Page_Size. @param Page_Size Page_Size */ @Override public void setPage_Size (int Page_Size) { set_ValueNoCheck (COLUMNNAME_Page_Size, Integer.valueOf(Page_Size)); } /** Get Page_Size. @return Page_Size */ @Override public int getPage_Size () { Integer ii = (Integer)get_Value(COLUMNNAME_Page_Size); if (ii == null) return 0; return ii.intValue(); } /** Set Result_Time. @param Result_Time Result_Time */ @Override public void setResult_Time (java.sql.Timestamp Result_Time) { set_ValueNoCheck (COLUMNNAME_Result_Time, Result_Time); } /** Get Result_Time. @return Result_Time */ @Override public java.sql.Timestamp getResult_Time () {
return (java.sql.Timestamp)get_Value(COLUMNNAME_Result_Time); } /** Set Total_Size. @param Total_Size Total_Size */ @Override public void setTotal_Size (int Total_Size) { set_ValueNoCheck (COLUMNNAME_Total_Size, Integer.valueOf(Total_Size)); } /** Get Total_Size. @return Total_Size */ @Override public int getTotal_Size () { Integer ii = (Integer)get_Value(COLUMNNAME_Total_Size); if (ii == null) return 0; return ii.intValue(); } /** Set UUID. @param UUID UUID */ @Override public void setUUID (java.lang.String UUID) { set_ValueNoCheck (COLUMNNAME_UUID, UUID); } /** Get UUID. @return UUID */ @Override public java.lang.String getUUID () { return (java.lang.String)get_Value(COLUMNNAME_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_Pagination.java
1
请在Spring Boot框架中完成以下Java代码
public GenericResponse<? extends DataMarker> getGenericResponse(@RequestBody GenericRequest<? extends DataMarker> request) { LOG.info("getGenericResponse"); if (request.getData() instanceof SimpleDataPayload) { SimpleDataPayload payload = (SimpleDataPayload) request.getData(); return new GenericResponse<>(request.getName(), payload); } else if (request.getData() instanceof ComplexDataPayload) { ComplexDataPayload payload = (ComplexDataPayload) request.getData(); return new GenericResponse<>(request.getName(), payload); } else { throw new UnsupportedOperationException("Unsupported type"); } } @RequestMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<RequestInfo> getRequestParameters(HttpServletRequest request) throws IOException { LOG.info("getRequestParameters: {}?{}", request.getRequestURL(), request.getQueryString()); String body = request.getReader().lines().collect(Collectors.joining()); RequestInfo requestInfo = new RequestInfo(applicationConfig.getId(), request.getRequestURL().toString(), request.getQueryString(), body, request.getCharacterEncoding(), request.getMethod(), createCookiesMap(request.getCookies()), request.getContentType(), createHeaderMap(request), request.getProtocol(), createRemoteInfo(request)); return ResponseEntity.ok(requestInfo); } @GetMapping(path="/very-long-number") public ResponseEntity<NumberWrapper> getVeryLongNumber() { return ResponseEntity.ok(new NumberWrapper(4855910445484272258L)); } private Map<String, String> createCookiesMap(Cookie[] cookies) { Map<String, String> cookiesMap = new HashMap<>();
if (cookies != null) { for (Cookie cookie : cookies) { String id = cookie.getDomain() + ":" + cookie.getName(); cookiesMap.put(id, cookie.toString()); } } return cookiesMap; } private Map<String, List<String>> createHeaderMap(HttpServletRequest request) { Map<String, List<String>> headers = new HashMap<>(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { List<String> headerValues = new ArrayList<>(); String headerName = headerNames.nextElement(); Enumeration<String> values = request.getHeaders(headerName); while (values.hasMoreElements()) { headerValues.add(values.nextElement()); } headers.put(headerName, headerValues); } } return headers; } private String createRemoteInfo(HttpServletRequest request) { return request.getRemoteHost() + ":" + request.getRemotePort(); } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\controller\DataServiceController.java
2
请完成以下Java代码
public int getAnfrageMenge() { return anfrageMenge; } /** * Sets the value of the anfrageMenge property. * */ public void setAnfrageMenge(int value) { this.anfrageMenge = value; } /** * Gets the value of the anfragePzn property. * */ public long getAnfragePzn() { return anfragePzn; } /** * Sets the value of the anfragePzn property. * */ public void setAnfragePzn(long value) { this.anfragePzn = value; } /** * Gets the value of the substitution property. * * @return * possible object is * {@link VerfuegbarkeitSubstitution } * */ public VerfuegbarkeitSubstitution getSubstitution() { return substitution; } /** * Sets the value of the substitution property. * * @param value * allowed object is * {@link VerfuegbarkeitSubstitution } * */ public void setSubstitution(VerfuegbarkeitSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property. *
* <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link VerfuegbarkeitAnteil } * * */ public List<VerfuegbarkeitAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<VerfuegbarkeitAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsantwortArtikel.java
1
请完成以下Java代码
public Flux<String> getIndexMongo() { personRepository.findAll() .doOnNext(p -> logger.info("Person: {}", p)) .subscribe(); return Flux.fromIterable(getThreads()); } @GetMapping("/threads/reactor-kafka") public Flux<String> getIndexKafka() { Map<String, Object> producerProps = new HashMap<>(); producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); SenderOptions<Integer, String> senderOptions = SenderOptions.create(producerProps); KafkaSender<Integer, String> sender = KafkaSender.create(senderOptions); Flux<SenderRecord<Integer, String, Integer>> outboundFlux = Flux.range(1, 10) .map(i -> SenderRecord.create(new ProducerRecord<>("reactive-test", i, "Message_" + i), i)); sender.send(outboundFlux) .subscribe(); Map<String, Object> consumerProps = new HashMap<>(); consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "my-consumer"); consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "my-group"); consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class); consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); ReceiverOptions<Integer, String> receiverOptions = ReceiverOptions.create(consumerProps); receiverOptions.subscription(Collections.singleton("reactive-test")); KafkaReceiver<Integer, String> receiver = KafkaReceiver.create(receiverOptions);
Flux<ReceiverRecord<Integer, String>> inboundFlux = receiver.receive(); inboundFlux.subscribe(r -> { logger.info("Received message: {}", r.value()); r.receiverOffset() .acknowledge(); }); return Flux.fromIterable(getThreads()); } @GetMapping("/index") public Mono<String> getIndex() { return Mono.just("Hello world!"); } private List<String> getThreads() { return Thread.getAllStackTraces() .keySet() .stream() .map(t -> String.format("%-20s \t %s \t %d \t %s\n", t.getName(), t.getState(), t.getPriority(), t.isDaemon() ? "Daemon" : "Normal")) .collect(Collectors.toList()); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\concurrency\Controller.java
1
请完成以下Java代码
public Config setSample(float sample) { this.sample = sample; return this; } public float getSample() { return sample; } public Config setAlpha(float alpha) { this.alpha = alpha; return this; } public float getAlpha() { return alpha; } public Config setInputFile(String inputFile) { this.inputFile = inputFile;
return this; } public String getInputFile() { return inputFile; } public TrainingCallback getCallback() { return callback; } public void setCallback(TrainingCallback callback) { this.callback = callback; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Config.java
1
请在Spring Boot框架中完成以下Java代码
public class DiagramLayout implements Serializable { private static final long serialVersionUID = 1L; private Map<String, DiagramElement> elements; public DiagramLayout(Map<String, DiagramElement> elements) { this.setElements(elements); } public DiagramNode getNode(String id) { DiagramElement element = getElements().get(id); if (element instanceof DiagramNode) { return (DiagramNode) element; } else { return null; } } public DiagramEdge getEdge(String id) { DiagramElement element = getElements().get(id); if (element instanceof DiagramEdge) { return (DiagramEdge) element; } else { return null; } } public Map<String, DiagramElement> getElements() { return elements; }
public void setElements(Map<String, DiagramElement> elements) { this.elements = elements; } public List<DiagramNode> getNodes() { List<DiagramNode> nodes = new ArrayList<DiagramNode>(); for (Entry<String, DiagramElement> entry : getElements().entrySet()) { DiagramElement element = entry.getValue(); if (element instanceof DiagramNode) { nodes.add((DiagramNode) element); } } return nodes; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\repository\DiagramLayout.java
2
请在Spring Boot框架中完成以下Java代码
public class OrderCreateRequest { @JsonProperty("orderId") Id orderId; @JsonProperty("supportId") SupportIDType supportId; @JsonProperty("bpartnerId") BPartnerId bpartnerId; @JsonProperty("orderPackages") List<OrderCreateRequestPackage> orderPackages; @Builder private OrderCreateRequest(
@JsonProperty("orderId") @NonNull final Id orderId, @JsonProperty("supportId") @NonNull final SupportIDType supportId, @JsonProperty("bpartnerId") @NonNull final BPartnerId bpartnerId, @JsonProperty("orderPackages") @NonNull @Singular final List<OrderCreateRequestPackage> orderPackages) { if (orderPackages.isEmpty()) { throw new IllegalArgumentException("Order shall have at least one item"); } this.orderId = orderId; this.supportId = supportId; this.bpartnerId = bpartnerId; this.orderPackages = ImmutableList.copyOf(orderPackages); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderCreateRequest.java
2
请完成以下Java代码
public synchronized void disableForSession(final String sessionId) { // TODO: implement } public WebsocketTopicName getWebsocketEndpoint(final UserId adUserId) { return getNotificationsQueue(adUserId).getWebsocketEndpoint(); } private UserNotificationsQueue getNotificationsQueueOrNull(final UserId adUserId) { return adUserId2notifications.get(adUserId); } private UserNotificationsQueue getNotificationsQueue(final UserId adUserId) { final UserNotificationsQueue notificationsQueue = getNotificationsQueueOrNull(adUserId); if (notificationsQueue == null) { throw new IllegalArgumentException("No notifications queue found for AD_User_ID=" + adUserId); } return notificationsQueue; } public UserNotificationsList getNotifications(final UserId adUserId, final QueryLimit limit) { return getNotificationsQueue(adUserId).getNotificationsAsList(limit); } private void forwardEventToNotificationsQueues(final IEventBus eventBus, final Event event) { logger.trace("Got event from {}: {}", eventBus, event); final UserNotification notification = UserNotificationUtils.toUserNotification(event); final UserId recipientUserId = UserId.ofRepoId(notification.getRecipientUserId()); final UserNotificationsQueue notificationsQueue = getNotificationsQueueOrNull(recipientUserId); if (notificationsQueue == null) { logger.trace("No notification queue was found for recipientUserId={}", recipientUserId); return; } notificationsQueue.addNotification(notification); } public void markNotificationAsRead(final UserId adUserId, final String notificationId) {
getNotificationsQueue(adUserId).markAsRead(notificationId); } public void markAllNotificationsAsRead(final UserId adUserId) { getNotificationsQueue(adUserId).markAllAsRead(); } public int getNotificationsUnreadCount(final UserId adUserId) { return getNotificationsQueue(adUserId).getUnreadCount(); } public void deleteNotification(final UserId adUserId, final String notificationId) { getNotificationsQueue(adUserId).delete(notificationId); } public void deleteAllNotification(final UserId adUserId) { getNotificationsQueue(adUserId).deleteAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsService.java
1
请完成以下Java代码
public Wallet loadDecryptedWallet() throws IOException, UnreadableWalletException { File walletFile = new File("baeldungencrypted.dat"); Wallet wallet = Wallet.loadFromFile(walletFile); wallet.decrypt("password"); return wallet; } public Wallet loadWallet() throws IOException, UnreadableWalletException { File walletFile = new File("baeldung.dat"); Wallet wallet = Wallet.loadFromFile(walletFile); logger.info("Address: " + wallet.currentReceiveAddress().toString()); logger.info("Seed Phrase: " + wallet.getKeyChainSeed().getMnemonicString()); logger.info("Balance: " + wallet.getBalance().toFriendlyString()); logger.info("Public Key: " + wallet.findKeyFromAddress(wallet.currentReceiveAddress()).getPublicKeyAsHex()); logger.info("Private Key: " + wallet.findKeyFromAddress(wallet.currentReceiveAddress()).getPrivateKeyAsHex()); return wallet; } public Wallet loadUsingSeed(String seedWord) throws UnreadableWalletException { DeterministicSeed seed = new DeterministicSeed(seedWord, null, "", Utils.currentTimeSeconds()); return Wallet.fromSeed(params, seed); } public void connectWalletToPeer() throws BlockStoreException, UnreadableWalletException, IOException { Wallet wallet = loadWallet(); BlockStore blockStore = new MemoryBlockStore(params); BlockChain chain = new BlockChain(params, wallet, blockStore); PeerGroup peerGroup = new PeerGroup(params, chain); peerGroup.addPeerDiscovery(new DnsDiscovery(params)); peerGroup.addWallet(wallet);
wallet.addCoinsReceivedEventListener((Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) -> { logger.info("Received tx for " + tx.getValueSentToMe(wallet)); logger.info("New balance: " + newBalance.toFriendlyString()); }); peerGroup.start(); peerGroup.downloadBlockChain(); wallet.saveToFile(new File("baeldung.dat")); logger.info("Wallet balance: " + wallet.getBalance() .toFriendlyString()); } }
repos\tutorials-master\java-blockchain\src\main\java\com\baeldung\bitcoinj\CreateWallet.java
1
请在Spring Boot框架中完成以下Java代码
private String getOrDeducePassword(SecurityProperties.User user, @Nullable PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; } return NOOP_PASSWORD_PREFIX + password; } static class RSocketEnabledOrReactiveWebApplication extends AnyNestedCondition { RSocketEnabledOrReactiveWebApplication() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnBean(RSocketMessageHandler.class) static class RSocketSecurityEnabledCondition { } @ConditionalOnWebApplication(type = Type.REACTIVE) static class ReactiveWebApplicationCondition { } } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\ReactiveUserDetailsServiceAutoConfiguration.java
2
请完成以下Java代码
public EventDefinitionEntity findLatestEventDefinitionByKey(String eventDefinitionKey) { return dataManager.findLatestEventDefinitionByKey(eventDefinitionKey); } @Override public void deleteEventDefinitionsByDeploymentId(String deploymentId) { dataManager.deleteEventDefinitionsByDeploymentId(deploymentId); } @Override public List<EventDefinition> findEventDefinitionsByQueryCriteria(EventDefinitionQueryImpl eventQuery) { return dataManager.findEventDefinitionsByQueryCriteria(eventQuery); } @Override public long findEventDefinitionCountByQueryCriteria(EventDefinitionQueryImpl eventQuery) { return dataManager.findEventDefinitionCountByQueryCriteria(eventQuery); } @Override public EventDefinitionEntity findEventDefinitionByDeploymentAndKey(String deploymentId, String eventDefinitionKey) { return dataManager.findEventDefinitionByDeploymentAndKey(deploymentId, eventDefinitionKey); } @Override public EventDefinitionEntity findEventDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String eventDefinitionKey, String tenantId) { return dataManager.findEventDefinitionByDeploymentAndKeyAndTenantId(deploymentId, eventDefinitionKey, tenantId); } @Override public EventDefinitionEntity findLatestEventDefinitionByKeyAndTenantId(String eventDefinitionKey, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findLatestEventDefinitionByKey(eventDefinitionKey);
} else { return dataManager.findLatestEventDefinitionByKeyAndTenantId(eventDefinitionKey, tenantId); } } @Override public EventDefinitionEntity findEventDefinitionByKeyAndVersionAndTenantId(String eventDefinitionKey, Integer eventVersion, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findEventDefinitionByKeyAndVersion(eventDefinitionKey, eventVersion); } else { return dataManager.findEventDefinitionByKeyAndVersionAndTenantId(eventDefinitionKey, eventVersion, tenantId); } } @Override public List<EventDefinition> findEventDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findEventDefinitionsByNativeQuery(parameterMap); } @Override public long findEventDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findEventDefinitionCountByNativeQuery(parameterMap); } @Override public void updateEventDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateEventDefinitionTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityManagerImpl.java
1
请完成以下Java代码
private final class ColumnAttributes { protected TableCellEditor cellEditor; protected TableCellRenderer cellRenderer; // protected Object headerValue; protected int minWidth; protected int maxWidth; protected int preferredWidth; } @Override public Object getModelValueAt(int rowIndexModel, int columnIndexModel) { return getModel().getValueAt(rowIndexModel, columnIndexModel); } private ITableColorProvider colorProvider = new DefaultTableColorProvider(); @Override public void setColorProvider(final ITableColorProvider colorProvider) { Check.assumeNotNull(colorProvider, "colorProvider not null"); this.colorProvider = colorProvider; } @Override public ITableColorProvider getColorProvider() { return colorProvider; } @Override public void setModel(final TableModel dataModel) {
super.setModel(dataModel); if (modelRowSorter == null) { // i.e. we are in JTable constructor and modelRowSorter was not yet set // => do nothing } else if (!modelRowSorter.isEnabled()) { setupViewRowSorter(); } } private final void setupViewRowSorter() { final TableModel model = getModel(); viewRowSorter.setModel(model); if (modelRowSorter != null) { viewRowSorter.setSortKeys(modelRowSorter.getSortKeys()); } setRowSorter(viewRowSorter); viewRowSorter.sort(); } } // CTable
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTable.java
1
请在Spring Boot框架中完成以下Java代码
public static class RocketChatNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.rocketchat") public RocketChatNotifier rocketChatNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new RocketChatNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "spring.boot.admin.notify.feishu", name = "webhook-url") @AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class }) @Lazy(false) public static class FeiShuNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.feishu") public FeiShuNotifier feiShuNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new FeiShuNotifier(repository, createNotifierRestTemplate(proxyProperties));
} } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "spring.boot.admin.notify.webex", name = "auth-token") @AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class }) @Lazy(false) public static class WebexNotifierConfiguration { @Bean @ConditionalOnMissingBean @ConfigurationProperties("spring.boot.admin.notify.webex") public WebexNotifier webexNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) { return new WebexNotifier(repository, createNotifierRestTemplate(proxyProperties)); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerNotifierAutoConfiguration.java
2
请完成以下Java代码
public String getBody() { return body; } public void setBody(String body) { if (multiValueParts != null && !multiValueParts.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both body and multi value parts"); } else if (formParameters != null && !formParameters.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both body and form parameters"); } this.body = body; } public String getBodyEncoding() { return bodyEncoding; } public void setBodyEncoding(String bodyEncoding) { this.bodyEncoding = bodyEncoding; } public Collection<MultiValuePart> getMultiValueParts() { return multiValueParts; } public void addMultiValuePart(MultiValuePart part) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and multi value parts"); } else if (formParameters != null && !formParameters.isEmpty()) { throw new FlowableIllegalStateException("Cannot set both form parameters and multi value parts"); } if (multiValueParts == null) { multiValueParts = new ArrayList<>(); } multiValueParts.add(part); } public Map<String, List<String>> getFormParameters() { return formParameters; } public void addFormParameter(String key, String value) { if (body != null) { throw new FlowableIllegalStateException("Cannot set both body and form parameters"); } else if (multiValueParts != null && !multiValueParts.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both multi value parts and form parameters"); } if (formParameters == null) { formParameters = new LinkedHashMap<>(); } formParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public boolean isNoRedirects() { return noRedirects; } public void setNoRedirects(boolean noRedirects) { this.noRedirects = noRedirects; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpRequest.java
1
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Sample sample = Timer.start(meterRegistry); return chain.filter(exchange) .doOnSuccess(aVoid -> endTimerRespectingCommit(exchange, sample)) .doOnError(throwable -> endTimerRespectingCommit(exchange, sample)); } private void endTimerRespectingCommit(ServerWebExchange exchange, Sample sample) { ServerHttpResponse response = exchange.getResponse(); if (response.isCommitted()) { endTimerInner(exchange, sample); } else { response.beforeCommit(() -> { endTimerInner(exchange, sample);
return Mono.empty(); }); } } private void endTimerInner(ServerWebExchange exchange, Sample sample) { Tags tags = compositeTagsProvider.apply(exchange); if (log.isTraceEnabled()) { log.trace(metricsPrefix + ".requests tags: " + tags); } sample.stop(meterRegistry.timer(metricsPrefix + ".requests", tags)); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\GatewayMetricsFilter.java
1
请完成以下Java代码
protected void writeInternal(OAuth2Error oauth2Error, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException { try { Map<String, String> errorParameters = this.errorParametersConverter.convert(oauth2Error); this.jsonMessageConverter.write(errorParameters, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage); } catch (Exception ex) { throw new HttpMessageNotWritableException( "An error occurred writing the OAuth 2.0 Error: " + ex.getMessage(), ex); } } /** * Sets the {@link Converter} used for converting the OAuth 2.0 Error parameters to an * {@link OAuth2Error}. * @param errorConverter the {@link Converter} used for converting to an * {@link OAuth2Error} */ public final void setErrorConverter(Converter<Map<String, String>, OAuth2Error> errorConverter) { Assert.notNull(errorConverter, "errorConverter cannot be null"); this.errorConverter = errorConverter; } /** * Sets the {@link Converter} used for converting the {@link OAuth2Error} to a * {@code Map} representation of the OAuth 2.0 Error parameters. * @param errorParametersConverter the {@link Converter} used for converting to a * {@code Map} representation of the Error parameters */ public final void setErrorParametersConverter( Converter<OAuth2Error, Map<String, String>> errorParametersConverter) { Assert.notNull(errorParametersConverter, "errorParametersConverter cannot be null"); this.errorParametersConverter = errorParametersConverter; } /** * A {@link Converter} that converts the provided OAuth 2.0 Error parameters to an * {@link OAuth2Error}. */ private static class OAuth2ErrorConverter implements Converter<Map<String, String>, OAuth2Error> {
@Override public OAuth2Error convert(Map<String, String> parameters) { String errorCode = parameters.get(OAuth2ParameterNames.ERROR); String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION); String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI); return new OAuth2Error(errorCode, errorDescription, errorUri); } } /** * A {@link Converter} that converts the provided {@link OAuth2Error} to a {@code Map} * representation of OAuth 2.0 Error parameters. */ private static class OAuth2ErrorParametersConverter implements Converter<OAuth2Error, Map<String, String>> { @Override public Map<String, String> convert(OAuth2Error oauth2Error) { Map<String, String> parameters = new HashMap<>(); parameters.put(OAuth2ParameterNames.ERROR, oauth2Error.getErrorCode()); if (StringUtils.hasText(oauth2Error.getDescription())) { parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, oauth2Error.getDescription()); } if (StringUtils.hasText(oauth2Error.getUri())) { parameters.put(OAuth2ParameterNames.ERROR_URI, oauth2Error.getUri()); } return parameters; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverter.java
1
请完成以下Java代码
Mono<String> useOauthWithAuthCode() { Mono<String> retrievedResource = webClient.get() .uri(RESOURCE_URI) .retrieve() .bodyToMono(String.class); return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); } @GetMapping("/auth-code-annotated") Mono<String> useOauthWithAuthCodeAndAnnotation(@RegisteredOAuth2AuthorizedClient("bael") OAuth2AuthorizedClient authorizedClient) { Mono<String> retrievedResource = webClient.get() .uri(RESOURCE_URI) .attributes(oauth2AuthorizedClient(authorizedClient)) .retrieve() .bodyToMono(String.class);
return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string + ". Principal associated: " + authorizedClient.getPrincipalName() + ". Token will expire at: " + authorizedClient.getAccessToken() .getExpiresAt()); } @GetMapping("/auth-code-explicit-client") Mono<String> useOauthWithExpicitClient() { Mono<String> retrievedResource = webClient.get() .uri(RESOURCE_URI) .attributes(clientRegistrationId("bael")) .retrieve() .bodyToMono(String.class); return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-oauth\src\main\java\com\baeldung\webclient\authorizationcodeclient\web\ClientRestController.java
1
请完成以下Java代码
public class MultipleSubscribersColdObs { private static final Logger LOGGER = LoggerFactory.getLogger(MultipleSubscribersColdObs.class); public static void main(String[] args) throws InterruptedException { defaultBehaviour(); // subscribeBeforeConnect(); } private static void defaultBehaviour() { Observable obs = getObservable(); LOGGER.info("Subscribing"); Subscription s1 = obs.subscribe(i -> LOGGER.info("subscriber#1 is printing " + i)); Subscription s2 = obs.subscribe(i -> LOGGER.info("subscriber#2 is printing " + i)); s1.unsubscribe(); s2.unsubscribe(); } private static void subscribeBeforeConnect() throws InterruptedException { ConnectableObservable obs = getObservable().publish(); LOGGER.info("Subscribing"); obs.subscribe(i -> LOGGER.info("subscriber #1 is printing " + i)); obs.subscribe(i -> LOGGER.info("subscriber #2 is printing " + i)); Thread.sleep(1000); LOGGER.info("Connecting"); Subscription s = obs.connect();
s.unsubscribe(); } private static Observable getObservable() { return Observable.create(subscriber -> { subscriber.onNext(gettingValue(1)); subscriber.onNext(gettingValue(2)); subscriber.add(Subscriptions.create(() -> { LOGGER.info("Clear resources"); })); }); } private static Integer gettingValue(int i) { LOGGER.info("Getting " + i); return i; } }
repos\tutorials-master\rxjava-modules\rxjava-observables\src\main\java\com\baeldung\rxjava\MultipleSubscribersColdObs.java
1
请在Spring Boot框架中完成以下Java代码
private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); } private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, "&quot;", two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } }
private String checkEntity(final String preamble, final String term) { return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble; } private boolean isValidEntity(final String entity) { return inArray(entity, vAllowedEntities); } private static boolean inArray(final String s, final String[] array) { for (String item : array) { if (item != null && item.equals(s)) { return true; } } return false; } private boolean allowed(final String name) { return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); } private boolean allowedAttribute(final String name, final String paramName) { return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\config\HTMLFilter.java
2
请完成以下Java代码
public static class FileSystemExportResourceResolver extends AbstractExportResourceResolver { @Override protected @NonNull String getResourcePath() { return String.format("%1$s%2$s%3$s", ResourcePrefix.FILESYSTEM_URL_PREFIX.toUrlPrefix(), System.getProperty("user.dir"), File.separator); } } /** * Marker interface extending {@link CacheResourceResolver} for cache data imports. * * @see org.springframework.geode.core.io.ResourceResolver * @see CacheResourceResolver */ @FunctionalInterface public interface ImportResourceResolver extends CacheResourceResolver { } /** * Abstract base class extended by import {@link ResourceResolver} implementations, providing a template * to resolve the {@link Resource} to import. * * @see AbstractCacheResourceResolver * @see ImportResourceResolver */ public static abstract class AbstractImportResourceResolver extends AbstractCacheResourceResolver implements ImportResourceResolver { /** * @inheritDoc */ @Override public Optional<Resource> resolve(@NonNull Region<?, ?> region) { Assert.notNull(region, "Region must not be null"); String resourceLocation = getResourceLocation(region, CACHE_DATA_IMPORT_RESOURCE_LOCATION_PROPERTY_NAME); Optional<Resource> resource = resolve(resourceLocation); boolean exists = resource.isPresent(); boolean readable = exists && resource.filter(Resource::isReadable).isPresent(); if (!exists) { getLogger().warn("Resource [{}] for Region [{}] could not be found; skipping import for Region", resourceLocation, region.getFullPath()); } else { Assert.state(readable, () -> String.format("Resource [%1$s] for Region [%2$s] is not readable", resourceLocation, region.getFullPath())); } return resource;
} @Nullable @Override protected Resource onMissingResource(@Nullable Resource resource, @NonNull String location) { getLogger().warn("Resource [{}] at location [{}] does not exist; skipping import", ResourceUtils.nullSafeGetDescription(resource), location); return null; } } /** * Resolves the {@link Resource} to {@literal import} from the {@literal classpath}. */ public static class ClassPathImportResourceResolver extends AbstractImportResourceResolver { @Override protected @NonNull String getResourcePath() { return ResourcePrefix.CLASSPATH_URL_PREFIX.toUrlPrefix(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\support\ResourceCapableCacheDataImporterExporter.java
1
请完成以下Java代码
public @Nullable Map<String, Object> getVariables() { return this.variables; } /** * Creates an instance of {@link MatchResult} that is a match with no variables * @return */ public static Mono<MatchResult> match() { return match(Collections.emptyMap()); } /** * * Creates an instance of {@link MatchResult} that is a match with the specified * variables * @param variables * @return */
public static Mono<MatchResult> match(Map<String, ? extends Object> variables) { MatchResult result = new MatchResult(true, (variables != null) ? new HashMap<>(variables) : null); return Mono.just(result); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return */ public static Mono<MatchResult> notMatch() { return Mono.just(new MatchResult(false, Collections.emptyMap())); } } }
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\util\matcher\PayloadExchangeMatcher.java
1
请在Spring Boot框架中完成以下Java代码
static class ThymeleafWebLayoutConfiguration { @Bean @ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean @ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class WebController { @Autowired private CustomerDAO customerDAO; @GetMapping(path = "/") public String index() { return "external"; } @GetMapping("/logout") public String logout(HttpServletRequest request) throws Exception { request.logout(); return "redirect:/"; } @GetMapping(path = "/customers") public String customers(Principal principal, Model model) { addCustomers(); Iterable<Customer> customers = customerDAO.findAll(); model.addAttribute("customers", customers); model.addAttribute("username", principal.getName()); return "customers"; } // add customers for demonstration public void addCustomers() { Customer customer1 = new Customer(); customer1.setAddress("1111 foo blvd"); customer1.setName("Foo Industries"); customer1.setServiceRendered("Important services");
customerDAO.save(customer1); Customer customer2 = new Customer(); customer2.setAddress("2222 bar street"); customer2.setName("Bar LLP"); customer2.setServiceRendered("Important services"); customerDAO.save(customer2); Customer customer3 = new Customer(); customer3.setAddress("33 main street"); customer3.setName("Big LLC"); customer3.setServiceRendered("Important services"); customerDAO.save(customer3); } }
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\WebController.java
2
请完成以下Java代码
public class JacksonJsonPathQuery implements SpinJsonPathQuery { private static final JacksonJsonLogger LOG = JacksonJsonLogger.JSON_TREE_LOGGER; protected final SpinJsonNode spinJsonNode; protected final JsonPath query; protected final JacksonJsonDataFormat dataFormat; public JacksonJsonPathQuery(JacksonJsonNode jacksonJsonNode, JsonPath query, JacksonJsonDataFormat dataFormat) { this.spinJsonNode = jacksonJsonNode; this.query = query; this.dataFormat = dataFormat; } public SpinJsonNode element() { try { Object result = query.read(spinJsonNode.toString(), dataFormat.getJsonPathConfiguration()); JsonNode node; if (result != null) { node = dataFormat.createJsonNode(result); } else { node = dataFormat.createNullJsonNode(); } return dataFormat.createWrapperInstance(node); } catch(PathNotFoundException pex) { throw LOG.unableToEvaluateJsonPathExpressionOnNode(spinJsonNode, pex); } catch (ClassCastException cex) { throw LOG.unableToCastJsonPathResultTo(SpinJsonNode.class, cex); } catch(InvalidPathException iex) { throw LOG.invalidJsonPath(SpinJsonNode.class, iex); } } public SpinList<SpinJsonNode> elementList() { JacksonJsonNode node = (JacksonJsonNode) element();
if(node.isArray()) { return node.elements(); } else { throw LOG.unableToParseValue(SpinList.class.getSimpleName(), node.getNodeType()); } } public String stringValue() { JacksonJsonNode node = (JacksonJsonNode) element(); if(node.isString()) { return node.stringValue(); } else { throw LOG.unableToParseValue(String.class.getSimpleName(), node.getNodeType()); } } public Number numberValue() { JacksonJsonNode node = (JacksonJsonNode) element(); if(node.isNumber()) { return node.numberValue(); } else { throw LOG.unableToParseValue(Number.class.getSimpleName(), node.getNodeType()); } } public Boolean boolValue() { JacksonJsonNode node = (JacksonJsonNode) element(); if(node.isBoolean()) { return node.boolValue(); } else { throw LOG.unableToParseValue(Boolean.class.getSimpleName(), node.getNodeType()); } } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\query\JacksonJsonPathQuery.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + (int) (id ^ (id >>> 32)); result = (prime * result) + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; }
final Possession other = (Possession) obj; if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "Possession [id=" + id + ", name=" + name + "]"; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\modifying\model\Possession.java
1
请完成以下Java代码
public class AProcessModel { private static final String ACTION_Name = "Process"; private static final transient Logger logger = LogManager.getLogger(AProcessModel.class); public String getActionName() { return ACTION_Name; } public List<SwingRelatedProcessDescriptor> fetchProcesses(final Properties ctx, final GridTab gridTab) { if (gridTab == null) { return ImmutableList.of(); } final IUserRolePermissions role = Env.getUserRolePermissions(ctx); Check.assumeNotNull(role, "No role found for {}", ctx); final IProcessPreconditionsContext preconditionsContext = gridTab.toPreconditionsContext(); final AdTableId adTableId = AdTableId.ofRepoId(gridTab.getAD_Table_ID()); final AdWindowId adWindowId = preconditionsContext.getAdWindowId(); final AdTabId adTabId = preconditionsContext.getAdTabId(); return SpringContextHolder.instance.getBean(ADProcessService.class).getRelatedProcessDescriptors(adTableId, adWindowId, adTabId) .stream() .filter(relatedProcess -> isExecutionGrantedOrLog(relatedProcess, role)) .map(relatedProcess -> createSwingRelatedProcess(relatedProcess, preconditionsContext)) .filter(this::isEnabledOrLog) .collect(GuavaCollectors.toImmutableList()); } private SwingRelatedProcessDescriptor createSwingRelatedProcess(final RelatedProcessDescriptor relatedProcess, final IProcessPreconditionsContext preconditionsContext) { final Supplier<ProcessPreconditionsResolution> preconditionsResolutionSupplier = () -> checkPreconditionApplicable(relatedProcess, preconditionsContext); return SwingRelatedProcessDescriptor.of(relatedProcess, preconditionsResolutionSupplier); } private boolean isExecutionGrantedOrLog(final RelatedProcessDescriptor relatedProcess, final IUserRolePermissions permissions) { if (relatedProcess.isExecutionGranted(permissions)) { return true; } if (logger.isDebugEnabled()) { logger.debug("Skip process {} because execution was not granted using {}", relatedProcess, permissions); } return false; } private boolean isEnabledOrLog(final SwingRelatedProcessDescriptor relatedProcess) { if (relatedProcess.isEnabled()) {
return true; } if (!relatedProcess.isSilentRejection()) { return true; } // // Log and filter it out if (logger.isDebugEnabled()) { final String disabledReason = relatedProcess.getDisabledReason(Env.getAD_Language(Env.getCtx())); logger.debug("Skip process {} because {} (silent={})", relatedProcess, disabledReason, relatedProcess.isSilentRejection()); } return false; } @VisibleForTesting /* package */ProcessPreconditionsResolution checkPreconditionApplicable(final RelatedProcessDescriptor relatedProcess, final IProcessPreconditionsContext preconditionsContext) { return ProcessPreconditionChecker.newInstance() .setProcess(relatedProcess) .setPreconditionsContext(preconditionsContext) .checkApplies(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\AProcessModel.java
1
请完成以下Java代码
public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\quarkus-modules\mongo-db\src\main\java\com\baeldung\mongoclient\Article.java
1
请完成以下Java代码
public class ShipmentDeclaration { @NonFinal ShipmentDeclarationId id; @NonNull String documentNo; @NonNull OrgId orgId; @NonNull InOutId shipmentId; @NonNull BPartnerLocationId bpartnerAndLocationId; @Nullable UserId userId; @NonNull DocTypeId docTypeId; @NonNull LocalDate shipmentDate; @NonNull String docAction; @NonNull String docStatus; @Nullable @NonFinal ShipmentDeclarationId baseShipmentDeclarationId; @Nullable @NonFinal ShipmentDeclarationId correctionShipmentDeclarationId;
@NonNull ImmutableList<ShipmentDeclarationLine> lines; public void updateLineNos() { int nextLineNo = 10; for (ShipmentDeclarationLine line : lines) { line.setLineNo(nextLineNo); nextLineNo += 10; } } public ShipmentDeclaration copyToNew( @NonNull final DocTypeId newDocTypeId, @NonNull final String newDocAction) { final ImmutableList<ShipmentDeclarationLine> newLines = getLines() .stream() .map(ShipmentDeclarationLine::copyToNew) .collect(ImmutableList.toImmutableList()); return toBuilder() .id(null) .docTypeId(newDocTypeId) .docAction(newDocAction) .lines(newLines) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\ShipmentDeclaration.java
1
请完成以下Java代码
final class WeightingSpecificationsMap { private final ImmutableMap<WeightingSpecificationsId, WeightingSpecifications> byId; private final Optional<WeightingSpecificationsId> defaultId; public WeightingSpecificationsMap(final List<WeightingSpecifications> list) { byId = Maps.uniqueIndex(list, WeightingSpecifications::getId); defaultId = list.stream() .map(WeightingSpecifications::getId) .min(Comparator.naturalOrder()); } public WeightingSpecifications getDefault() { return getById(getDefaultId());
} public WeightingSpecificationsId getDefaultId() { return defaultId.orElseThrow(() -> new AdempiereException("No specifications defined")); } public WeightingSpecifications getById(@NonNull final WeightingSpecificationsId id) { final WeightingSpecifications spec = byId.get(id); if (spec == null) { throw new AdempiereException("Invalid ID: " + id); } return spec; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\spec\WeightingSpecificationsMap.java
1
请完成以下Java代码
private void consolidateBPartnerWithIdentifier( @NonNull final ExternalIdentifier identifierString, @Nullable final JsonRequestBPartner jsonBPartner) { if (jsonBPartner == null) { return; } switch (identifierString.getType()) { case METASFRESH_ID: // nothing to do; the JsonRequestBPartner has no metasfresh-ID to consolidate with break; case EXTERNAL_REFERENCE: // nothing to do break; case GLN: // GLN-identifierString is valid for bPartner-lookup, but we can't consolidate the given jsonBPartner with it break; case GLN_WITH_LABEL: if (!jsonBPartner.isLookupLabelSet()) { final String lookupLabel = identifierString.asGlnWithLabel().getLabel(); jsonBPartner.setLookupLabel(lookupLabel); } default: throw new AdempiereException("Unexpected IdentifierString.Type=" + identifierString.getType()) .appendParametersToMessage() .setParameter("identifierString", identifierString) .setParameter("jsonRequestBPartner", jsonBPartner); } } private void consolidateWithIdentifier(@NonNull final JsonRequestLocationUpsertItem requestItem) { final ExternalIdentifier externalIdentifier = ExternalIdentifier.of(requestItem.getLocationIdentifier()); final JsonRequestLocation jsonLocation = requestItem.getLocation(); switch (externalIdentifier.getType()) { case METASFRESH_ID: // nothing to do; the JsonRequestLocationUpsertItem has no metasfresh-ID to consolidate with break;
case EXTERNAL_REFERENCE: // nothing to do break; case GLN: if (!jsonLocation.isGlnSet()) { jsonLocation.setGln(externalIdentifier.asGLN().getCode()); } break; default: throw new AdempiereException("Unexpected IdentifierString.Type=" + externalIdentifier.getType()) .appendParametersToMessage() .setParameter("externalIdentifier", externalIdentifier) .setParameter("jsonRequestLocationUpsertItem", requestItem); } } private void consolidateWithIdentifier(@NonNull final JsonRequestContactUpsertItem requestItem) { final ExternalIdentifier externalIdentifier = ExternalIdentifier.of(requestItem.getContactIdentifier()); switch (externalIdentifier.getType()) { case METASFRESH_ID: // nothing to do; the JsonRequestContactUpsertItem has no metasfresh-ID to consolidate with break; case EXTERNAL_REFERENCE: // nothing to do break; default: throw new AdempiereException("Unexpected IdentifierString.Type=" + externalIdentifier.getType()) .appendParametersToMessage() .setParameter("externalIdentifier", externalIdentifier) .setParameter("jsonRequestContactUpsertItem", requestItem); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\JsonRequestConsolidateService.java
1
请完成以下Java代码
private void logException(final Throwable e, final String messageText) { log("Error: " + e.getLocalizedMessage(), messageText, // text null, // reference e// isError ); } private void log(final String summary, final String text, final String reference, final Throwable error) { final I_IMP_Processor impProcessor = replicationProcessor.getMImportProcessor(); Services.get(IIMPProcessorBL.class).createLog(impProcessor, summary, text, reference, error); } @Override public void onMessage(@NonNull final Message message) { String text = null; final String messageReference = "onMessage-startAt-millis-" + SystemTime.millis(); try (final IAutoCloseable ignored = setupLoggable(messageReference)) { text = extractMessageBodyAsString(message); Loggables.withLogger(logger, Level.TRACE) .addLog("Received message(text): \n{}", text); importXMLDocument(text); log("Imported Document", text, null, null); // loggable can't store the message-text for us // not sending reply if (StringUtils.isNotEmpty(message.getMessageProperties().getReplyTo())) { Loggables.withLogger(logger, Level.WARN) .addLog("Sending reply currently not supported with RabbitMQ"); } } catch (final RuntimeException e)
{ logException(e, text); } } private String extractMessageBodyAsString(@NonNull final Message message) { final String encoding = message.getMessageProperties().getContentEncoding(); if (Check.isEmpty(encoding)) { Loggables.withLogger(logger, Level.WARN) .addLog("Incoming RabbitMQ message lacks content encoding info; assuming UTF-8; messageId={}", message.getMessageProperties().getMessageId()); return new String(message.getBody(), StandardCharsets.UTF_8); } try { return new String(message.getBody(), encoding); } catch (final UnsupportedEncodingException e) { throw new AdempiereException("Incoming RabbitMQ message has unsupportred encoding='" + encoding + "'; messageId=" + message.getMessageProperties().getMessageId(), e); } } private IAutoCloseable setupLoggable(@NonNull final String reference) { final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class); final I_IMP_Processor importProcessor = replicationProcessor.getMImportProcessor(); return impProcessorBL.setupTemporaryLoggable(importProcessor, reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\imp\RabbitMqListener.java
1
请在Spring Boot框架中完成以下Java代码
protected @NonNull <K, V> ClientRegionFactoryBean<K, V> configureAsLocalClientRegion( @NonNull Environment environment, @NonNull ClientRegionFactoryBean<K, V> clientRegion) { ClientRegionShortcut shortcut = environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY, ClientRegionShortcut.class, LOCAL_CLIENT_REGION_SHORTCUT); clientRegion.setPoolName(null); clientRegion.setShortcut(shortcut); return clientRegion; } public static final class AllClusterNotAvailableConditions extends AllNestedConditions { public AllClusterNotAvailableConditions() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @Conditional(ClusterNotAvailableCondition.class) static class IsClusterNotAvailableCondition { } @Conditional(NotCloudFoundryEnvironmentCondition.class) static class IsNotCloudFoundryEnvironmentCondition { } @Conditional(NotKubernetesEnvironmentCondition.class) static class IsNotKubernetesEnvironmentCondition { } } public static final class ClusterNotAvailableCondition extends ClusterAwareConfiguration.ClusterAwareCondition { @Override public synchronized boolean matches(@NonNull ConditionContext conditionContext, @NonNull AnnotatedTypeMetadata typeMetadata) {
return !super.matches(conditionContext, typeMetadata); } } public static final class NotCloudFoundryEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.CLOUD_FOUNDRY.isActive(context.getEnvironment()); } } public static final class NotKubernetesEnvironmentCondition implements Condition { @Override public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { return !CloudPlatform.KUBERNETES.isActive(context.getEnvironment()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterNotAvailableConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public List<Object> range(String k, long l, long l1){ ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k,l,l1); } /** * set add * @param key * @param value */ public void setAdd(String key,Object value){ SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key,value); } /** * set get * @param key * @return */ public Set<Object> setMembers(String key){ SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } /** * ordered set add * @param key
* @param value * @param scoure */ public void zAdd(String key,Object value,double scoure){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key,value,scoure); } /** * rangeByScore * @param key * @param scoure * @param scoure1 * @return */ public Set<Object> rangeByScore(String key,double scoure,double scoure1){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rangeByScore(key, scoure, scoure1); } }
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\service\RedisService.java
2
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public Integer add() { for(int i=0;i<10000;i++) { String key = "Resume:company:" + getChineseName(); redisTemplate.opsForValue().set(key, i); } return 1000; } @Override public Integer del() { // redisTemplate. return null; } @Override public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } @Override public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } private static String name_sex = ""; public static int getNum(int start,int end) { return (int)(Math.random()*(end-start+1)+start); }
private static String getChineseName() { int index=getNum(0, firstName.length()-1); String first=firstName.substring(index, index+1); int sex=getNum(0,1); String str=boy; int length=boy.length(); if(sex==0){ str=girl; length=girl.length(); name_sex = "女"; }else { name_sex="男"; } index=getNum(0,length-1); String second=str.substring(index, index+1); int hasThird=getNum(0,1); String third=""; if(hasThird==1){ index=getNum(0,length-1); third=str.substring(index, index+1); } return first+second+third; } }
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\service\impl\CompanyServiceImpl.java
2
请完成以下Java代码
public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getUrl() { return url; } @Override public void setUrl(String url) { this.url = url; } @Override public String getContentId() { return contentId; } @Override public void setContentId(String contentId) { this.contentId = contentId; } @Override public ByteArrayEntity getContent() {
return content; } @Override public void setContent(ByteArrayEntity content) { this.content = content; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public String getUserId() { return userId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\AttachmentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public static class RestClientRegistrationClientConfig { @Bean @ConditionalOnMissingBean public RegistrationClient registrationClient(ClientProperties client, RestClient.Builder restClientBuilder, ClientHttpRequestFactoryBuilder<?> clientHttpRequestFactoryBuilder) { var factorySettings = ClientHttpRequestFactorySettings.defaults() .withConnectTimeout(client.getConnectTimeout()) .withReadTimeout(client.getReadTimeout()); var clientHttpRequestFactory = clientHttpRequestFactoryBuilder.build(factorySettings); restClientBuilder = restClientBuilder.requestFactory(clientHttpRequestFactory); if (client.getUsername() != null && client.getPassword() != null) { restClientBuilder = restClientBuilder .requestInterceptor(new BasicAuthenticationInterceptor(client.getUsername(), client.getPassword())); } var restClient = restClientBuilder.build(); return new RestClientRegistrationClient(restClient); } }
@Configuration(proxyBeanMethods = false) @ConditionalOnBean(WebClient.Builder.class) public static class ReactiveRegistrationClientConfig { @Bean @ConditionalOnMissingBean public RegistrationClient registrationClient(ClientProperties client, WebClient.Builder webClient) { if (client.getUsername() != null && client.getPassword() != null) { webClient = webClient.filter(basicAuthentication(client.getUsername(), client.getPassword())); } return new ReactiveRegistrationClient(webClient.build(), client.getReadTimeout()); } } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\config\SpringBootAdminClientAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public ImmutableSet<PriceListId> filterAndListIds(@NonNull final Set<CountryId> countryIds) { return filterAndStreamIds(countryIds) .collect(ImmutableSet.toImmutableSet()); } public Stream<PriceListId> filterAndStreamIds(@NonNull final Set<CountryId> countryIds) { Check.assumeNotEmpty(countryIds, "countryIds is not empty"); return getPriceLists() .stream() .filter(PriceListFilter.builder() .countryIds(ImmutableSet.copyOf(countryIds)) .build()) .map(PriceListsCollection::extractPriceListId) .distinct(); } @NonNull public ImmutableList<I_M_PriceList> getPriceList() { return getPriceLists(); } private static PriceListId extractPriceListId(final I_M_PriceList priceList) { return PriceListId.ofRepoId(priceList.getM_PriceList_ID()); } @Value @Builder static class PriceListFilter implements Predicate<I_M_PriceList> { ImmutableSet<CountryId> countryIds; boolean acceptNoCountry; SOTrx soTrx; CurrencyId currencyId; @Override public boolean test(final I_M_PriceList priceList) { return isCountryMatching(priceList) && isSOTrxMatching(priceList) && isCurrencyMatching(priceList) ; } private boolean isCurrencyMatching(final I_M_PriceList priceList) { if (currencyId == null) { return true; } else { return currencyId.equals(CurrencyId.ofRepoId(priceList.getC_Currency_ID())); } } private boolean isCountryMatching(final I_M_PriceList priceList)
{ if (countryIds == null) { return true; } final CountryId priceListCountryId = CountryId.ofRepoIdOrNull(priceList.getC_Country_ID()); if (priceListCountryId == null && acceptNoCountry) { return true; } if (countryIds.isEmpty()) { return priceListCountryId == null; } else { return countryIds.contains(priceListCountryId); } } private boolean isSOTrxMatching(final I_M_PriceList priceList) { return soTrx == null || soTrx.isSales() == priceList.isSOPriceList(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\PriceListsCollection.java
2
请完成以下Java代码
public ComparatorChain<T> addComparator(Comparator<T> cmp) { final boolean reverse = false; return addComparator(cmp, reverse); } public ComparatorChain<T> addComparator(Comparator<T> cmp, boolean reverse) { Check.assumeNotNull(cmp, "cmp not null"); if (reverse) { comparators.add(new ReverseComparator<T>(cmp)); } else { comparators.add(cmp); } return this; } @Override public int compare(T o1, T o2) { Check.assume(!comparators.isEmpty(), "ComparatorChain contains comparators");
for (final Comparator<T> cmp : comparators) { final int result = cmp.compare(o1, o2); if (result != 0) { return result; } } // assuming that objects are equal if none of child comparators said otherwise return 0; } @Override public String toString() { return "ComparatorChain [comparators=" + comparators + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\ComparatorChain.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_LabelPrinter[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Label printer. @param AD_LabelPrinter_ID Label Printer Definition */ public void setAD_LabelPrinter_ID (int AD_LabelPrinter_ID) { if (AD_LabelPrinter_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, Integer.valueOf(AD_LabelPrinter_ID)); } /** Get Label printer. @return Label Printer Definition */ public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription ()
{ return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinter.java
1
请完成以下Spring Boot application配置
spring: application: name: user-service-consumer # dubbo 配置项,对应 DubboConfigurationProperties 配置类 dubbo: # Dubbo 应用配置 application: name: ${spring.application.name} # 应用名 # Dubbo 注册中心配置 registry: address: zookeeper://127.0.0.1:2181 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/
zh-cn/docs/user/references/registry/introduction.html 文档。 # Dubbo 服务提供者的配置,对应 ConsumerConfig 类 consumer: filter: tracing
repos\SpringBoot-Labs-master\lab-40\lab-40-zipkin-dubbo\lab-40-zipkin-dubbo-consumer\src\main\resources\application.yaml
2
请完成以下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 Times Dunned. @param TimesDunned Number of times dunned previously */ public void setTimesDunned (int TimesDunned) { set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned)); } /** Get Times Dunned. @return Number of times dunned previously */ public int getTimesDunned () { Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned); if (ii == null) return 0;
return ii.intValue(); } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java
1
请完成以下Java代码
public void setMSGRAPH_ClientId (final @Nullable java.lang.String MSGRAPH_ClientId) { set_Value (COLUMNNAME_MSGRAPH_ClientId, MSGRAPH_ClientId); } @Override public java.lang.String getMSGRAPH_ClientId() { return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientId); } @Override public void setMSGRAPH_ClientSecret (final @Nullable java.lang.String MSGRAPH_ClientSecret) { set_Value (COLUMNNAME_MSGRAPH_ClientSecret, MSGRAPH_ClientSecret); } @Override public java.lang.String getMSGRAPH_ClientSecret() { return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientSecret); } @Override public void setMSGRAPH_TenantId (final @Nullable java.lang.String MSGRAPH_TenantId) { set_Value (COLUMNNAME_MSGRAPH_TenantId, MSGRAPH_TenantId); } @Override public java.lang.String getMSGRAPH_TenantId() { return get_ValueAsString(COLUMNNAME_MSGRAPH_TenantId); } @Override public void setPassword (final @Nullable java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public java.lang.String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSMTPHost (final @Nullable java.lang.String SMTPHost) { set_Value (COLUMNNAME_SMTPHost, SMTPHost); } @Override public java.lang.String getSMTPHost() { return get_ValueAsString(COLUMNNAME_SMTPHost); } @Override
public void setSMTPPort (final int SMTPPort) { set_Value (COLUMNNAME_SMTPPort, SMTPPort); } @Override public int getSMTPPort() { return get_ValueAsInt(COLUMNNAME_SMTPPort); } /** * Type AD_Reference_ID=541904 * Reference name: AD_MailBox_Type */ public static final int TYPE_AD_Reference_ID=541904; /** SMTP = smtp */ public static final String TYPE_SMTP = "smtp"; /** MSGraph = msgraph */ public static final String TYPE_MSGraph = "msgraph"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java
1
请完成以下Java代码
public class BackupCodeTwoFaAccountConfig extends TwoFaAccountConfig { @NotEmpty private Set<String> codes; @Override public TwoFaProviderType getProviderType() { return TwoFaProviderType.BACKUP_CODE; } @JsonGetter("codes") private Set<String> getCodesForJson() { if (serializeHiddenFields) { return codes;
} else { return null; } } @JsonGetter private Integer getCodesLeft() { if (codes != null) { return codes.size(); } else { return null; } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\security\model\mfa\account\BackupCodeTwoFaAccountConfig.java
1
请完成以下Java代码
private static void addKeyToQueryBuilder(final BPartnerCompositeLookupKey bpartnerLookupKey, final BPartnerQueryBuilder queryBuilder) { final JsonExternalId jsonExternalId = bpartnerLookupKey.getJsonExternalId(); if (jsonExternalId != null) { queryBuilder.externalId(JsonConverters.fromJsonOrNull(jsonExternalId)); } final String value = bpartnerLookupKey.getCode(); if (isNotBlank(value)) { queryBuilder.bpartnerValue(value.trim()); } final GLN gln = bpartnerLookupKey.getGln(); if (gln != null) { queryBuilder.gln(gln);
} final GlnWithLabel glnWithLabel = bpartnerLookupKey.getGlnWithLabel(); if (glnWithLabel != null) { queryBuilder.gln(glnWithLabel.getGln()); queryBuilder.glnLookupLabel(glnWithLabel.getLabel()); } final MetasfreshId metasfreshId = bpartnerLookupKey.getMetasfreshId(); if (metasfreshId != null) { queryBuilder.bPartnerId(BPartnerId.ofRepoId(metasfreshId.getValue())); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerQueryService.java
1
请在Spring Boot框架中完成以下Java代码
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { OAuthJSONAccessTokenResponse accessTokenResponse = oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { setAccessToken(accessTokenResponse.getAccessToken()); return !getAccessToken().equals(requestAccessToken); } } catch (OAuthSystemException | OAuthProblemException e) { throw new IOException(e); } } return false; } public TokenRequestBuilder getTokenRequestBuilder()
{ return tokenRequestBuilder; } public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { this.tokenRequestBuilder = tokenRequestBuilder; } // Applying authorization to parameters is performed in the retryingIntercept method @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) { // No implementation necessary } }
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\invoker\auth\RetryingOAuth.java
2
请完成以下Java代码
protected Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch (Exception e) { throw LOG.exceptionWhileInteractingWithTransaction("getting transaction", e); } } @Override protected boolean isTransactionActiveInternal() throws Exception { return transactionManager.getStatus() != Status.STATUS_MARKED_ROLLBACK && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION; } public static class JtaTransactionStateSynchronization extends TransactionStateSynchronization implements Synchronization { public JtaTransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) {
super(transactionState, transactionListener, commandContext); } @Override protected boolean isRolledBack(int status) { return Status.STATUS_ROLLEDBACK == status; } @Override protected boolean isCommitted(int status) { return Status.STATUS_COMMITTED == status; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\JakartaTransactionContext.java
1
请完成以下Java代码
public I_M_PriceList_Version getPLV() { return plv; } /* package */void setPlv(I_M_PriceList_Version plv) { this.plv = plv; } private final void loadQtysIfNeeded() { final IUOMDAO uomDAO = Services.get(IUOMDAO.class); if (_loaded) { return; } final I_M_InOutLine firstInOutLine = inOutLines.get(0); // // Vendor Product final int productId = _product.getM_Product_ID(); final UomId productUomId = UomId.ofRepoIdOrNull(_product.getC_UOM_ID()); Check.assumeNotNull(productUomId, "UomId of product={} may not be null", _product); // Define the conversion context (in case we need it) final UOMConversionContext uomConversionCtx = UOMConversionContext.of(ProductId.ofRepoId(_product.getM_Product_ID())); // // UOM final UomId qtyReceivedTotalUomId = UomId.ofRepoId(firstInOutLine.getC_UOM_ID()); // // Iterate Receipt Lines linked to this invoice candidate, extract & aggregate informations from them BigDecimal qtyReceivedTotal = BigDecimal.ZERO; IHandlingUnitsInfo handlingUnitsInfoTotal = null; final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); for (final I_M_InOutLine inoutLine : inOutLines) { if (inoutLine.getM_Product_ID() != productId) { loggable.addLog("Not counting {} because its M_Product_ID={} is not the ID of product {}", new Object[] { inoutLine, inoutLine.getM_Product_ID(), _product }); continue; }
final I_M_InOut inOutRecord = inoutLine.getM_InOut(); // task 09117: we only may count iol that are not reversed, in progress of otherwise "not relevant" final I_M_InOut inout = inoutLine.getM_InOut(); final DocStatus inoutDocStatus = DocStatus.ofCode(inout.getDocStatus()); if (!inoutDocStatus.isCompletedOrClosed()) { loggable.addLog("Not counting {} because its M_InOut has docstatus {}", inoutLine, inOutRecord.getDocStatus()); continue; } final BigDecimal qtyReceived = inoutBL.negateIfReturnMovmenType(inoutLine, inoutLine.getMovementQty()); logger.debug("M_InOut_ID={} has MovementType={}; -> proceeding with qtyReceived={}", inOutRecord.getM_InOut_ID(), inOutRecord.getMovementType(), qtyReceived); final BigDecimal qtyReceivedConv = uomConversionBL.convertQty(uomConversionCtx, qtyReceived, productUomId, qtyReceivedTotalUomId); qtyReceivedTotal = qtyReceivedTotal.add(qtyReceivedConv); final IHandlingUnitsInfo handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(inoutLine); if (handlingUnitsInfo == null) { // do nothing } if (handlingUnitsInfoTotal == null) { handlingUnitsInfoTotal = handlingUnitsInfo; } else { handlingUnitsInfoTotal = handlingUnitsInfoTotal.add(handlingUnitsInfo); } } // // Set loaded values _qtyReceived = qtyReceivedTotal; _qtyReceivedUOM = uomDAO.getById(qtyReceivedTotalUomId); _handlingUnitsInfo = handlingUnitsInfoTotal; _loaded = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InOutLineAsVendorReceipt.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setDocument_Acct_Log_ID (final int Document_Acct_Log_ID) { if (Document_Acct_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, Document_Acct_Log_ID); } @Override public int getDocument_Acct_Log_ID() { return get_ValueAsInt(COLUMNNAME_Document_Acct_Log_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID);
} /** * Type AD_Reference_ID=541967 * Reference name: Document_Acct_Log_Type */ public static final int TYPE_AD_Reference_ID=541967; /** Enqueued = enqueued */ public static final String TYPE_Enqueued = "enqueued"; /** Posting Done = posting_ok */ public static final String TYPE_PostingDone = "posting_ok"; /** Posting Error = posting_error */ public static final String TYPE_PostingError = "posting_error"; @Override public void setType (final @Nullable java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Document_Acct_Log.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Report Line Set. @param PA_ReportLineSet_ID Report Line Set */ public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID) { if (PA_ReportLineSet_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID)); } /** Get Report Line Set. @return Report Line Set */ public int getPA_ReportLineSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID); if (ii == null) return 0; return ii.intValue(); } /** 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportLineSet.java
1
请完成以下Java代码
public BigInteger getKtoNr() { return ktoNr; } public void setKtoNr(BigInteger ktoNr) { this.ktoNr = ktoNr; } public BigInteger getBlz() { return blz; } public void setBlz(BigInteger blz) { this.blz = blz; } public String getAuftragsreferenzNr() { return auftragsreferenzNr; } public void setAuftragsreferenzNr(String auftragsreferenzNr) { this.auftragsreferenzNr = auftragsreferenzNr; } public String getBezugsrefernznr() { return bezugsrefernznr; } public void setBezugsrefernznr(String bezugsrefernznr) { this.bezugsrefernznr = bezugsrefernznr; } public BigInteger getAuszugsNr() { return auszugsNr; } public void setAuszugsNr(BigInteger auszugsNr) { this.auszugsNr = auszugsNr; } public Saldo getAnfangsSaldo() { return anfangsSaldo; } public void setAnfangsSaldo(Saldo anfangsSaldo) {
this.anfangsSaldo = anfangsSaldo; } public Saldo getSchlussSaldo() { return schlussSaldo; } public void setSchlussSaldo(Saldo schlussSaldo) { this.schlussSaldo = schlussSaldo; } public Saldo getAktuellValutenSaldo() { return aktuellValutenSaldo; } public void setAktuellValutenSaldo(Saldo aktuellValutenSaldo) { this.aktuellValutenSaldo = aktuellValutenSaldo; } public Saldo getZukunftValutenSaldo() { return zukunftValutenSaldo; } public void setZukunftValutenSaldo(Saldo zukunftValutenSaldo) { this.zukunftValutenSaldo = zukunftValutenSaldo; } public List<BankstatementLine> getLines() { return lines; } public void setLines(List<BankstatementLine> lines) { this.lines = lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Bankstatement.java
1
请在Spring Boot框架中完成以下Java代码
public String profile(HttpServletRequest request) { Long loginUserId = (long) request.getSession().getAttribute("loginUserId"); Admin adminUser = adminService.getUserDetailById(loginUserId); if (adminUser == null) { return "admin/login"; } request.setAttribute("path", "profile"); request.setAttribute("loginUserName", adminUser.getLoginName()); request.setAttribute("nickName", adminUser.getAdminNickName()); return "admin/profile"; } @PostMapping("/profile/password") @ResponseBody public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword, @RequestParam("newPassword") String newPassword) { if (!StringUtils.hasText(originalPassword) || !StringUtils.hasText(newPassword)) { return "参数不能为空"; } Long loginUserId = (long) request.getSession().getAttribute("loginUserId"); if (adminService.updatePassword(loginUserId, originalPassword, newPassword)) { //修改成功后清空session中的数据,前端控制跳转至登录页 request.getSession().removeAttribute("loginUserId"); request.getSession().removeAttribute("loginUser"); request.getSession().removeAttribute("errorMsg"); return "success"; } else { return "修改失败"; } }
@PostMapping("/profile/name") @ResponseBody public String nameUpdate(HttpServletRequest request, @RequestParam("loginUserName") String loginUserName, @RequestParam("nickName") String nickName) { if (!StringUtils.hasText(loginUserName) || !StringUtils.hasText(nickName)) { return "参数不能为空"; } Long loginUserId = (long) request.getSession().getAttribute("loginUserId"); if (adminService.updateName(loginUserId, loginUserName, nickName)) { return "success"; } else { return "修改失败"; } } @GetMapping("/logout") public String logout(HttpServletRequest request) { request.getSession().removeAttribute("loginUserId"); request.getSession().removeAttribute("loginUser"); request.getSession().removeAttribute("errorMsg"); return "admin/login"; } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\AdminController.java
2
请完成以下Java代码
private static class SLF4JAsGraphLoggerAdapter implements ILogger { @NonNull private final Logger logger; @Override public void setLoggingLevel(@NonNull final LoggerLevel level) { switch (level) { case ERROR: LogManager.setLoggerLevel(logger, Level.WARN); break; case DEBUG: default: LogManager.setLoggerLevel(logger, Level.DEBUG); break; } } @Override public @NonNull LoggerLevel getLoggingLevel() { final Level level = LogManager.getLoggerLevel(logger); if (level == null) { return LoggerLevel.DEBUG; } else if (Level.ERROR.equals(level) || Level.WARN.equals(level)) { return LoggerLevel.ERROR; } else { return LoggerLevel.DEBUG; }
} @Override public void logDebug(@NonNull final String message) { logger.debug(message); } @Override public void logError(@NonNull final String message, @Nullable final Throwable throwable) { logger.warn(message, throwable); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\sender\MicrosoftGraphMailSender.java
1
请完成以下Java代码
public IScriptScanner createScriptScannerByFilename(final String filename) { final IFileRef fileRef = new FileRef(new File(filename)); final IScriptScanner scriptScanner = createScriptScanner(fileRef); if (scriptScanner == null) { throw new RuntimeException("No script scanner found for " + filename); } return scriptScanner; } @Override public IScriptScanner createScriptScanner(final IFileRef fileRef) { final Class<? extends IScriptScanner> scannerClass = getScriptScannerClassOrNull(fileRef); if (scannerClass == null) { return null; } try { final IScriptScanner scriptScanner = scannerClass.getConstructor(IFileRef.class).newInstance(fileRef); scriptScanner.setScriptScannerFactory(this); return scriptScanner; } catch (final Exception e) { throw new ScriptException("Cannot instantiate scanner class: " + scannerClass, e); } } @Override public void registerScriptScannerClass(final String fileExtension, final Class<? extends IScriptScanner> scannerClass) { final String fileExtensionNorm = normalizeFileExtension(fileExtension); final Class<? extends IScriptScanner> scannerClassOld = scriptScannerClasses.put(fileExtensionNorm, scannerClass); if (scannerClassOld != null) { logger.info("Unregistering scanner " + scannerClassOld + " for fileExtension=" + fileExtension); } logger.info("Registering scanner " + scannerClass + " for fileExtension=" + fileExtension); } @Override public void registerScriptScannerClassesFor(final IScriptExecutorFactory scriptExecutorFactory) {
for (final ScriptType scriptType : scriptExecutorFactory.getSupportedScriptTypes()) { registerScriptScannerClass(scriptType.getFileExtension(), SingletonScriptScanner.class); } } private static final String normalizeFileExtension(final String fileExtension) { return fileExtension.trim().toLowerCase(); } @Override public void setScriptFactory(final IScriptFactory scriptFactory) { this.scriptFactory = scriptFactory; } @Override public IScriptFactory getScriptFactoryToUse() { if (scriptFactory != null) { return scriptFactory; } return scriptFactoryDefault; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ScriptScannerFactory.java
1
请完成以下Java代码
public ProcessId getProcessId() { return processDescriptor.getProcessId(); } public AdProcessId getReportAdProcessId() { return huProcessDescriptor.getProcessId(); } public DocumentEntityDescriptor getParametersDescriptor() { return processDescriptor.getParametersDescriptor(); } public WebuiRelatedProcessDescriptor toWebuiRelatedProcessDescriptor() {
return WebuiRelatedProcessDescriptor.builder() .processId(processDescriptor.getProcessId()) .internalName(processDescriptor.getInternalName()) .processCaption(processDescriptor.getCaption()) .processDescription(processDescriptor.getDescription()) .displayPlace(DisplayPlace.ViewQuickActions) .preconditionsResolutionSupplier(ProcessPreconditionsResolution::accept) .build(); } public boolean appliesToHUUnitType(final HuUnitType huUnitType) { return huProcessDescriptor.appliesToHUUnitType(huUnitType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\WebuiHUProcessDescriptor.java
1
请完成以下Java代码
protected List<ConsumerSeekCallback> getSeekCallbacksFor(TopicPartition topicPartition) { return this.topicToCallbacks.get(topicPartition); } /** * The map of callbacks for all currently assigned partitions. * @return the map. * @since 3.3 */ protected Map<TopicPartition, List<ConsumerSeekCallback>> getTopicsAndCallbacks() { return Collections.unmodifiableMap(this.topicToCallbacks); } /** * Return the currently registered callbacks and their associated {@link TopicPartition}(s). * @return the map of callbacks and partitions. * @since 2.6 */ protected Map<ConsumerSeekCallback, List<TopicPartition>> getCallbacksAndTopics() { return Collections.unmodifiableMap(this.callbackToTopics); } /** * Seek all assigned partitions to the beginning. * @since 2.6 */
public void seekToBeginning() { getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToBeginning); } /** * Seek all assigned partitions to the end. * @since 2.6 */ public void seekToEnd() { getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToEnd); } /** * Seek all assigned partitions to the offset represented by the timestamp. * @param time the time to seek to. * @since 2.6 */ public void seekToTimestamp(long time) { getCallbacksAndTopics().forEach((cb, topics) -> cb.seekToTimestamp(topics, time)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\AbstractConsumerSeekAware.java
1
请完成以下Java代码
public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_W_Basket getW_Basket() throws RuntimeException { return (I_W_Basket)MTable.get(getCtx(), I_W_Basket.Table_Name) .getPO(getW_Basket_ID(), get_TrxName()); } /** Set W_Basket_ID. @param W_Basket_ID Web Basket */ public void setW_Basket_ID (int W_Basket_ID) { if (W_Basket_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID)); } /** Get W_Basket_ID. @return Web Basket
*/ public int getW_Basket_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Basket Line. @param W_BasketLine_ID Web Basket Line */ public void setW_BasketLine_ID (int W_BasketLine_ID) { if (W_BasketLine_ID < 1) set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, null); else set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, Integer.valueOf(W_BasketLine_ID)); } /** Get Basket Line. @return Web Basket Line */ public int getW_BasketLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_BasketLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_BasketLine.java
1
请完成以下Java代码
public void add(Element element) { elements.add(element); } public String attribute(String name) { if (attributeMap.containsKey(name)) { return attributeMap.get(name).getValue(); } return null; } public Set<String> attributes() { return attributeMap.keySet(); } public String attributeNS(Namespace namespace, String name) { String attribute = attribute(composeMapKey(namespace.getNamespaceUri(), name)); if (attribute == null && namespace.hasAlternativeUri()) { attribute = attribute(composeMapKey(namespace.getAlternativeUri(), name)); } return attribute; } public String attribute(String name, String defaultValue) { if (attributeMap.containsKey(name)) { return attributeMap.get(name).getValue(); } return defaultValue; } public String attributeNS(Namespace namespace, String name, String defaultValue) { String attribute = attribute(composeMapKey(namespace.getNamespaceUri(), name)); if (attribute == null && namespace.hasAlternativeUri()) { attribute = attribute(composeMapKey(namespace.getAlternativeUri(), name)); } if (attribute == null) { return defaultValue; } return attribute; } protected String composeMapKey(String attributeUri, String attributeName) { StringBuilder strb = new StringBuilder(); if (attributeUri != null && !attributeUri.equals("")) { strb.append(attributeUri); strb.append(":"); } strb.append(attributeName); return strb.toString(); } public List<Element> elements() { return elements; } public String toString() { return "<"+tagName+"..."; }
public String getUri() { return uri; } public String getTagName() { return tagName; } public int getLine() { return line; } public int getColumn() { return column; } /** * Due to the nature of SAX parsing, sometimes the characters of an element * are not processed at once. So instead of a setText operation, we need * to have an appendText operation. */ public void appendText(String text) { this.text.append(text); } public String getText() { return text.toString(); } /** * allows to recursively collect the ids of all elements in the tree. */ public void collectIds(List<String> ids) { ids.add(attribute("id")); for (Element child : elements) { child.collectIds(ids); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Element.java
1
请完成以下Java代码
public int getEXP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Java Class. @param JavaClass Java Class */ public void setJavaClass (String JavaClass) { set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */ public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity
*/ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor_Type.java
1
请完成以下Java代码
public void setDateInvoiced (java.sql.Timestamp DateInvoiced) { set_ValueNoCheck (COLUMNNAME_DateInvoiced, DateInvoiced); } @Override public java.sql.Timestamp getDateInvoiced() { return get_ValueAsTimestamp(COLUMNNAME_DateInvoiced); } @Override public void setdocument (java.lang.String document) { set_ValueNoCheck (COLUMNNAME_document, document); } @Override public java.lang.String getdocument() { return (java.lang.String)get_Value(COLUMNNAME_document); } @Override public void setDocumentNo (java.lang.String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } @Override public void setFirstname (java.lang.String Firstname) { set_ValueNoCheck (COLUMNNAME_Firstname, Firstname); } @Override
public java.lang.String getFirstname() { return (java.lang.String)get_Value(COLUMNNAME_Firstname); } @Override public void setGrandTotal (java.math.BigDecimal GrandTotal) { set_ValueNoCheck (COLUMNNAME_GrandTotal, GrandTotal); } @Override public java.math.BigDecimal getGrandTotal() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLastname (java.lang.String Lastname) { set_ValueNoCheck (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } @Override public void setprintjob (java.lang.String printjob) { set_ValueNoCheck (COLUMNNAME_printjob, printjob); } @Override public java.lang.String getprintjob() { return (java.lang.String)get_Value(COLUMNNAME_printjob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Prt_Bericht_Statistik_List_Per_Org.java
1
请完成以下Java代码
public class ModelApiResponse { @JsonProperty("code") private Integer code = null; @JsonProperty("type") private String type = null; @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { this.code = code; return this; } /** * Get code * @return code **/ @ApiModelProperty(value = "") public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { this.type = type; return this; } /** * Get type * @return type **/ @ApiModelProperty(value = "") public String getType() { return type; } public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { this.message = message; return this; } /** * Get message * @return message **/ @ApiModelProperty(value = "")
public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; return Objects.equals(this.code, _apiResponse.code) && Objects.equals(this.type, _apiResponse.type) && Objects.equals(this.message, _apiResponse.message); } @Override public int hashCode() { return Objects.hash(code, type, message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ModelApiResponse {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
1
请完成以下Java代码
public class C_Doc_Outbound_CreatePDF extends JavaProcess { private final IQueueProcessorFactory queueProcessorFactory = Services.get(IQueueProcessorFactory.class); private final IQueueDAO queueDAO = Services.get(IQueueDAO.class); private final QueueProcessorService queueProcessorService = SpringContextHolder.instance.getBean(QueueProcessorService.class); @Override protected void prepare() { // nothing } @Override protected String doIt() throws Exception
{ final Properties ctx = getCtx(); final I_C_Queue_PackageProcessor packageProcessor = queueDAO.retrievePackageProcessorDefByClass(ctx, DocOutboundWorkpackageProcessor.class); final QueuePackageProcessorId packageProcessorId = QueuePackageProcessorId.ofRepoId(packageProcessor.getC_Queue_PackageProcessor_ID()); final IQueueProcessor queueProcessor = queueProcessorFactory.createAsynchronousQueueProcessor(packageProcessorId); queueProcessorService.runAndWait(queueProcessor); final IQueueProcessorStatistics statistics = queueProcessor.getStatisticsSnapshot(); return "OK/Error #" + statistics.getCountProcessed() + "/" + statistics.getCountErrors(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\process\C_Doc_Outbound_CreatePDF.java
1
请完成以下Java代码
public void setI_IsImported (boolean I_IsImported) { set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported)); } /** Get Importiert. @return Ist dieser Import verarbeitet worden? */ @Override public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override 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 */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @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 URL3. @param URL3 Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public void setURL3 (java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } /** Get URL3. @return Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public java.lang.String getURL3 () { return (java.lang.String)get_Value(COLUMNNAME_URL3); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner_GlobalID.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Relative Priority. @param PromotionPriority Which promotion should be apply to a product */ public void setPromotionPriority (int PromotionPriority)
{ set_Value (COLUMNNAME_PromotionPriority, Integer.valueOf(PromotionPriority)); } /** Get Relative Priority. @return Which promotion should be apply to a product */ public int getPromotionPriority () { Integer ii = (Integer)get_Value(COLUMNNAME_PromotionPriority); 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_Promotion.java
1
请完成以下Java代码
public void setIsNextBusinessDay (final boolean IsNextBusinessDay) { set_Value (COLUMNNAME_IsNextBusinessDay, IsNextBusinessDay); } @Override public boolean isNextBusinessDay() { return get_ValueAsBoolean(COLUMNNAME_IsNextBusinessDay); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setName_Invoice (final @Nullable java.lang.String Name_Invoice) { set_Value (COLUMNNAME_Name_Invoice, Name_Invoice); } @Override public java.lang.String getName_Invoice() { return get_ValueAsString(COLUMNNAME_Name_Invoice); } /** * NetDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int NETDAY_AD_Reference_ID=167; /** Sunday = 7 */ public static final String NETDAY_Sunday = "7"; /** Monday = 1 */ public static final String NETDAY_Monday = "1"; /** Tuesday = 2 */ public static final String NETDAY_Tuesday = "2"; /** Wednesday = 3 */ public static final String NETDAY_Wednesday = "3"; /** Thursday = 4 */ public static final String NETDAY_Thursday = "4";
/** Friday = 5 */ public static final String NETDAY_Friday = "5"; /** Saturday = 6 */ public static final String NETDAY_Saturday = "6"; @Override public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay() { return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentTerm.java
1
请在Spring Boot框架中完成以下Java代码
static PrefixBasedMethodMatcher fromClass(String className, String method) { int lastDotIndex = method.lastIndexOf("."); Assert.isTrue(lastDotIndex != -1 || StringUtils.hasText(className), () -> "'" + method + "' is not a valid method name: format is FQN.methodName"); if (lastDotIndex == -1) { Class<?> javaType = ClassUtils.resolveClassName(className, beanClassLoader); return new PrefixBasedMethodMatcher(javaType, method); } String methodName = method.substring(lastDotIndex + 1); Assert.hasText(methodName, () -> "Method not found for '" + method + "'"); String typeName = method.substring(0, lastDotIndex); Class<?> javaType = ClassUtils.resolveClassName(typeName, beanClassLoader); return new PrefixBasedMethodMatcher(javaType, method); } @Override public ClassFilter getClassFilter() { return this.classFilter; } @Override public MethodMatcher getMethodMatcher() { return this; } @Override public boolean matches(Method method, Class<?> targetClass) { return matches(this.methodPrefix, method.getName()); } @Override public boolean isRuntime() { return false;
} @Override public boolean matches(Method method, Class<?> targetClass, Object... args) { return matches(this.methodPrefix, method.getName()); } private boolean matches(String mappedName, String methodName) { boolean equals = methodName.equals(mappedName); return equals || prefixMatches(mappedName, methodName) || suffixMatches(mappedName, methodName); } private boolean prefixMatches(String mappedName, String methodName) { return mappedName.endsWith("*") && methodName.startsWith(mappedName.substring(0, mappedName.length() - 1)); } private boolean suffixMatches(String mappedName, String methodName) { return mappedName.startsWith("*") && methodName.endsWith(mappedName.substring(1)); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\PrefixBasedMethodMatcher.java
2
请在Spring Boot框架中完成以下Java代码
public class LocalStorageConfiguration { private final StorageProperties storageProperties; public LocalStorageConfiguration(StorageProperties storageProperties) { this.storageProperties = storageProperties; } @Bean public BlobStore blobStore() { Properties properties = new Properties(); properties.setProperty("jclouds.filesystem.basedir", storageProperties.getLocalFileBaseDirectory()); return ContextBuilder .newBuilder("filesystem") .overrides(properties) .build(BlobStoreContext.class) .getBlobStore(); } @Bean public S3Proxy s3Proxy(BlobStore blobStore) { return S3Proxy .builder()
.awsAuthentication(AuthenticationType.NONE, null, null) .blobStore(blobStore) .endpoint(URI.create(storageProperties.getProxyEndpoint())) .build(); } @Bean public S3Client s3Client() { return S3Client .builder() .region(Region.US_EAST_1) .endpointOverride(URI.create(storageProperties.getProxyEndpoint())) .build(); } }
repos\tutorials-master\aws-modules\s3proxy\src\main\java\com\baeldung\s3proxy\LocalStorageConfiguration.java
2
请完成以下Java代码
public class Stack<E> { private E[] stackContent; private int total; public Stack(int capacity) { this.stackContent = (E[]) new Object[capacity]; } public void push(E data) { System.out.println("In base stack push#"); if (total == stackContent.length) { resize(2 * stackContent.length); } stackContent[total++] = data; } public E pop() { if (!isEmpty()) {
E datum = stackContent[total]; stackContent[total--] = null; return datum; } return null; } private void resize(int capacity) { Arrays.copyOf(stackContent, capacity); } public boolean isEmpty() { return total == 0; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-generics\src\main\java\com\baeldung\typeerasure\Stack.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Set<String> getInclude() { return this.include; } public void setInclude(@Nullable Set<String> include) { this.include = include; } public @Nullable Set<String> getExclude() { return this.exclude; } public void setExclude(@Nullable Set<String> exclude) { this.exclude = exclude; } @Override public @Nullable Show getShowDetails() { return this.showDetails; } public void setShowDetails(@Nullable Show showDetails) { this.showDetails = showDetails; } public @Nullable String getAdditionalPath() { return this.additionalPath; } public void setAdditionalPath(@Nullable String additionalPath) { this.additionalPath = additionalPath; } } /**
* Health logging properties. */ public static class Logging { /** * Threshold after which a warning will be logged for slow health indicators. */ private Duration slowIndicatorThreshold = Duration.ofSeconds(10); public Duration getSlowIndicatorThreshold() { return this.slowIndicatorThreshold; } public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) { this.slowIndicatorThreshold = slowIndicatorThreshold; } } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java
2
请完成以下Java代码
public Criteria andSourceTypeBetween(Integer value1, Integer value2) { addCriterion("source_type between", value1, value2, "sourceType"); return (Criteria) this; } public Criteria andSourceTypeNotBetween(Integer value1, Integer value2) { addCriterion("source_type not between", value1, value2, "sourceType"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() {
return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsIntegrationChangeHistoryExample.java
1
请在Spring Boot框架中完成以下Java代码
public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadySetup) { return; } // == create initial privileges Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE"); Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE"); // == create initial roles List<Privilege> adminPrivileges = Arrays.asList(readPrivilege, writePrivilege); createRoleIfNotFound("ROLE_ADMIN", adminPrivileges); List<Privilege> rolePrivileges = new ArrayList<>(); createRoleIfNotFound("ROLE_USER", rolePrivileges); Role adminRole = roleRepository.findByName("ROLE_ADMIN"); User user = new User(); user.setFirstName("Admin"); user.setLastName("Admin"); user.setEmail("admin@test.com"); user.setPassword(passwordEncoder.encode("admin")); user.setRoles(Arrays.asList(adminRole)); user.setEnabled(true); userRepository.save(user); Role basicRole = roleRepository.findByName("ROLE_USER"); User basicUser = new User(); basicUser.setFirstName("User"); basicUser.setLastName("User"); basicUser.setEmail("user@test.com"); basicUser.setPassword(passwordEncoder.encode("user")); basicUser.setRoles(Arrays.asList(basicRole)); basicUser.setEnabled(true); userRepository.save(basicUser); alreadySetup = true; } @Transactional public Privilege createPrivilegeIfNotFound(String name) {
Privilege privilege = privilegeRepository.findByName(name); if (privilege == null) { privilege = new Privilege(name); privilegeRepository.save(privilege); } return privilege; } @Transactional public Role createRoleIfNotFound(String name, Collection<Privilege> privileges) { Role role = roleRepository.findByName(name); if (role == null) { role = new Role(name); role.setPrivileges(privileges); roleRepository.save(role); } return role; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\persistence\SetupDataLoader.java
2
请完成以下Spring Boot application配置
--- logging: file: name: "target/boot-admin-sample-hazelcast.log" management: endpoints: web: exposure: include: "*" endpoint: health: show-details: ALWAYS spring: application: name: spring-boot-admin-sample-hazelcast boot
: admin: client: url: http://localhost:${server.port:8080} profiles: active: - insecure
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-hazelcast\src\main\resources\application.yml
2
请在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 GraphiteProtocol getProtocol() { return this.protocol; } public void setProtocol(GraphiteProtocol protocol) { this.protocol = protocol; } public Boolean getGraphiteTagsEnabled() {
return (this.graphiteTagsEnabled != null) ? this.graphiteTagsEnabled : ObjectUtils.isEmpty(this.tagsAsPrefix); } public void setGraphiteTagsEnabled(Boolean graphiteTagsEnabled) { this.graphiteTagsEnabled = graphiteTagsEnabled; } public String[] getTagsAsPrefix() { return this.tagsAsPrefix; } public void setTagsAsPrefix(String[] tagsAsPrefix) { this.tagsAsPrefix = tagsAsPrefix; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphiteProperties.java
2
请在Spring Boot框架中完成以下Java代码
void configure(ObservationRegistry registry) { registerObservationPredicates(registry); registerGlobalObservationConventions(registry); registerHandlers(registry); registerFilters(registry); customize(registry); } private void registerHandlers(ObservationRegistry registry) { ObservationHandlerGroups groups = new ObservationHandlerGroups(this.observationHandlerGroups.stream().toList()); List<ObservationHandler<?>> orderedHandlers = this.observationHandlers.orderedStream().toList(); groups.register(registry.observationConfig(), orderedHandlers); } private void registerObservationPredicates(ObservationRegistry registry) { this.observationPredicates.orderedStream().forEach(registry.observationConfig()::observationPredicate); }
private void registerGlobalObservationConventions(ObservationRegistry registry) { this.observationConventions.orderedStream().forEach(registry.observationConfig()::observationConvention); } private void registerFilters(ObservationRegistry registry) { this.observationFilters.orderedStream().forEach(registry.observationConfig()::observationFilter); } @SuppressWarnings("unchecked") private void customize(ObservationRegistry registry) { LambdaSafe.callbacks(ObservationRegistryCustomizer.class, this.customizers.orderedStream().toList(), registry) .withLogger(ObservationRegistryConfigurer.class) .invoke((customizer) -> customizer.customize(registry)); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationRegistryConfigurer.java
2
请完成以下Java代码
private int extractSequenceId( @NonNull final ProductCategoryId productCategoryId, @NonNull final Set<ProductCategoryId> seenIds) { final I_M_Product_Category productCategory = loadOutOfTrx(productCategoryId, I_M_Product_Category.class); final int adSequenceId = productCategory.getAD_Sequence_ProductValue_ID(); if (adSequenceId > 0) { // return our result return adSequenceId; } if (productCategory.getM_Product_Category_Parent_ID() > 0) { final ProductCategoryId productCategoryParentId = ProductCategoryId.ofRepoId(productCategory.getM_Product_Category_Parent_ID());
// first, guard against a loop if (!seenIds.add(productCategoryParentId)) { // there is no AD_Sequence_ID for us return -1; } // recurse return extractSequenceId(productCategoryParentId, seenIds); } // there is no AD_Sequence_ID for us return -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\sequence\ProductValueSequenceProvider.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Status Category. @param R_StatusCategory_ID Request Status Category */ public void setR_StatusCategory_ID (int R_StatusCategory_ID) { if (R_StatusCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_StatusCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID)); } /** Get Status Category. @return Request Status Category */ public int getR_StatusCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_StatusCategory.java
1
请完成以下Java代码
public ResponseEntity follow( @PathVariable("username") String username, @AuthenticationPrincipal User user) { return userRepository .findByUsername(username) .map( target -> { FollowRelation followRelation = new FollowRelation(user.getId(), target.getId()); userRepository.saveRelation(followRelation); return profileResponse(profileQueryService.findByUsername(username, user).get()); }) .orElseThrow(ResourceNotFoundException::new); } @DeleteMapping(path = "follow") public ResponseEntity unfollow( @PathVariable("username") String username, @AuthenticationPrincipal User user) { Optional<User> userOptional = userRepository.findByUsername(username); if (userOptional.isPresent()) { User target = userOptional.get(); return userRepository .findRelation(user.getId(), target.getId()) .map( relation -> {
userRepository.removeRelation(relation); return profileResponse(profileQueryService.findByUsername(username, user).get()); }) .orElseThrow(ResourceNotFoundException::new); } else { throw new ResourceNotFoundException(); } } private ResponseEntity profileResponse(ProfileData profile) { return ResponseEntity.ok( new HashMap<String, Object>() { { put("profile", profile); } }); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ProfileApi.java
1
请完成以下Java代码
public class AtomicOperationProcessEnd extends AbstractEventAtomicOperation { private static final Logger LOGGER = LoggerFactory.getLogger(AtomicOperationProcessEnd.class); @Override protected ScopeImpl getScope(InterpretableExecution execution) { return execution.getProcessDefinition(); } @Override protected String getEventName() { return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END; } @Override protected void eventNotificationsCompleted(InterpretableExecution execution) { InterpretableExecution superExecution = execution.getSuperExecution(); SubProcessActivityBehavior subProcessActivityBehavior = null; // copy variables before destroying the ended sub process instance if (superExecution != null) { ActivityImpl activity = (ActivityImpl) superExecution.getActivity(); subProcessActivityBehavior = (SubProcessActivityBehavior) activity.getActivityBehavior(); try { subProcessActivityBehavior.completing(superExecution, execution); } catch (RuntimeException e) { LOGGER.error("Error while completing sub process of execution {}", execution, e); throw e; } catch (Exception e) { LOGGER.error("Error while completing sub process of execution {}", execution, e); throw new ActivitiException("Error while completing sub process of execution " + execution, e); } }
execution.destroy(); execution.remove(); // and trigger execution afterwards if (superExecution != null) { superExecution.setSubProcessInstance(null); try { subProcessActivityBehavior.completed(superExecution); } catch (RuntimeException e) { LOGGER.error("Error while completing sub process of execution {}", execution, e); throw e; } catch (Exception e) { LOGGER.error("Error while completing sub process of execution {}", execution, e); throw new ActivitiException("Error while completing sub process of execution " + execution, e); } } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationProcessEnd.java
1
请在Spring Boot框架中完成以下Java代码
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } @Bean public IBarService barJpaService() { return new BarJpaService(); } @Bean public IBarService barSpringDataJpaService() { return new BarSpringDataJpaService(); } @Bean public IFooService fooHibernateService() { return new FooService(); } @Bean public IBarAuditableService barHibernateAuditableService() { return new BarAuditableService(); } @Bean public IFooAuditableService fooHibernateAuditableService() { return new FooAuditableService(); } @Bean public IBarDao barJpaDao() { return new BarJpaDao(); } @Bean public IBarDao barHibernateDao() { return new BarDao(); } @Bean public IBarAuditableDao barHibernateAuditableDao() { return new BarAuditableDao();
} @Bean public IFooDao fooHibernateDao() { return new FooDao(); } @Bean public IFooAuditableDao fooHibernateAuditableDao() { return new FooAuditableDao(); } private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "true"); // hibernateProperties.setProperty("hibernate.format_sql", "true"); hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\audit\PersistenceConfig.java
2
请完成以下Java代码
public class EmbeddedMongoDBSetup { private static final String MONGODB_HOST = "localhost"; private static final int MONGODB_PORT = 27019; private static final MongodStarter starter = MongodStarter.getDefaultInstance(); private static MongodExecutable _mongodExe; private static MongodProcess _mongod; public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { try { System.out.println("Starting Embedded MongoDB"); initdb(); System.out.println("Embedded MongoDB started"); } catch (IOException e) { System.out.println("Embedded MongoDB starting error !!"); e.printStackTrace(); } }
private void initdb() throws IOException { _mongodExe = starter.prepare(new MongodConfigBuilder() .version(Version.Main.DEVELOPMENT) .net(new Net(MONGODB_HOST, MONGODB_PORT, Network.localhostIsIPv6())) .build()); _mongod = _mongodExe.start(); } public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) { System.out.println("Stopping Embedded MongoDB"); _mongod.stop(); _mongodExe.stop(); System.out.println("Embedded MongoDB stopped !"); } }
repos\tutorials-master\persistence-modules\jnosql\jnosql-artemis\src\main\java\com\baeldung\jnosql\artemis\EmbeddedMongoDBSetup.java
1
请完成以下Java代码
public Optional<GTIN> getGTIN() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.GTIN); if (element == null) { return Optional.empty(); } return GTIN.optionalOfNullableString(element.getValueAsString()); } public Optional<BigDecimal> getWeightInKg() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.ITEM_NET_WEIGHT_KG); if (element == null) { return Optional.empty(); } return Optional.of(element.getValueAsBigDecimal()); } public Optional<LocalDate> getBestBeforeDate() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BEST_BEFORE_DATE); if (element == null)
{ return Optional.empty(); } return Optional.of(element.getValueAsLocalDate()); } public Optional<String> getLotNumber() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BATCH_OR_LOT_NUMBER); if (element == null) { return Optional.empty(); } return Optional.of(element.getValueAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1Elements.java
1
请完成以下Java代码
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 void addOutput(OutputClause output) { this.outputs.add(output); } public List<DecisionRule> getRules() { return rules; } public void addRule(DecisionRule rule) { this.rules.add(rule); } public HitPolicy getHitPolicy() { return hitPolicy; } public void setHitPolicy(HitPolicy hitPolicy) { this.hitPolicy = hitPolicy; } public BuiltinAggregator getAggregation() { return aggregation; } public void setAggregation(BuiltinAggregator aggregation) { this.aggregation = aggregation; }
public DecisionTableOrientation getPreferredOrientation() { return preferredOrientation; } public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) { this.preferredOrientation = preferredOrientation; } public String getOutputLabel() { return outputLabel; } public void setOutputLabel(String outputLabel) { this.outputLabel = outputLabel; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionTable.java
1
请完成以下Java代码
public boolean canMap(Object parameter) { return parameter != null; } public String writeValue(Object value) { try { StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, value); return stringWriter.toString(); } catch (IOException e) { throw LOG.unableToWriteValue(value, e); } } @SuppressWarnings("unchecked") public <T> T readValue(String value, String typeIdentifier) { try { Class<?> cls = Class.forName(typeIdentifier); return (T) readValue(value, cls); } catch (ClassNotFoundException e) { JavaType javaType = constructJavaTypeFromCanonicalString(typeIdentifier); return readValue(value, javaType); } } public <T> T readValue(String value, Class<T> cls) { try { return objectMapper.readValue(value, cls); } catch (JsonParseException e) { throw LOG.unableToReadValue(value, e); } catch (JsonMappingException e) { throw LOG.unableToReadValue(value, e); } catch (IOException e) { throw LOG.unableToReadValue(value, e); } } protected <C> C readValue(String value, JavaType type) { try { return objectMapper.readValue(value, type); } catch (JsonParseException e) { throw LOG.unableToReadValue(value, e); } catch (JsonMappingException e) { throw LOG.unableToReadValue(value, e); } catch (IOException e) { throw LOG.unableToReadValue(value, e);
} } public JavaType constructJavaTypeFromCanonicalString(String canonicalString) { try { return TypeFactory.defaultInstance().constructFromCanonical(canonicalString); } catch (IllegalArgumentException e) { throw LOG.unableToConstructJavaType(canonicalString, e); } } public String getCanonicalTypeName(Object value) { ensureNotNull("value", value); for (TypeDetector typeDetector : typeDetectors) { if (typeDetector.canHandle(value)) { return typeDetector.detectType(value); } } throw LOG.unableToDetectCanonicalType(value); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\JacksonJsonDataFormat.java
1
请完成以下Java代码
public static void main(String[] args) throws IOException { InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml"); String xmlString = readFromInputStream(inputStream); System.out.println("Pretty printing by Transformer"); System.out.println("============================================="); System.out.println(prettyPrintByTransformer(xmlString, 2, true)); System.out.println("============================================="); System.out.println("Pretty printing by Dom4j"); System.out.println("============================================="); System.out.println(prettyPrintByDom4j(xmlString, 8, false)); System.out.println("============================================="); } private static String readPrettyPrintXslt() throws IOException {
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl"); return readFromInputStream(inputStream); } private static String readFromInputStream(InputStream inputStream) throws IOException { StringBuilder resultStringBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { resultStringBuilder.append(line).append("\n"); } } return resultStringBuilder.toString(); } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\prettyprint\XmlPrettyPrinter.java
1
请完成以下Java代码
private void updateProductFromResource(@NonNull final I_M_Product product, @NonNull final I_S_Resource from) { product.setProductType(X_M_Product.PRODUCTTYPE_Resource); product.setS_Resource_ID(from.getS_Resource_ID()); product.setIsActive(from.isActive()); product.setValue("PR" + from.getValue()); // the "PR" is a QnD solution to the possible problem that if the production resource's value is set to its ID (like '1000000") there is probably already a product with the same value. product.setName(from.getName()); product.setDescription(from.getDescription()); } @Override public void onResourceTypeChanged(final I_S_ResourceType resourceTypeRecord) { final Set<ResourceId> resourceIds = queryBL .createQueryBuilder(I_S_Resource.class) // in trx! .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Resource.COLUMNNAME_S_ResourceType_ID, resourceTypeRecord.getS_ResourceType_ID()) .create() .idsAsSet(ResourceId::ofRepoId); if (resourceIds.isEmpty()) { return; } final ResourceType resourceType = toResourceType(resourceTypeRecord); final IProductDAO productsRepo = Services.get(IProductDAO.class); productsRepo.updateProductsByResourceIds(resourceIds, product -> updateProductFromResourceType(product, resourceType)); } private void updateProductFromResourceType(final I_M_Product product, final ResourceType from) { product.setProductType(X_M_Product.PRODUCTTYPE_Resource); product.setC_UOM_ID(from.getDurationUomId().getRepoId()); product.setM_Product_Category_ID(ProductCategoryId.toRepoId(from.getProductCategoryId())); } @Override public ImmutableSet<ResourceId> getResourceIdsByUserId(@NonNull final UserId userId) {
final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Resource.COLUMNNAME_AD_User_ID, userId) .create() .idsAsSet(ResourceId::ofRepoId); } @Override public ImmutableSet<ResourceId> getResourceIdsByResourceTypeIds(@NonNull final Collection<ResourceTypeId> resourceTypeIds) { if (resourceTypeIds.isEmpty()) { return ImmutableSet.of(); } final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_S_Resource.COLUMNNAME_S_ResourceType_ID, resourceTypeIds) .create() .idsAsSet(ResourceId::ofRepoId); } @Override public ImmutableSet<ResourceId> getActivePlantIds() { return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Resource.COLUMNNAME_ManufacturingResourceType, X_S_Resource.MANUFACTURINGRESOURCETYPE_Plant) .create() .idsAsSet(ResourceId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\ResourceDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class RelatedSubscriptionsForOrdersProvider implements RelatedRecordsProvider { @Override public SourceRecordsKey getSourceRecordsKey() { return SourceRecordsKey.of(I_C_Order.Table_Name); } @Override public IPair<SourceRecordsKey, List<ITableRecordReference>> provideRelatedRecords( @NonNull final List<ITableRecordReference> records) { // get the C_Flatrate_Term records that *directly* reference the given orders. final List<OrderId> orderIds = records .stream() .map(ref -> OrderId.ofRepoId(ref.getRecord_ID())) .collect(ImmutableList.toImmutableList()); final IQueryBL queryBL = Services.get(IQueryBL.class); final List<Integer> flatrateTermRecords = queryBL .createQueryBuilder(I_C_Order.class) .addInArrayFilter(I_C_Order.COLUMNNAME_C_Order_ID, orderIds) .addOnlyActiveRecordsFilter()
.andCollectChildren(I_C_OrderLine.COLUMN_C_Order_ID) .addOnlyActiveRecordsFilter() .andCollectChildren(I_C_Flatrate_Term.COLUMN_C_OrderLine_Term_ID) // as of now, extended terms inherit their predecessor's order line ID .addOnlyActiveRecordsFilter() // order latest first, because we need to void them in that order .orderBy().addColumnDescending(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID).endOrderBy() .create() .listIds(); final ImmutableList<ITableRecordReference> resultReferences = flatrateTermRecords .stream() .map(termId -> TableRecordReference.of(I_C_Flatrate_Term.Table_Name, termId)) .collect(ImmutableList.toImmutableList()); // construct the result and be done final SourceRecordsKey resultSourceRecordsKey = SourceRecordsKey.of(I_C_Flatrate_Term.Table_Name); final IPair<SourceRecordsKey, List<ITableRecordReference>> result = ImmutablePair.of(resultSourceRecordsKey, resultReferences); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\order\restart\RelatedSubscriptionsForOrdersProvider.java
2
请完成以下Java代码
public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } public Map<String, Object> getDebugProperties() { final ImmutableMap.Builder<String, Object> debugProperties = ImmutableMap.builder(); if (debugProcessClassname != null) { debugProperties.put("debug-classname", debugProcessClassname); } return debugProperties.build(); } public boolean isDisplayedOn(@NonNull final DisplayPlace displayPlace) { return getDisplayPlaces().contains(displayPlace); } @Value private static class ValueAndDuration<T> { public static <T> ValueAndDuration<T> fromSupplier(final Supplier<T> supplier) {
final Stopwatch stopwatch = Stopwatch.createStarted(); final T value = supplier.get(); final Duration duration = Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS)); return new ValueAndDuration<>(value, duration); } T value; Duration duration; private ValueAndDuration(final T value, final Duration duration) { this.value = value; this.duration = duration; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\WebuiRelatedProcessDescriptor.java
1
请完成以下Java代码
public void invalidateShipmentSchedules(final I_M_Shipment_Constraint constraint, final ModelChangeType changeType) { final Set<IShipmentScheduleSegment> affectedStorageSegments = extractAffectedStorageSegments(constraint, changeType); if (affectedStorageSegments.isEmpty()) { return; } final IShipmentScheduleInvalidateBL invalidSchedulesInvalidator = Services.get(IShipmentScheduleInvalidateBL.class); invalidSchedulesInvalidator.flagSegmentForRecompute(affectedStorageSegments); } private static final Set<IShipmentScheduleSegment> extractAffectedStorageSegments(final I_M_Shipment_Constraint constraint, final ModelChangeType changeType) { final Set<IShipmentScheduleSegment> storageSegments = new LinkedHashSet<>(); if (changeType.isNewOrChange()) { if (constraint.isActive()) { storageSegments.add(createStorageSegment(constraint)); } } if (changeType.isChangeOrDelete()) { final I_M_Shipment_Constraint constraintOld = InterfaceWrapperHelper.createOld(constraint, I_M_Shipment_Constraint.class);
if (constraintOld.isActive()) { storageSegments.add(createStorageSegment(constraintOld)); } } return storageSegments; } private static IShipmentScheduleSegment createStorageSegment(final I_M_Shipment_Constraint constraint) { return ImmutableShipmentScheduleSegment.builder() .anyBPartner() .billBPartnerId(constraint.getBill_BPartner_ID()) .anyProduct() .anyLocator() .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_Shipment_Constraint.java
1
请在Spring Boot框架中完成以下Java代码
public void createDefaultNotificationConfigs() { log.info("Creating default notification configs for system admin"); if (notificationTargetService.countNotificationTargetsByTenantId(TenantId.SYS_TENANT_ID) == 0) { notificationSettingsService.createDefaultNotificationConfigs(TenantId.SYS_TENANT_ID); } PageDataIterable<TenantId> tenants = new PageDataIterable<>(tenantService::findTenantsIds, 500); ExecutorService executor = Executors.newFixedThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 4)); log.info("Creating default notification configs for all tenants"); AtomicInteger count = new AtomicInteger(); for (TenantId tenantId : tenants) { executor.submit(() -> { if (notificationTargetService.countNotificationTargetsByTenantId(tenantId) == 0) { notificationSettingsService.createDefaultNotificationConfigs(tenantId); int n = count.incrementAndGet(); if (n % 500 == 0) { log.info("{} tenants processed", n); } } }); } executor.shutdown(); executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } @Override @SneakyThrows public void updateDefaultNotificationConfigs(boolean updateTenants) { log.info("Updating notification configs..."); notificationSettingsService.updateDefaultNotificationConfigs(TenantId.SYS_TENANT_ID);
if (updateTenants) { PageDataIterable<TenantId> tenants = new PageDataIterable<>(tenantService::findTenantsIds, 500); ExecutorService executor = Executors.newFixedThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 4)); AtomicInteger count = new AtomicInteger(); for (TenantId tenantId : tenants) { executor.submit(() -> { notificationSettingsService.updateDefaultNotificationConfigs(tenantId); int n = count.incrementAndGet(); if (n % 500 == 0) { log.info("{} tenants processed", n); } }); } executor.shutdown(); executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\DefaultSystemDataLoaderService.java
2
请完成以下Java代码
public void setWriteListener(WriteListener listener) { } @Override public boolean isReady() { return true; } }; } public ServletInputStream getInputStream() { ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes()); return new ServletInputStream() { @Override public int read() throws IOException { return body.read(); } @Override
public void setReadListener(ReadListener listener) { } @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return body.available() <= 0; } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
1
请完成以下Java代码
public void afterPropertiesSet() throws Exception { } public ClientConfiguration getClientConfiguration() { return clientConfiguration; } public void setClientConfiguration(ClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } public List<ClientRequestInterceptor> getRequestInterceptors() { return requestInterceptors; } protected void close() { if (client != null) { client.stop(); } } @Autowired(required = false) protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) { PropertySources appliedPropertySources = configurer.getAppliedPropertySources();
propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources); } protected String resolve(String property) { if (propertyResolver == null) { return property; } if (property != null) { return propertyResolver.resolvePlaceholders(property); } else { return null; } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java
1
请完成以下Java代码
public JobDefinitionQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public JobDefinitionQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public JobDefinitionQuery includeJobDefinitionsWithoutTenantId() { this.includeJobDefinitionsWithoutTenantId = true; return this; } // order by /////////////////////////////////////////// public JobDefinitionQuery orderByJobDefinitionId() { return orderBy(JobDefinitionQueryProperty.JOB_DEFINITION_ID); } public JobDefinitionQuery orderByActivityId() { return orderBy(JobDefinitionQueryProperty.ACTIVITY_ID); } public JobDefinitionQuery orderByProcessDefinitionId() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_ID); } public JobDefinitionQuery orderByProcessDefinitionKey() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_KEY); } public JobDefinitionQuery orderByJobType() { return orderBy(JobDefinitionQueryProperty.JOB_TYPE); } public JobDefinitionQuery orderByJobConfiguration() { return orderBy(JobDefinitionQueryProperty.JOB_CONFIGURATION); } public JobDefinitionQuery orderByTenantId() { return orderBy(JobDefinitionQueryProperty.TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefinitionCountByQueryCriteria(this);
} @Override public List<JobDefinition> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefnitionByQueryCriteria(this, page); } // getters ///////////////////////////////////////////// public String getId() { return id; } public String[] getActivityIds() { return activityIds; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getJobType() { return jobType; } public String getJobConfiguration() { return jobConfiguration; } public SuspensionState getSuspensionState() { return suspensionState; } public Boolean getWithOverridingJobPriority() { return withOverridingJobPriority; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java
1
请完成以下Java代码
public void onFailure(Throwable t) { TbMsg next = processException(msg, t); tellFailure(ctx, next, t); } }, ctx.getExternalCallExecutor()); } private TbMsg processPublishResult(TbMsg origMsg, String messageId) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(MESSAGE_ID, messageId); return origMsg.transform() .metaData(metaData) .build(); } private TbMsg processException(TbMsg origMsg, Throwable t) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage()); return origMsg.transform() .metaData(metaData) .build(); }
Publisher initPubSubClient(TbContext ctx) throws IOException { ProjectTopicName topicName = ProjectTopicName.of(config.getProjectId(), config.getTopicName()); ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream( new ByteArrayInputStream(config.getServiceAccountKey().getBytes())); CredentialsProvider credProvider = FixedCredentialsProvider.create(credentials); var retrySettings = RetrySettings.newBuilder() .setTotalTimeout(Duration.ofSeconds(10)) .setInitialRetryDelay(Duration.ofMillis(50)) .setRetryDelayMultiplier(1.1) .setMaxRetryDelay(Duration.ofSeconds(2)) .setInitialRpcTimeout(Duration.ofSeconds(2)) .setRpcTimeoutMultiplier(1) .setMaxRpcTimeout(Duration.ofSeconds(10)) .build(); return Publisher.newBuilder(topicName) .setCredentialsProvider(credProvider) .setRetrySettings(retrySettings) .setExecutorProvider(FixedExecutorProvider.create(ctx.getPubSubRuleNodeExecutorProvider().getExecutor())) .build(); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\gcp\pubsub\TbPubSubNode.java
1