instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public void process(final Exchange exchange) throws Exception
{
final EbayImportOrdersRouteContext importOrdersRouteContext = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_ORDERS_CONTEXT, EbayImportOrdersRouteContext.class);
final Order ebayOrder = importOrdersRouteContext.getOrderNotNull();
final ProductUpsertRequestProducer productUpsertRequestProducer = ProductUpsertRequestProducer.builder()
.orgCode(importOrdersRouteContext.getOrgCode())
.articles(ebayOrder.getLineItems())
.build();
final Optional<ProductRequestProducerResult> productRequestProducerResult = productUpsertRequestProducer.run();
if (productRequestProducerResult.isPresent())
{
|
final ProductUpsertCamelRequest productUpsertCamelRequest = ProductUpsertCamelRequest.builder()
.jsonRequestProductUpsert(productRequestProducerResult.get().getJsonRequestProductUpsert())
.orgCode(importOrdersRouteContext.getOrgCode())
.build();
exchange.getIn().setBody(productUpsertCamelRequest);
}
else
{
exchange.getIn().setBody(null);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\product\CreateProductUpsertReqProcessor.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractManager {
protected EventSubscriptionServiceConfiguration eventSubscriptionServiceConfiguration;
public AbstractManager(EventSubscriptionServiceConfiguration eventSubscriptionServiceConfiguration) {
this.eventSubscriptionServiceConfiguration = eventSubscriptionServiceConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected EventSubscriptionServiceConfiguration getEventSubscriptionServiceConfiguration() {
|
return eventSubscriptionServiceConfiguration;
}
protected Clock getClock() {
return getEventSubscriptionServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getEventSubscriptionServiceConfiguration().getEventDispatcher();
}
protected EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getEventSubscriptionServiceConfiguration().getEventSubscriptionEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\AbstractManager.java
| 2
|
请完成以下Java代码
|
private List<FTSModelIndexer> getModelIndexers(final ConfigAndEvents configAndEvents)
{
return indexersRegistry.getBySourceTableNames(configAndEvents.getSourceTableNames());
}
private boolean isESIndexExists(final FTSConfig config) throws IOException
{
return configService.elasticsearchClient()
.indices()
.exists(new GetIndexRequest(config.getEsIndexName()), RequestOptions.DEFAULT);
}
private void createESIndex(final FTSConfig config) throws IOException
{
configService.elasticsearchClient()
.indices()
.create(new CreateIndexRequest(config.getEsIndexName())
.source(config.getCreateIndexCommand().getAsString(), XContentType.JSON),
RequestOptions.DEFAULT);
}
private void addDocumentsToIndex(
@NonNull final FTSConfig config,
@NonNull final List<ESDocumentToIndexChunk> chunks) throws IOException
{
for (final ESDocumentToIndexChunk chunk : chunks)
{
addDocumentsToIndex(config, chunk);
}
}
private void addDocumentsToIndex(
@NonNull final FTSConfig config,
@NonNull final ESDocumentToIndexChunk chunk) throws IOException
{
final RestHighLevelClient elasticsearchClient = configService.elasticsearchClient();
final String esIndexName = config.getEsIndexName();
final BulkRequest bulkRequest = new BulkRequest();
for (final String documentIdToDelete : chunk.getDocumentIdsToDelete())
{
bulkRequest.add(new DeleteRequest(esIndexName)
.id(documentIdToDelete));
}
for (final ESDocumentToIndex documentToIndex : chunk.getDocumentsToIndex())
{
bulkRequest.add(new IndexRequest(esIndexName)
.id(documentToIndex.getDocumentId())
|
.source(documentToIndex.getJson(), XContentType.JSON));
}
if (bulkRequest.numberOfActions() > 0)
{
elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
}
}
@ToString
private static class ConfigAndEvents
{
@Getter
private final FTSConfig config;
@Getter
private final ImmutableSet<TableName> sourceTableNames;
private final ArrayList<ModelToIndex> events = new ArrayList<>();
private ConfigAndEvents(
@NonNull final FTSConfig config,
@NonNull final ImmutableSet<TableName> sourceTableNames)
{
this.config = config;
this.sourceTableNames = sourceTableNames;
}
public void addEvent(final ModelToIndex event)
{
if (!events.contains(event))
{
events.add(event);
}
}
public ImmutableList<ModelToIndex> getEvents()
{
return ImmutableList.copyOf(events);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelToIndexEnqueueProcessor.java
| 1
|
请完成以下Java代码
|
public String getIpAddress() {
return ipAddress;
}
public Builder setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
public int getPort() {
return port;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public String getTopic() {
return topic;
}
public Builder setTopic(String topic) {
this.topic = topic;
return this;
}
public String getPartition() {
return partition;
}
public Builder setPartition(String partition) {
this.partition = partition;
return this;
}
@Override
public KafkaAppender build() {
return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition));
}
}
|
private KafkaBroker broker;
private KafkaAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, KafkaBroker broker) {
super(name, filter, layout, ignoreExceptions);
this.broker = broker;
}
@Override
public void append(LogEvent event) {
connectAndSendToKafka(broker, event);
}
private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) {
//send to Kafka
}
}
|
repos\tutorials-master\logging-modules\log4j2\src\main\java\com\baeldung\logging\log4j2\plugins\KafkaAppender.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Override
public String toString() {
return "Customer{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\''
+ '}';
}
@Override
public boolean equals(Object o) {
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
var customer = (Customer) o;
if (id != null ? !id.equals(customer.id) : customer.id != null)
return false;
if (firstname != null ? !firstname.equals(customer.firstname) : customer.firstname != null)
return false;
return lastname != null ? lastname.equals(customer.lastname) : customer.lastname == null;
}
@Override
public int hashCode() {
var result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstname != null ? firstname.hashCode() : 0);
result = 31 * result + (lastname != null ? lastname.hashCode() : 0);
return result;
}
}
|
repos\spring-data-examples-main\mongodb\querydsl\src\main\java\example\springdata\mongodb\Customer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<HPAYT1> getHPAYT1() {
if (hpayt1 == null) {
hpayt1 = new ArrayList<HPAYT1>();
}
return this.hpayt1;
}
/**
* Gets the value of the halch1 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 halch1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getHALCH1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link HALCH1 }
*
*
*/
public List<HALCH1> getHALCH1() {
if (halch1 == null) {
halch1 = new ArrayList<HALCH1>();
}
|
return this.halch1;
}
/**
* Gets the value of the detail 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 detail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDETAIL().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DETAILXrech }
*
*
*/
public List<DETAILXrech> getDETAIL() {
if (detail == null) {
detail = new ArrayList<DETAILXrech>();
}
return this.detail;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\HEADERXrech.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Builder assertingPartyMetadata(Consumer<AssertingPartyMetadata.Builder<?>> assertingPartyMetadata) {
assertingPartyMetadata.accept(this.assertingPartyMetadataBuilder);
return this;
}
/**
* Constructs a RelyingPartyRegistration object based on the builder
* configurations
* @return a RelyingPartyRegistration instance
*/
public RelyingPartyRegistration build() {
if (this.singleLogoutServiceResponseLocation == null) {
this.singleLogoutServiceResponseLocation = this.singleLogoutServiceLocation;
}
|
if (this.singleLogoutServiceBindings.isEmpty()) {
this.singleLogoutServiceBindings.add(Saml2MessageBinding.POST);
}
AssertingPartyMetadata party = this.assertingPartyMetadataBuilder.build();
return new RelyingPartyRegistration(this.registrationId, this.entityId,
this.assertionConsumerServiceLocation, this.assertionConsumerServiceBinding,
this.singleLogoutServiceLocation, this.singleLogoutServiceResponseLocation,
this.singleLogoutServiceBindings, party, this.nameIdFormat, this.authnRequestsSigned,
this.decryptionX509Credentials, this.signingX509Credentials);
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\RelyingPartyRegistration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String signup(@ApiParam("Signup User") @RequestBody UserDataDTO user) {
return userService.signup(modelMapper.map(user, User.class));
}
@DeleteMapping(value = "/{username}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "${UserController.delete}")
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
@ApiResponse(code = 404, message = "The user doesn't exist"), //
@ApiResponse(code = 500, message = "Expired or invalid JWT token")})
public String delete(@ApiParam("Username") @PathVariable String username) {
userService.delete(username);
return username;
}
@GetMapping(value = "/{username}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "${UserController.search}", response = UserResponseDTO.class)
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
@ApiResponse(code = 404, message = "The user doesn't exist"), //
@ApiResponse(code = 500, message = "Expired or invalid JWT token")})
|
public UserResponseDTO search(@ApiParam("Username") @PathVariable String username) {
return modelMapper.map(userService.search(username), UserResponseDTO.class);
}
@GetMapping(value = "/me")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_CLIENT')")
@ApiOperation(value = "${UserController.me}", response = UserResponseDTO.class)
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong"), //
@ApiResponse(code = 403, message = "Access denied"), //
@ApiResponse(code = 500, message = "Expired or invalid JWT token")})
public UserResponseDTO whoami(HttpServletRequest req) {
return modelMapper.map(userService.whoami(req), UserResponseDTO.class);
}
}
|
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\controller\UserController.java
| 2
|
请完成以下Spring Boot application配置
|
customer.datasource.host=localhost
customer.datasource.port=30028
customer.datasource.database=test_db
customer.datasource.username=test1
customer.datasource.password=test123
logging.level.root=INFO
lo
|
gging.level.io.debezium.postgres.BinlogReader=INFO
logging.level.io.davidarhcanjo=DEBUG
|
repos\springboot-demo-master\postgre\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public boolean isNew(final Object model)
{
return POWrapper.isNew(model);
}
@Override
public <T> T getValue(final Object model, final String columnName, final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable)
{
if (useOverrideColumnIfAvailable)
{
final IModelInternalAccessor modelAccessor = POWrapper.getModelInternalAccessor(model);
final T value = getValueOverrideOrNull(modelAccessor, columnName);
if (value != null)
{
return value;
}
}
//
final boolean useOldValues = POWrapper.isOldValues(model);
final PO po = POWrapper.getStrictPO(model);
final int idxColumnName = po.get_ColumnIndex(columnName);
if (idxColumnName < 0)
{
if (throwExIfColumnNotFound)
{
throw new AdempiereException("No columnName " + columnName + " found for " + model);
}
else
{
return null;
}
}
if (useOldValues)
{
@SuppressWarnings("unchecked") final T value = (T)po.get_ValueOld(idxColumnName);
return value;
}
else
{
@SuppressWarnings("unchecked") final T value = (T)po.get_Value(idxColumnName);
return value;
}
}
@Override
public boolean isValueChanged(final Object model, final String columnName)
{
return POWrapper.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
return POWrapper.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
return POWrapper.isNull(model, columnName);
}
@Nullable
@Override
public <T> T getDynAttribute(final @NonNull Object model, final String attributeName)
{
return POWrapper.getDynAttribute(model, attributeName);
}
|
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return POWrapper.setDynAttribute(model, attributeName, value);
}
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier)
{
return POWrapper.computeDynAttributeIfAbsent(model, attributeName, supplier);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
// always strict, else other wrapper helpers will handle it!
return POWrapper.getStrictPO(model);
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return POWrapper.getStrictPO(model);
}
@Override
public boolean isCopy(final Object model) {return POWrapper.getStrictPO(model).isCopiedFromOtherRecord();}
@Override
public boolean isCopying(final Object model) {return POWrapper.getStrictPO(model).isCopying();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POInterfaceWrapperHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getDefaultCount() {
return Boolean.valueOf(getProperty("defaultCount"));
}
public void setDefaultCount(Boolean defaultCount) {
setProperty("defaultCount", defaultCount.toString());
}
public String getDialectAlias() {
return getProperty("dialectAlias");
}
public void setDialectAlias(String dialectAlias) {
setProperty("dialectAlias", dialectAlias);
}
public String getAutoDialectClass() {
return getProperty("autoDialectClass");
}
public void setAutoDialectClass(String autoDialectClass) {
setProperty("autoDialectClass", autoDialectClass);
}
public Boolean getAsyncCount() {
return Boolean.valueOf(getProperty("asyncCount"));
}
public void setAsyncCount(Boolean asyncCount) {
setProperty("asyncCount", asyncCount.toString());
}
public String getCountSqlParser() {
|
return getProperty("countSqlParser");
}
public void setCountSqlParser(String countSqlParser) {
setProperty("countSqlParser", countSqlParser);
}
public String getOrderBySqlParser() {
return getProperty("orderBySqlParser");
}
public void setOrderBySqlParser(String orderBySqlParser) {
setProperty("orderBySqlParser", orderBySqlParser);
}
public String getSqlServerSqlParser() {
return getProperty("sqlServerSqlParser");
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
setProperty("sqlServerSqlParser", sqlServerSqlParser);
}
public void setBannerEnabled(Boolean bannerEnabled) {
setProperty("banner",bannerEnabled.toString());
}
public Boolean getBannerEnabled() {
return Boolean.valueOf(getProperty("banner"));
}
}
|
repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperProperties.java
| 2
|
请完成以下Java代码
|
public Builder setNetAmtToInvoice(BigDecimal netAmtToInvoice)
{
this.netAmtToInvoice = netAmtToInvoice;
return this;
}
public Builder setNetAmtInvoiced(BigDecimal netAmtInvoiced)
{
this.netAmtInvoiced = netAmtInvoiced;
return this;
}
public Builder setDiscount(BigDecimal discount)
{
this.discount = discount;
return this;
}
public Builder setCurrencyISOCode(String currencyISOCode)
{
|
this.currencyISOCode = currencyISOCode;
return this;
}
public Builder setInvoiceRuleName(String invoiceRuleName)
{
this.invoiceRuleName = invoiceRuleName;
return this;
}
public Builder setHeaderAggregationKey(String headerAggregationKey)
{
this.headerAggregationKey = headerAggregationKey;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidateRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() {
return s -> JSON.parseArray(s, ApiDefinitionEntity.class);
}
/**
* 网关flowRule
*
* @return
* @throws Exception
*/
@Bean
public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {
return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);
}
|
@Bean
public ConfigService nacosConfigService() throws Exception {
Properties properties=new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr());
if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){
properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){
properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){
properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace());
}
return ConfigFactory.createConfigService(properties);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\SentinelConfig.java
| 2
|
请完成以下Java代码
|
public void setResources(Map<String, EngineResource> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getDerivedFrom() {
|
return null;
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getEngineVersion() {
return null;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "AppDeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean bucketExists(String bucketName) {
try {
HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
.bucket(bucketName)
.build();
s3Client.headBucket(headBucketRequest);
return true;
} catch (S3Exception e) {
// 如果状态码是 404 (Not Found), 说明存储桶不存在
if (e.statusCode() == 404) {
log.error("存储桶 '{}' 不存在。", bucketName);
return false;
}
// 其他异常 (如 403 Forbidden) 说明存在问题,但不能断定它不存在
throw new BadRequestException("检查存储桶时出错: " + e.awsErrorDetails().errorMessage());
}
}
/**
* 创建云存储桶
* @param bucketName 存储桶名称
*/
private boolean createBucket(String bucketName) {
try {
// 使用 S3Waiter 等待存储桶创建完成
|
S3Waiter s3Waiter = s3Client.waiter();
CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
.bucket(bucketName)
.acl(BucketCannedACL.PRIVATE)
.build();
s3Client.createBucket(bucketRequest);
// 等待直到存储桶创建完成
HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
.bucket(bucketName)
.build();
// 使用 WaiterResponse 等待存储桶存在
WaiterResponse<HeadBucketResponse> waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait);
waiterResponse.matched().response().ifPresent(response ->
log.info("存储桶 '{}' 创建成功,状态: {}", bucketName, response.sdkHttpResponse().statusCode())
);
} catch (BucketAlreadyOwnedByYouException e) {
log.warn("存储桶 '{}' 已经被您拥有,无需重复创建。", bucketName);
} catch (S3Exception e) {
throw new BadRequestException("创建存储桶时出错: " + e.awsErrorDetails().errorMessage());
}
return true;
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\service\impl\S3StorageServiceImpl.java
| 2
|
请完成以下Java代码
|
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
// Default constructor for Gson
public StudentV2() {
}
public StudentV2(String firstName, String lastName, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
}
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StudentV2))
return false;
StudentV2 studentV2 = (StudentV2) o;
return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, major);
}
}
|
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\StudentV2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void subscribed(final URL url, final NotifyListener listener) {
if (Constants.ANY_VALUE.equals(url.getServiceInterface())) {
new Thread(new Runnable() {
public void run() {
Map<String, List<URL>> map = new HashMap<String, List<URL>>();
for (URL u : getRegistered()) {
if (UrlUtils.isMatch(url, u)) {
String service = u.getServiceInterface();
List<URL> list = map.get(service);
if (list == null) {
list = new ArrayList<URL>();
map.put(service, list);
}
list.add(u);
}
}
for (List<URL> list : map.values()) {
try {
listener.notify(list);
} catch (Throwable e) {
logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener);
}
}
}
}, "DubboMonitorNotifier").start();
} else {
List<URL> list = lookup(url);
try {
listener.notify(list);
} catch (Throwable e) {
logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener);
}
}
}
|
public void disconnect() {
String client = RpcContext.getContext().getRemoteAddressString();
if (logger.isInfoEnabled()) {
logger.info("Disconnected " + client);
}
Set<URL> urls = remoteRegistered.get(client);
if (urls != null && urls.size() > 0) {
for (URL url : urls) {
unregister(url);
}
}
Map<URL, Set<NotifyListener>> listeners = remoteSubscribed.get(client);
if (listeners != null && listeners.size() > 0) {
for (Map.Entry<URL, Set<NotifyListener>> entry : listeners.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
unsubscribe(url, listener);
}
}
}
}
}
|
repos\tutorials-master\microservices-modules\dubbo\src\main\java\com\alibaba\dubbo\registry\simple\SimpleRegistryService.java
| 2
|
请完成以下Java代码
|
public String getName() {
return getVariableName();
}
// entity lifecycle /////////////////////////////////////////////////////////
public void postLoad() {
// make sure the serializer is initialized
typedValueField.postLoad();
}
// getters and setters //////////////////////////////////////////////////////
public String getTypeName() {
return typedValueField.getTypeName();
}
public String getVariableTypeName() {
return getTypeName();
}
public Date getTime() {
return timestamp;
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[variableName=" + variableName
+ ", variableInstanceId=" + variableInstanceId
+ ", revision=" + revision
+ ", serializerName=" + serializerName
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", byteArrayId=" + byteArrayId
+ ", activityInstanceId=" + activityInstanceId
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", id=" + id
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", timestamp=" + timestamp
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
| 1
|
请完成以下Java代码
|
public static ProcessEngineConfiguration parseProcessEngineConfiguration(Resource springResource, String beanName) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
xmlBeanDefinitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
xmlBeanDefinitionReader.loadBeanDefinitions(springResource);
// Check non singleton beans for types
// Do not eagerly initialize FactorBeans when getting BeanFactoryPostProcessor beans
Collection<BeanFactoryPostProcessor> factoryPostProcessors = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class, true, false).values();
if (factoryPostProcessors.isEmpty()) {
factoryPostProcessors = Collections.singleton(new PropertyPlaceholderConfigurer());
}
for (BeanFactoryPostProcessor factoryPostProcessor : factoryPostProcessors) {
factoryPostProcessor.postProcessBeanFactory(beanFactory);
}
|
ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) beanFactory.getBean(beanName);
processEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(beanFactory));
return processEngineConfiguration;
}
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
Resource springResource = new InputStreamResource(inputStream);
return parseProcessEngineConfiguration(springResource, beanName);
}
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromResource(String resource, String beanName) {
Resource springResource = new ClassPathResource(resource);
return parseProcessEngineConfiguration(springResource, beanName);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cfg\BeansConfigurationHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onDeviceInactivityTimeoutUpdate(TenantId tenantId, DeviceId deviceId, long inactivityTimeout, TbCallback callback) {
forwardToDeviceStateService(tenantId, deviceId,
deviceStateService -> {
log.debug("[{}][{}] Forwarding device inactivity timeout update to local service. Updated inactivity timeout: [{}].", tenantId.getId(), deviceId.getId(), inactivityTimeout);
deviceStateService.onDeviceInactivityTimeoutUpdate(tenantId, deviceId, inactivityTimeout);
},
() -> {
log.debug("[{}][{}] Sending device inactivity timeout update message to core. Updated inactivity timeout: [{}].", tenantId.getId(), deviceId.getId(), inactivityTimeout);
var deviceInactivityTimeoutUpdateMsg = TransportProtos.DeviceInactivityTimeoutUpdateProto.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setDeviceIdMSB(deviceId.getId().getMostSignificantBits())
.setDeviceIdLSB(deviceId.getId().getLeastSignificantBits())
.setInactivityTimeout(inactivityTimeout)
.build();
return TransportProtos.ToCoreMsg.newBuilder()
.setDeviceInactivityTimeoutUpdateMsg(deviceInactivityTimeoutUpdateMsg)
.build();
}, callback);
}
private void forwardToDeviceStateService(
TenantId tenantId, DeviceId deviceId,
Consumer<DeviceStateService> toDeviceStateService,
Supplier<TransportProtos.ToCoreMsg> toCore,
|
TbCallback callback
) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, deviceId);
if (serviceInfoProvider.isService(ServiceType.TB_CORE) && tpi.isMyPartition() && deviceStateService.isPresent()) {
try {
toDeviceStateService.accept(deviceStateService.get());
} catch (Exception e) {
log.error("[{}][{}] Failed to process device connectivity event.", tenantId.getId(), deviceId.getId(), e);
callback.onFailure(e);
return;
}
callback.onSuccess();
} else {
TransportProtos.ToCoreMsg toCoreMsg = toCore.get();
clusterService.pushMsgToCore(tpi, deviceId.getId(), toCoreMsg, new SimpleTbQueueCallback(__ -> callback.onSuccess(), callback::onFailure));
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\state\DefaultDeviceStateManager.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getCode()
{
return code;
}
@Nullable
public static RowType forCodeOrNull(@Nullable final String code)
{
if (code == null)
{
return null;
}
for (final RowType d : values())
{
if (d.getCode().equals(code))
{
return d;
}
}
return null;
}
}
public static class Builder
{
@Nullable
private String noNameHeaderPrefix = DEFAULT_UnknownHeaderPrefix;
private boolean considerNullStringAsNull = false;
private boolean considerEmptyStringAsNull = false;
private String rowNumberMapKey = null;
private boolean discardRepeatingHeaders = false;
private boolean useTypeColumn = true;
private Builder()
{
super();
}
public ExcelToMapListConverter build()
{
return new ExcelToMapListConverter(this);
}
/**
* Sets the header prefix to be used if the header columns is null or black.
*
* Set it to <code>null</code> to turn it off and get rid of columns without header.
*
* @see #setDiscardNoNameHeaders()
*/
public Builder setNoNameHeaderPrefix(@Nullable final String noNameHeaderPrefix)
{
this.noNameHeaderPrefix = noNameHeaderPrefix;
return this;
}
public Builder setDiscardNoNameHeaders()
{
setNoNameHeaderPrefix(null);
return this;
}
/**
* Sets if a cell value which is a null string (i.e. {@link ExcelToMapListConverter#NULLStringMarker}) shall be considered as <code>null</code>.
*/
|
public Builder setConsiderNullStringAsNull(final boolean considerNullStringAsNull)
{
this.considerNullStringAsNull = considerNullStringAsNull;
return this;
}
public Builder setConsiderEmptyStringAsNull(final boolean considerEmptyStringAsNull)
{
this.considerEmptyStringAsNull = considerEmptyStringAsNull;
return this;
}
public Builder setRowNumberMapKey(final String rowNumberMapKey)
{
this.rowNumberMapKey = rowNumberMapKey;
return this;
}
/**
* Sets if we shall detect repeating headers and discard them.
*/
public Builder setDiscardRepeatingHeaders(final boolean discardRepeatingHeaders)
{
this.discardRepeatingHeaders = discardRepeatingHeaders;
return this;
}
/**
* If enabled, the XLS converter will look for first not null column and it will expect to have one of the codes from {@link RowType}.
* If no row type would be found, the row would be ignored entirely.
*
* task 09045
*/
public Builder setUseRowTypeColumn(final boolean useTypeColumn)
{
this.useTypeColumn = useTypeColumn;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelToMapListConverter.java
| 2
|
请完成以下Java代码
|
public java.lang.String getColumnName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Aufsteigender.
@param IsAscending Aufsteigender */
@Override
public void setIsAscending (boolean IsAscending)
{
set_Value (COLUMNNAME_IsAscending, Boolean.valueOf(IsAscending));
}
/** Get Aufsteigender.
@return Aufsteigender */
@Override
public boolean isAscending ()
{
Object oo = get_Value(COLUMNNAME_IsAscending);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line.java
| 1
|
请完成以下Java代码
|
protected void initializeTaskCandidateUsers(TaskEntity task, VariableScope variableScope) {
Set<Expression> candidateUserIdExpressions = taskDefinition.getCandidateUserIdExpressions();
for (Expression userIdExpr : candidateUserIdExpressions) {
Object value = userIdExpr.getValue(variableScope);
if (value instanceof String) {
List<String> candiates = extractCandidates((String) value);
task.addCandidateUsers(candiates);
} else if (value instanceof Collection) {
task.addCandidateUsers((Collection) value);
} else {
throw new ProcessEngineException("Expression did not resolve to a string or collection of strings");
}
}
}
/**
* Extract a candidate list from a string.
*/
protected List<String> extractCandidates(String str) {
|
return Arrays.asList(str.split("[\\s]*,[\\s]*"));
}
// getters ///////////////////////////////////////////////////////////////
public TaskDefinition getTaskDefinition() {
return taskDefinition;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
protected BusinessCalendar getBusinessCalender() {
return Context
.getProcessEngineConfiguration()
.getBusinessCalendarManager()
.getBusinessCalendar(DueDateBusinessCalendar.NAME);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDecorator.java
| 1
|
请完成以下Java代码
|
public static String resolvePassword(String input){
if(oConvertUtils.isEmpty(input)){
return input;
}
// 1. 先尝试新版
try{
String p = decryptPkcs5(input);
return clean(p);
}catch(Exception ignore){
//log.debug("【AES解密】Password not AES PKCS5 cipher, try legacy.");
}
// 2. 回退旧版
try{
String legacy = decryptLegacyNoPadding(input);
return clean(legacy);
}catch(Exception e){
log.debug("【AES解密】Password not AES cipher, raw used.");
}
// 3. 视为明文
return input;
}
/* -------- 可选:统一清理尾部不可见控制字符 -------- */
private static String clean(String s){
if(s==null) return null;
// 去除结尾控制符/空白(不影响中间合法空格)
return s.replaceAll("[\\p{Cntrl}]+","").trim();
}
/* -------- 若仍需要旧接口,可保留 (不建议再用于新前端) -------- */
@Deprecated
public static String desEncrypt(String data) throws Exception {
return decryptLegacyNoPadding(data);
}
/* 加密(若前端不再使用,可忽略;保留旧实现避免影响历史) */
@Deprecated
public static String encrypt(String data) throws Exception {
try{
|
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength += (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.encodeToString(encrypted);
}catch(Exception e){
throw new IllegalStateException("legacy encrypt error", e);
}
}
// public static void main(String[] args) throws Exception {
// // 前端 CBC/Pkcs7 密文测试
// String frontCipher = encrypt("sa"); // 仅验证管道是否可用(旧方式)
// System.out.println(resolvePassword(frontCipher));
// }
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\encryption\AesEncryptUtil.java
| 1
|
请完成以下Java代码
|
public boolean isValueAggregate ()
{
Object oo = get_Value(COLUMNNAME_IsValueAggregate);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Merkmal.
@param M_Attribute_ID
Produkt-Merkmal
*/
@Override
public void setM_Attribute_ID (int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_Value (COLUMNNAME_M_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID));
}
/** Get Merkmal.
@return Produkt-Merkmal
*/
@Override
public int getM_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Gruppenname.
@param ValueAggregateName Gruppenname */
@Override
public void setValueAggregateName (java.lang.String ValueAggregateName)
{
set_Value (COLUMNNAME_ValueAggregateName, ValueAggregateName);
}
/** Get Gruppenname.
@return Gruppenname */
@Override
public java.lang.String getValueAggregateName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValueAggregateName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Attribute.java
| 1
|
请完成以下Java代码
|
public void setC_RfQ_Topic(de.metas.rfq.model.I_C_RfQ_Topic C_RfQ_Topic)
{
set_ValueFromPO(COLUMNNAME_C_RfQ_Topic_ID, de.metas.rfq.model.I_C_RfQ_Topic.class, C_RfQ_Topic);
}
/** Set Ausschreibungs-Thema.
@param C_RfQ_Topic_ID
Topic for Request for Quotations
*/
@Override
public void setC_RfQ_Topic_ID (int C_RfQ_Topic_ID)
{
if (C_RfQ_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, Integer.valueOf(C_RfQ_Topic_ID));
}
/** Get Ausschreibungs-Thema.
@return Topic for Request for Quotations
*/
@Override
public int getC_RfQ_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set RfQ Subscriber.
@param C_RfQ_TopicSubscriber_ID
Request for Quotation Topic Subscriber
*/
@Override
public void setC_RfQ_TopicSubscriber_ID (int C_RfQ_TopicSubscriber_ID)
{
if (C_RfQ_TopicSubscriber_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, Integer.valueOf(C_RfQ_TopicSubscriber_ID));
}
/** Get RfQ Subscriber.
@return Request for Quotation Topic Subscriber
*/
@Override
public int getC_RfQ_TopicSubscriber_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum der Abmeldung.
@param OptOutDate
Date the contact opted out
*/
@Override
public void setOptOutDate (java.sql.Timestamp OptOutDate)
{
set_Value (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Datum der Abmeldung.
@return Date the contact opted out
*/
@Override
public java.sql.Timestamp getOptOutDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
/** Set Anmeldung.
@param SubscribeDate
Date the contact actively subscribed
*/
@Override
public void setSubscribeDate (java.sql.Timestamp SubscribeDate)
{
set_Value (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Anmeldung.
@return Date the contact actively subscribed
*/
@Override
public java.sql.Timestamp getSubscribeDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java
| 1
|
请完成以下Java代码
|
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代码
|
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public String[] getProcessDefinitionIdIn() {
return processDefinitionIdIn;
}
public String[] getProcessDefinitionKeyIn() {
return processDefinitionKeyIn;
}
|
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public String getReportPeriodUnitName() {
return durationPeriodUnit.name();
}
protected class ExecuteDurationReportCmd implements Command<List<DurationReportResult>> {
@Override
public List<DurationReportResult> execute(CommandContext commandContext) {
return executeDurationReport(commandContext);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricProcessInstanceReportImpl.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminEurekaApplication.class, args);
}
@Bean
@Profile("insecure")
public SecurityWebFilterChain securityWebFilterChainPermitAll(ServerHttpSecurity http) {
return http.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().permitAll())
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.build();
}
@Bean
@Profile("secure")
public SecurityWebFilterChain securityWebFilterChainSecure(ServerHttpSecurity http) {
return http
.authorizeExchange(
(authorizeExchange) -> authorizeExchange.pathMatchers(this.adminServer.path("/assets/**"))
.permitAll()
.pathMatchers("/actuator/health/**")
.permitAll()
.pathMatchers(this.adminServer.path("/login"))
.permitAll()
.anyExchange()
.authenticated())
|
.formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
.authenticationSuccessHandler(loginSuccessHandler(this.adminServer.path("/"))))
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))
.logoutSuccessHandler(logoutSuccessHandler(this.adminServer.path("/login?logout"))))
.httpBasic(Customizer.withDefaults())
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.build();
}
// The following two methods are only required when setting a custom base-path (see
// 'basepath' profile in application.yml)
private ServerLogoutSuccessHandler logoutSuccessHandler(String uri) {
RedirectServerLogoutSuccessHandler successHandler = new RedirectServerLogoutSuccessHandler();
successHandler.setLogoutSuccessUrl(URI.create(uri));
return successHandler;
}
private ServerAuthenticationSuccessHandler loginSuccessHandler(String uri) {
RedirectServerAuthenticationSuccessHandler successHandler = new RedirectServerAuthenticationSuccessHandler();
successHandler.setLocation(URI.create(uri));
return successHandler;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\java\de\codecentric\boot\admin\SpringBootAdminEurekaApplication.java
| 1
|
请完成以下Java代码
|
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public void setCaseExecutionId(String caseExecutionId) {
this.caseExecutionId = caseExecutionId;
}
public String getErrorMessage() {
return typedValueField.getErrorMessage();
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
|
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", processDefinitionKey=" + processDefinitionKey
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", executionId=" + executionId
+ ", tenantId=" + tenantId
+ ", activityInstanceId=" + activityInstanceId
+ ", caseDefinitionKey=" + caseDefinitionKey
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", caseExecutionId=" + caseExecutionId
+ ", name=" + name
+ ", createTime=" + createTime
+ ", revision=" + revision
+ ", serializerName=" + getSerializerName()
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", state=" + state
+ ", byteArrayId=" + getByteArrayId()
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SimpleCLI implements CommandMarker {
private String getContentsOfUrlAsString(URL url) {
StringBuilder sb = new StringBuilder();
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
}
} catch (IOException ex) {
sb.append("ERROR");
}
return sb.toString();
}
@CliCommand(value = { "web-get", "wg" }, help = "Displays the contents of a URL.")
public String webGet(@CliOption(key = { "", "url" }, help = "URL whose contents will be displayed.") URL url) {
return getContentsOfUrlAsString(url);
}
@CliCommand(value = { "web-save", "ws" }, help = "Saves the contents of a URL.")
public String webSave(@CliOption(key = { "", "url" }, help = "URL whose contents will be saved.") URL url, @CliOption(key = { "out", "file" }, mandatory = true, help = "The name of the file.") String file) {
String contents = getContentsOfUrlAsString(url);
try (PrintWriter out = new PrintWriter(file)) {
out.write(contents);
} catch (FileNotFoundException ex) {
// Ignore
}
return "Done.";
|
}
private boolean adminEnableExecuted = false;
@CliAvailabilityIndicator(value = { "web-save" })
public boolean isAdminEnabled() {
return adminEnableExecuted;
}
@CliCommand(value = "admin-enable")
public String adminEnable() {
adminEnableExecuted = true;
return "Admin commands enabled.";
}
@CliCommand(value = "admin-disable")
public String adminDisable() {
adminEnableExecuted = false;
return "Admin commands disabled.";
}
}
|
repos\tutorials-master\spring-shell\src\main\java\com\baeldung\shell\simple\SimpleCLI.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean exist(String processDefinitionKey) {
ProcessDefinitionQuery processDefinitionQuery
= createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
long count = processDefinitionQuery.count();
return count > 0 ? true : false;
}
@Override
public Deployment deploy(String name, String tenantId, String category, InputStream in) {
return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in)
.name(name)
.tenantId(tenantId)
.category(category)
.deploy();
}
@Override
public ProcessDefinition queryByProcessDefinitionKey(String processDefinitionKey) {
ProcessDefinition processDefinition
= createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.active().singleResult();
return processDefinition;
}
|
@Override
public Deployment deployName(String deploymentName) {
List<Deployment> list = repositoryService
.createDeploymentQuery()
.deploymentName(deploymentName).list();
Assert.notNull(list, "list must not be null");
return list.get(0);
}
@Override
public void addCandidateStarterUser(String processDefinitionKey, String userId) {
repositoryService.addCandidateStarterUser(processDefinitionKey, userId);
}
}
|
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\service\handler\ProcessHandler.java
| 2
|
请完成以下Java代码
|
public class UpdateService {
/**
* 设置集合名称
*/
private static final String COLLECTION_NAME = "users";
@Resource
private MongoTemplate mongoTemplate;
/**
* 更新集合中【匹配】查询到的第一条文档数据,如果没有找到就【创建并插入一个新文档】
*
* @return 执行更新的结果
*/
public Object update() {
// 创建条件对象
Criteria criteria = Criteria.where("age").is(30);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 创建更新对象,并设置更新的内容
Update update = new Update().set("age", 33).set("name", "zhangsansan");
// 执行更新,如果没有找到匹配查询的文档,则创建并插入一个新文档
UpdateResult result = mongoTemplate.upsert(query, update, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "匹配到" + result.getMatchedCount() + "条数据,对第一条数据进行了更改";
log.info("更新结果:{}", resultInfo);
return resultInfo;
}
/**
* 更新集合中【匹配】查询到的【文档数据集合】中的【第一条数据】
*
* @return 执行更新的结果
*/
public Object updateFirst() {
// 创建条件对象
|
Criteria criteria = Criteria.where("name").is("zhangsan");
// 创建查询对象,然后将条件对象添加到其中,并设置排序
Query query = new Query(criteria).with(Sort.by("age").ascending());
// 创建更新对象,并设置更新的内容
Update update = new Update().set("age", 30).set("name", "zhangsansan");
// 执行更新
UpdateResult result = mongoTemplate.updateFirst(query, update, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
return resultInfo;
}
/**
* 更新【匹配查询】到的【文档数据集合】中的【所有数据】
*
* @return 执行更新的结果
*/
public Object updateMany() {
// 创建条件对象
Criteria criteria = Criteria.where("age").gt(28);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 设置更新字段和更新的内容
Update update = new Update().set("age", 29).set("salary", "1999");
// 执行更新
UpdateResult result = mongoTemplate.updateMulti(query, update, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "总共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
return resultInfo;
}
}
|
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\UpdateService.java
| 1
|
请完成以下Java代码
|
public Collection<I_M_HU> retrieveActualSourceHUs(@NonNull final Set<HuId> huIds)
{
final Set<HuId> vhuSourceIds = retrieveVhuSourceIds(huIds);
return retrieveTopLevelSourceHus(vhuSourceIds);
}
private Set<HuId> retrieveVhuSourceIds(@NonNull final Set<HuId> huIds)
{
Check.assumeNotEmpty(huIds, "huIds is not empty");
final HUTraceEventQuery query = HUTraceEventQuery.builder()
.type(HUTraceType.TRANSFORM_LOAD)
.topLevelHuIds(huIds)
.build();
return huTraceRepository.query(query)
.stream()
.map(HUTraceEvent::getVhuSourceId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
/**
* Don't use Services.get(IHandlingUnitsBL.class).getTopLevelHUs() because the sourceHUs might already be destroyed.f
*
* @param vhuSourceIds
* @return
*/
private List<I_M_HU> retrieveTopLevelSourceHus(@NonNull final Set<HuId> vhuSourceIds)
{
if (vhuSourceIds.isEmpty())
{
return ImmutableList.of();
}
final HUTraceEventQuery query = HUTraceEventQuery.builder()
.type(HUTraceType.TRANSFORM_LOAD)
.vhuIds(vhuSourceIds)
|
.build();
final Set<HuId> topLevelSourceHuIds = huTraceRepository.query(query)
.stream()
.map(HUTraceEvent::getTopLevelHuId)
.collect(ImmutableSet.toImmutableSet());
if (topLevelSourceHuIds.isEmpty())
{
return ImmutableList.of();
}
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
return handlingUnitsDAO.getByIds(topLevelSourceHuIds);
}
public Collection<HuId> retrieveMatchingSourceHUIds(final HuId huId)
{
final MatchingSourceHusQuery query = MatchingSourceHusQuery.fromHuId(huId);
final ISourceHuDAO sourceHuDAO = Services.get(ISourceHuDAO.class);
return sourceHuDAO.retrieveActiveSourceHUIds(query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\HuId2SourceHUsService.java
| 1
|
请完成以下Java代码
|
public void stopExecutor() {
if (readResultsProcessingExecutor != null) {
readResultsProcessingExecutor.shutdownNow();
}
}
protected <T> ListenableFuture<T> getFuture(TbResultSetFuture future, java.util.function.Function<TbResultSet, T> transformer) {
return Futures.transform(future, new Function<TbResultSet, T>() {
@Nullable
@Override
public T apply(@Nullable TbResultSet input) {
return transformer.apply(input);
}
}, readResultsProcessingExecutor);
}
|
protected <T> ListenableFuture<T> getFutureAsync(TbResultSetFuture future, com.google.common.util.concurrent.AsyncFunction<TbResultSet, T> transformer) {
return Futures.transformAsync(future, new AsyncFunction<TbResultSet, T>() {
@Nullable
@Override
public ListenableFuture<T> apply(@Nullable TbResultSet input) {
try {
return transformer.apply(input);
} catch (Exception e) {
return Futures.immediateFailedFuture(e);
}
}
}, readResultsProcessingExecutor);
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractAsyncDao.java
| 1
|
请完成以下Java代码
|
private boolean enqueueFile(final File file)
{
log.info("Enqueuing " + file);
PrintPackage printPackage = null;
InputStream printPackageStream = null;
final File dataFile = new File(Util.changeFileExtension(file.getAbsolutePath(), "pdf"));
InputStream printDataStream = null;
try
{
printPackageStream = new FileInputStream(file);
printPackage = beanEncoder.decodeStream(printPackageStream, PrintPackage.class);
printPackageStream.close();
printPackageStream = null;
printDataStream = new FileInputStream(dataFile);
final byte[] data = Util.toByteArray(printDataStream);
printDataStream.close();
printDataStream = new ByteArrayInputStream(data);
file.delete();
dataFile.delete();
}
catch (final Exception e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
return false;
}
finally
{
Util.close(printPackageStream);
Util.close(printDataStream);
}
|
log.info("Adding package to buffer: " + printPackage);
buffer.addPrintPackage(printPackage, printDataStream);
return true;
}
@Override
public String toString()
{
return "DirectoryPrintConnectionEndpoint [directory=" + directory + ", fileExtension=" + fileExtension + ", beanEncoder=" + beanEncoder + ", buffer=" + buffer + "]";
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\DirectoryPrintConnectionEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmployeeController {
//
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow( () -> new ResourceNotFoundException("Employee not found for this id:: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employee")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException{
Employee employee = employeeRepository.findById(employeeId)
|
.orElseThrow(()-> new ResourceNotFoundException("Employee not found this id::" + employeeId));
employee.setEmail(employeeDetails.getEmail());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("Employee not found for the id::" + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringPostgreslq\src\main\java\spring\database\controller\EmployeeController.java
| 2
|
请完成以下Java代码
|
private ImmutableMap<String, String> computeLanguageTagsByADLanguageMap()
{
final HashMap<String, String> tag2adLanguage = new HashMap<>();
for (final String adLanguage : languagesByADLanguage.keySet())
{
final String tag = toHttpLanguageTag(adLanguage);
tag2adLanguage.put(tag, adLanguage);
final String languagePart = extractLanguagePartFromTag(tag);
if (languagePart != null && (isBaseLanguage(adLanguage) || !tag2adLanguage.containsKey(languagePart)))
{
tag2adLanguage.put(languagePart, adLanguage);
}
}
return ImmutableMap.copyOf(tag2adLanguage);
}
@Nullable
private static String extractLanguagePartFromTag(final String tag)
{
final int idx = tag.indexOf("-");
return idx > 0 ? tag.substring(0, idx) : null;
}
public static String toHttpLanguageTag(final String adLanguage)
{
return adLanguage.replace('_', '-').trim().toLowerCase();
}
public boolean isBaseLanguage(final ValueNamePair language)
{
return isBaseLanguage(language.getValue());
}
public boolean isBaseLanguage(final String adLanguage)
{
if (baseADLanguage == null)
{
return false;
}
return baseADLanguage.equals(adLanguage);
}
//
|
//
//
//
//
public static class Builder
{
private final Map<String, ValueNamePair> languagesByADLanguage = new LinkedHashMap<>();
private String baseADLanguage = null;
private Builder()
{
}
public ADLanguageList build()
{
return new ADLanguageList(this);
}
public Builder addLanguage(@NonNull final String adLanguage, @NonNull final String caption, final boolean isBaseLanguage)
{
final ValueNamePair languageVNP = ValueNamePair.of(adLanguage, caption);
languagesByADLanguage.put(adLanguage, languageVNP);
if (isBaseLanguage)
{
baseADLanguage = adLanguage;
}
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ADLanguageList.java
| 1
|
请完成以下Java代码
|
public class ProcessResumedEventListenerDelegate implements ActivitiEventListener {
private List<ProcessRuntimeEventListener<ProcessResumedEvent>> processRuntimeEventListeners;
private ToProcessResumedConverter processResumedConverter;
public ProcessResumedEventListenerDelegate(
List<ProcessRuntimeEventListener<ProcessResumedEvent>> listeners,
ToProcessResumedConverter processResumedConverter
) {
this.processRuntimeEventListeners = listeners;
this.processResumedConverter = processResumedConverter;
}
@Override
public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) {
|
processResumedConverter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (ProcessRuntimeEventListener<ProcessResumedEvent> listener : processRuntimeEventListeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ProcessResumedEventListenerDelegate.java
| 1
|
请完成以下Java代码
|
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
*
* @return info display
*/
public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
|
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java
| 1
|
请完成以下Java代码
|
public VersionRange format(Format format) {
Version lower = this.lowerVersion.format(format);
Version higher = (this.higherVersion != null) ? this.higherVersion.format(format) : null;
return new VersionRange(lower, this.lowerInclusive, higher, this.higherInclusive);
}
public Version getLowerVersion() {
return this.lowerVersion;
}
public boolean isLowerInclusive() {
return this.lowerInclusive;
}
public Version getHigherVersion() {
return this.higherVersion;
}
public boolean isHigherInclusive() {
return this.higherInclusive;
}
public String toRangeString() {
StringBuilder sb = new StringBuilder();
if (this.lowerVersion == null && this.higherVersion == null) {
return "";
}
if (this.higherVersion != null) {
sb.append(this.lowerInclusive ? "[" : "(")
.append(this.lowerVersion)
.append(",")
.append(this.higherVersion)
.append(this.higherInclusive ? "]" : ")");
}
else {
sb.append(this.lowerVersion);
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VersionRange other = (VersionRange) obj;
if (this.higherInclusive != other.higherInclusive) {
return false;
}
if (this.higherVersion == null) {
if (other.higherVersion != null) {
return false;
}
}
else if (!this.higherVersion.equals(other.higherVersion)) {
return false;
}
if (this.lowerInclusive != other.lowerInclusive) {
return false;
}
if (this.lowerVersion == null) {
|
if (other.lowerVersion != null) {
return false;
}
}
else if (!this.lowerVersion.equals(other.lowerVersion)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.higherInclusive ? 1231 : 1237);
result = prime * result + ((this.higherVersion == null) ? 0 : this.higherVersion.hashCode());
result = prime * result + (this.lowerInclusive ? 1231 : 1237);
result = prime * result + ((this.lowerVersion == null) ? 0 : this.lowerVersion.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.lowerVersion != null) {
sb.append(this.lowerInclusive ? ">=" : ">").append(this.lowerVersion);
}
if (this.higherVersion != null) {
sb.append(" and ").append(this.higherInclusive ? "<=" : "<").append(this.higherVersion);
}
return sb.toString();
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionRange.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CurrentCostId implements RepoIdAware
{
@JsonCreator
public static CurrentCostId ofRepoId(final int repoId)
{
return new CurrentCostId(repoId);
}
public static CurrentCostId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new CurrentCostId(repoId) : null;
}
public static CurrentCostId ofRepoIdOrNull(@Nullable final int repoId)
{
return repoId > 0 ? new CurrentCostId(repoId) : null;
}
public static int toRepoId(final CurrentCostId id)
{
return id != null ? id.getRepoId() : -1;
}
|
public static boolean equals(final CurrentCostId o1, final CurrentCostId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private CurrentCostId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Cost_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CurrentCostId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@ApiModelProperty(example = "null")
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
@ApiModelProperty(example = "5")
public String getProcessInstanceId() {
return processInstanceId;
|
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/5")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricIdentityLinkResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomNotifier extends AbstractStatusChangeNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger( LoggingNotifier.class);
public CustomNotifier(InstanceRepository repository) {
super(repository);
}
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
if (event instanceof InstanceStatusChangedEvent) {
LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());
String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();
switch (status) {
// 健康检查没通过
case "DOWN":
System.out.println("发送 健康检查没通过 的通知!");
break;
// 服务离线
case "OFFLINE":
System.out.println("发送 服务离线 的通知!");
break;
//服务上线
case "UP":
System.out.println("发送 服务上线 的通知!");
|
break;
// 服务未知异常
case "UNKNOWN":
System.out.println("发送 服务未知异常 的通知!");
break;
default:
break;
}
} else {
LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
event.getType());
}
});
}
}
|
repos\SpringBootLearning-master (1)\springboot-admin\sc-admin-server\src\main\java\com\gf\config\CustomNotifier.java
| 2
|
请完成以下Java代码
|
public class Foo {
private int id;
private String name;
private Foo parent;
public Foo() {
}
public Foo(int id, String name, Foo parent) {
this.id = id;
this.name = name;
this.parent = parent;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public Foo getParent() {
return parent;
}
public void setParent(Foo parent) {
this.parent = parent;
}
public Foo deepCopy() {
return new Foo(
this.id, this.name, this.parent != null ? this.parent.deepCopy() : null);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-conversions-2\src\main\java\com\baeldung\convertcollectiontoarraylist\Foo.java
| 1
|
请完成以下Java代码
|
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
return reconcilePayments().checkCanExecute();
}
@Override
protected String doIt()
{
reconcilePayments().execute();
// NOTE: usually this would not be needed but it seems frontend has some problems to refresh the left side view
invalidateBankStatementReconciliationView();
return MSG_OK;
}
|
private ReconcilePaymentsCommand reconcilePayments()
{
return ReconcilePaymentsCommand.builder()
.msgBL(msgBL)
.bankStatmentPaymentBL(bankStatmentPaymentBL)
//
.request(ReconcilePaymentsRequest.builder()
.selectedBankStatementLine(getSingleSelectedBankStatementRowOrNull())
.selectedPaymentsToReconcile(getSelectedPaymentToReconcileRows())
.build())
//
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\process\PaymentsToReconcileView_Reconcile.java
| 1
|
请完成以下Java代码
|
public static final class SourceHuMayNotBeRemovedException extends AdempiereException
{
private static final AdMessageKey MSG_CANNOT_MOVE_SOURCE_HU_1P = AdMessageKey.of("CANNOT_MOVE_SOURCE_HU");
private SourceHuMayNotBeRemovedException(final I_M_HU hu)
{
super(MSG_CANNOT_MOVE_SOURCE_HU_1P, new Object[] { hu.getValue() });
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_M_HU.COLUMNNAME_HUStatus)
public void validateHUStatus(@NonNull final I_M_HU hu)
{
final String huStatus = hu.getHUStatus();
|
final boolean isHUConsumed = X_M_HU.HUSTATUS_Picked.equals(huStatus) || X_M_HU.HUSTATUS_Shipped.equals(huStatus) || X_M_HU.HUSTATUS_Issued.equals(huStatus);
if (!isHUConsumed)
{
return;
}
if (!handlingUnitsBL.isHUHierarchyCleared(hu))
{
throw new AdempiereException("M_HUs that are not cleared can not be picked, shipped or issued!")
.appendParametersToMessage()
.setParameter("M_HU_ID", hu.getM_HU_ID());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\interceptor\M_HU.java
| 1
|
请完成以下Java代码
|
public List<Integer> getValueAsIntegersList()
{
if (value == null)
{
return ImmutableList.of();
}
if (value instanceof List<?>)
{
@SuppressWarnings("unchecked")
final List<Integer> intList = (List<Integer>)value;
return intList;
}
else if (value instanceof String)
{
return ImmutableList.copyOf(DocumentIdsSelection.ofCommaSeparatedString(value.toString()).toIntSet());
}
else
{
throw new AdempiereException("Cannot convert value to int list").setParameter("event", this);
}
}
public <ET extends Enum<ET>> ET getValueAsEnum(final Class<ET> enumType)
{
if (value == null)
{
|
return null;
}
if (enumType.isAssignableFrom(value.getClass()))
{
@SuppressWarnings("unchecked")
final ET valueConv = (ET)value;
return valueConv;
}
else if (value instanceof String)
{
return Enum.valueOf(enumType, value.toString());
}
else
{
throw new AdempiereException("Cannot convert value " + value + " to " + enumType);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONPatchEvent.java
| 1
|
请完成以下Java代码
|
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.passwordEncoder = passwordEncoder;
}
/**
* Sets the {@link Scheduler} used by the
* {@link UserDetailsRepositoryReactiveAuthenticationManager}. The default is
* {@code Schedulers.newParallel(String)} because modern password encoding is a CPU
* intensive task that is non blocking. This means validation is bounded by the number
* of CPUs. Some applications may want to customize the {@link Scheduler}. For
* example, if users are stuck using the insecure
* {@link org.springframework.security.crypto.password.NoOpPasswordEncoder} they might
* want to leverage {@code Schedulers.immediate()}.
* @param scheduler the {@link Scheduler} to use. Cannot be null.
* @since 5.0.6
*/
public void setScheduler(Scheduler scheduler) {
Assert.notNull(scheduler, "scheduler cannot be null");
this.scheduler = scheduler;
}
/**
* Sets the service to use for upgrading passwords on successful authentication.
* @param userDetailsPasswordService the service to use
*/
public void setUserDetailsPasswordService(ReactiveUserDetailsPasswordService userDetailsPasswordService) {
Assert.notNull(userDetailsPasswordService, "userDetailsPasswordService cannot be null");
this.userDetailsPasswordService = userDetailsPasswordService;
}
/**
* Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt>
* object after authentication occurs.
* @param postAuthenticationChecks The {@link UserDetailsChecker}
* @since 5.2
*/
public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
Assert.notNull(this.postAuthenticationChecks, "postAuthenticationChecks cannot be null");
this.postAuthenticationChecks = postAuthenticationChecks;
}
/**
* @since 5.5
|
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the {@link ReactiveCompromisedPasswordChecker} to be used before creating a
* successful authentication. Defaults to {@code null}.
* @param compromisedPasswordChecker the {@link CompromisedPasswordChecker} to use
* @since 6.3
*/
public void setCompromisedPasswordChecker(ReactiveCompromisedPasswordChecker compromisedPasswordChecker) {
this.compromisedPasswordChecker = compromisedPasswordChecker;
}
/**
* Allows subclasses to retrieve the <code>UserDetails</code> from an
* implementation-specific location.
* @param username The username to retrieve
* @return the user information. If authentication fails, a Mono error is returned.
*/
protected abstract Mono<UserDetails> retrieveUser(String username);
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AbstractUserDetailsReactiveAuthenticationManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static final class NettyDriverMongoClientSettingsBuilderCustomizer
implements MongoClientSettingsBuilderCustomizer, DisposableBean {
private final ObjectProvider<MongoClientSettings> settings;
private volatile @Nullable EventLoopGroup eventLoopGroup;
NettyDriverMongoClientSettingsBuilderCustomizer(ObjectProvider<MongoClientSettings> settings) {
this.settings = settings;
}
@Override
public void customize(Builder builder) {
if (!isCustomTransportConfiguration(this.settings.getIfAvailable())) {
EventLoopGroup eventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
this.eventLoopGroup = eventLoopGroup;
builder.transportSettings(TransportSettings.nettyBuilder().eventLoopGroup(eventLoopGroup).build());
}
}
|
@Override
public void destroy() {
EventLoopGroup eventLoopGroup = this.eventLoopGroup;
if (eventLoopGroup != null) {
eventLoopGroup.shutdownGracefully().awaitUninterruptibly();
this.eventLoopGroup = null;
}
}
private boolean isCustomTransportConfiguration(@Nullable MongoClientSettings settings) {
return settings != null && settings.getTransportSettings() != null;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\MongoReactiveAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected void setOwner(TenantId tenantId, Device device, IdProvider idProvider) {
device.setTenantId(tenantId);
device.setCustomerId(idProvider.getInternalId(device.getCustomerId()));
}
@Override
protected Device prepare(EntitiesImportCtx ctx, Device device, Device old, DeviceExportData exportData, IdProvider idProvider) {
device.setDeviceProfileId(idProvider.getInternalId(device.getDeviceProfileId()));
device.setFirmwareId(idProvider.getInternalId(device.getFirmwareId()));
device.setSoftwareId(idProvider.getInternalId(device.getSoftwareId()));
return device;
}
@Override
protected Device deepCopy(Device d) {
return new Device(d);
}
@Override
protected void cleanupForComparison(Device e) {
super.cleanupForComparison(e);
if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) {
e.setCustomerId(null);
}
}
@Override
protected Device saveOrUpdate(EntitiesImportCtx ctx, Device device, DeviceExportData exportData, IdProvider idProvider, CompareResult compareResult) {
Device savedDevice;
if (exportData.getCredentials() != null && ctx.isSaveCredentials()) {
exportData.getCredentials().setId(null);
exportData.getCredentials().setDeviceId(null);
savedDevice = deviceService.saveDeviceWithCredentials(device, exportData.getCredentials());
} else {
savedDevice = deviceService.saveDevice(device);
}
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, savedDevice, exportData, idProvider);
}
return savedDevice;
|
}
@Override
protected boolean updateRelatedEntitiesIfUnmodified(EntitiesImportCtx ctx, Device prepared, DeviceExportData exportData, IdProvider idProvider) {
boolean updated = super.updateRelatedEntitiesIfUnmodified(ctx, prepared, exportData, idProvider);
var credentials = exportData.getCredentials();
if (credentials != null && ctx.isSaveCredentials()) {
var existing = credentialsService.findDeviceCredentialsByDeviceId(ctx.getTenantId(), prepared.getId());
credentials.setId(existing.getId());
credentials.setDeviceId(prepared.getId());
if (!existing.equals(credentials)) {
credentialsService.updateDeviceCredentials(ctx.getTenantId(), credentials);
updated = true;
}
}
return updated;
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\DeviceImportService.java
| 2
|
请完成以下Java代码
|
public EventDefinitionQuery orderByEventDefinitionName() {
return orderBy(EventDefinitionQueryProperty.NAME);
}
@Override
public EventDefinitionQuery orderByTenantId() {
return orderBy(EventDefinitionQueryProperty.TENANT_ID);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionCountByQueryCriteria(this);
}
@Override
public List<EventDefinition> executeList(CommandContext commandContext) {
return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
|
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getKeyLikeIgnoreCase() {
return keyLikeIgnoreCase;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDefinitionQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
protected Book() {
}
public Book(Long id, String title) {
this.id = id;
this.title = title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
|
}
Book book = (Book) o;
return Objects.equals(id, book.id) && Objects.equals(title, book.title);
}
@Override
public int hashCode() {
return Objects.hash(id, title);
}
@Override
public String toString() {
return "Book{" + "title='" + title + '\'' + '}';
}
}
|
repos\spring-data-examples-main\jpa\graalvm-native\src\main\java\com\example\data\jpa\model\Book.java
| 2
|
请完成以下Java代码
|
public @Nullable ExecutionId getExecutionId() {
return this.executionId;
}
@Override
public Locale getLocale() {
return this.locale;
}
@Override
public void configureExecutionInput(BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer) {
this.executionInputConfigurers.add(configurer);
}
@Override
public ExecutionInput toExecutionInput() {
ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput()
.query(getDocument())
.operationName(getOperationName())
.variables(getVariables())
.extensions(getExtensions())
.locale(this.locale)
|
.executionId((this.executionId != null) ? this.executionId : ExecutionId.from(this.id));
ExecutionInput executionInput = inputBuilder.build();
for (BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer : this.executionInputConfigurers) {
ExecutionInput current = executionInput;
executionInput = executionInput.transform((builder) -> configurer.apply(current, builder));
}
return executionInput;
}
@Override
public String toString() {
return super.toString() + ", id=" + getId() + ", Locale=" + getLocale();
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\DefaultExecutionGraphQlRequest.java
| 1
|
请完成以下Java代码
|
private static class PressAction extends UIAction
{
PressAction ()
{
super (PRESS);
}
@Override
public void actionPerformed (ActionEvent e)
{
JLabel label = (JLabel)e.getSource ();
String key = getName ();
if (key.equals(PRESS))
{
doPress (label);
}
} // actionPerformed
/**
* Do Press - Focus the Field
* @param label label
*/
private void doPress (JLabel label)
{
Component labelFor = label.getLabelFor ();
if (labelFor != null && labelFor.isEnabled ())
{
Component owner = label.getLabelFor ();
if (owner instanceof Container
&& ((Container)owner).isFocusCycleRoot ())
{
owner.requestFocus ();
}
else
{
if (owner instanceof Container)
{
Container container = (Container)owner;
if (container.isFocusCycleRoot())
{
FocusTraversalPolicy policy = container.getFocusTraversalPolicy();
Component comp = policy.getDefaultComponent(container);
if (comp != null)
|
{
comp.requestFocus();
return;
}
}
Container rootAncestor = container.getFocusCycleRootAncestor();
if (rootAncestor != null)
{
FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
Component comp = policy.getComponentAfter(rootAncestor, container);
if (comp != null && SwingUtilities.isDescendingFrom(comp, container))
{
comp.requestFocus();
return;
}
}
}
if (owner.isFocusable())
{
owner.requestFocus();
return;
}
// No Forcus
}
}
} // doPress
} // PressAction
} // AdempiereLabelUI
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereLabelUI.java
| 1
|
请完成以下Java代码
|
public static class ExecutionPlan {
@Param({ "100", "200", "300", "500", "1000" })
public int iterations;
public Hasher murmur3;
public String password = "4v3rys3kur3p455w0rd";
@Setup(Level.Invocation)
public void setUp() {
murmur3 = Hashing.murmur3_128().newHasher();
}
}
@Fork(value = 1, warmups = 1)
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
public void benchMurmur3_128(ExecutionPlan plan) {
for (int i = plan.iterations; i > 0; i--) {
plan.murmur3.putString(plan.password, Charset.defaultCharset());
}
plan.murmur3.hash();
}
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.Throughput)
public void init() {
// Do nothing
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void doNothing() {
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void objectCreation() {
|
new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public Object pillarsOfCreation() {
return new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) {
blackhole.consume(new Object());
}
@Benchmark
public double foldedLog() {
int x = 8;
return Math.log(x);
}
@Benchmark
public double log(Log input) {
return Math.log(input.x);
}
}
|
repos\tutorials-master\jmh\src\main\java\com\baeldung\BenchMark.java
| 1
|
请完成以下Java代码
|
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
|
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java
| 1
|
请完成以下Java代码
|
public Map<WarehouseId, ProductHUInventory> mapByWarehouseId()
{
return mapByKey(huForInventoryLine -> huForInventoryLine.getLocatorId().getWarehouseId());
}
@NonNull
public List<InventoryLineHU> toInventoryLineHUs(
@NonNull final IUOMConversionBL uomConversionBL,
@NonNull final UomId targetUomId)
{
final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId);
return huForInventoryLineList.stream()
.map(DraftInventoryLinesCreateCommand::toInventoryLineHU)
.map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter))
.collect(ImmutableList.toImmutableList());
}
@NonNull
public Set<HuId> getHuIds()
{
return huForInventoryLineList.stream()
.map(HuForInventoryLine::getHuId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
|
@NonNull
private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider)
{
final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>();
huForInventoryLineList.forEach(hu -> {
final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>();
husFromTargetWarehouse.add(hu);
key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> {
oldList.addAll(newList);
return oldList;
});
});
return key2Hus.keySet()
.stream()
.collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId))));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
| 1
|
请完成以下Java代码
|
public class SkipList {
private Node head;
private int maxLevel;
private int level;
private Random random;
public SkipList() {
maxLevel = 16; // maximum number of levels
level = 0; // current level of SkipList
head = new Node(Integer.MIN_VALUE, maxLevel);
random = new Random();
}
public void insert(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current == null || current.value != value) {
int lvl = randomLevel();
if (lvl > level) {
for (int i = level + 1; i <= lvl; i++) {
update[i] = head;
}
level = lvl;
}
Node newNode = new Node(value, lvl);
for (int i = 0; i <= lvl; i++) {
newNode.forward[i] = update[i].forward[i];
update[i].forward[i] = newNode;
}
}
}
public boolean search(int value) {
Node current = this.head;
for (int i = level; i >= 0; i--) {
|
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
}
current = current.forward[0];
return current != null && current.value == value;
}
public void delete(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current != null && current.value == value) {
for (int i = 0; i <= level; i++) {
if (update[i].forward[i] != current) break;
update[i].forward[i] = current.forward[i];
}
while (level > 0 && head.forward[level] == null) {
level--;
}
}
}
private int randomLevel() {
int lvl = 0;
while (lvl < maxLevel && random.nextDouble() < 0.5) {
lvl++;
}
return lvl;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\skiplist\SkipList.java
| 1
|
请完成以下Java代码
|
public boolean addIfAbsent(final E item)
{
if (list.contains(item))
{
return false;
}
return add(item);
}
public int size()
{
return list.size();
}
public E get(final int index)
{
return list.get(index);
}
public void clear()
{
if (list.isEmpty())
{
return;
}
final int sizeBeforeClear = list.size();
|
list.clear();
fireIntervalRemoved(this, 0, sizeBeforeClear - 1);
}
public void set(final Collection<E> items)
{
clear();
addAll(items);
}
public void set(final E[] items)
{
final List<E> itemsAsList;
if (items == null || items.length == 0)
{
itemsAsList = Collections.emptyList();
}
else
{
itemsAsList = Arrays.asList(items);
}
set(itemsAsList);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\ListComboBoxModel.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) {
this.nameLikeIgnoreCase = nameLikeIgnoreCase;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
|
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public void setInvolvedGroups(List<String> involvedGroups) {
this.involvedGroups = involvedGroups;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
protected String getBusinessKey(CmmnEngineConfiguration cmmnEngineConfiguration, PlanItemInstanceEntity planItemInstanceEntity, ChildTask childTask) {
String businessKey = null;
ExpressionManager expressionManager = cmmnEngineConfiguration.getExpressionManager();
CaseInstanceEntityManager caseInstanceEntityManager = cmmnEngineConfiguration.getCaseInstanceEntityManager();
if (!StringUtils.isEmpty(childTask.getBusinessKey())) {
Expression expression = expressionManager.createExpression(childTask.getBusinessKey());
businessKey = expression.getValue(planItemInstanceEntity).toString();
} else if (childTask.isInheritBusinessKey()) {
String caseInstanceId = planItemInstanceEntity.getCaseInstanceId();
CaseInstance caseInstance = caseInstanceEntityManager.findById(caseInstanceId);
businessKey = caseInstance.getBusinessKey();
}
return businessKey;
}
/**
* Called when a manual delete is triggered (NOT when a terminate/complete is triggered),
* for example when a deployment is deleted and everything related needs to be deleted.
*/
public abstract void deleteChildEntity(CommandContext commandContext, DelegatePlanItemInstance delegatePlanItemInstance, boolean cascade);
public static class VariableInfo {
protected Map<String, Object> variables;
protected Map<String, Object> formVariables;
protected String formOutcome;
protected FormInfo formInfo;
public VariableInfo(Map<String, Object> variables) {
this.variables = variables;
}
public VariableInfo(Map<String, Object> variables, Map<String, Object> formVariables, String formOutcome, FormInfo formInfo) {
this(variables);
this.formVariables = formVariables;
this.formOutcome = formOutcome;
this.formInfo = formInfo;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
|
public Map<String, Object> getFormVariables() {
return formVariables;
}
public void setFormVariables(Map<String, Object> formVariables) {
this.formVariables = formVariables;
}
public String getFormOutcome() {
return formOutcome;
}
public void setFormOutcome(String formOutcome) {
this.formOutcome = formOutcome;
}
public FormInfo getFormInfo() {
return formInfo;
}
public void setFormInfo(FormInfo formInfo) {
this.formInfo = formInfo;
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\ChildTaskActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public NamePair retrieveLookupValue(
@CacheAllowMutable final IValidationContext validationCtx,
@CacheAllowMutable final MLookupInfo lookupInfo,
@CacheAllowMutable final Object key)
{
final String sqlQueryDirect = lookupInfo.getSqlQueryDirect();
if (key == null || Check.isEmpty(sqlQueryDirect, true))
{
return null; // Nothing to query
}
final boolean isNumber = lookupInfo.getSqlQuery().isNumericKey();
// Case: key it's for a numeric ID but it's an empty string
if (isNumber && Check.isEmpty(key.toString(), true))
{
return null;
}
// 04617: applying the validation rule's prefilter where clause, to make sure that what we return is valid
String validation;
if (validationCtx == IValidationContext.DISABLED)
{
// NOTE: if validation is disabled we shall not add any where clause
validation = "";
}
else
{
final IStringExpression validationExpr = lookupInfo.getValidationRule().getPrefilterWhereClause();
validation = validationExpr.evaluate(validationCtx, OnVariableNotFound.ReturnNoResult);
if (validationExpr.isNoResult(validation))
{
validation = null;
}
}
final String sql;
if (validation == null)
{
sql = sqlQueryDirect;
}
else
{
sql = injectWhereClause(sqlQueryDirect, validation);
}
// 04617 end
PreparedStatement pstmt = null;
ResultSet rs = null;
NamePair directValue = null;
try
{
// SELECT Key, Value, Name FROM ...
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
if (isNumber)
{
pstmt.setInt(1, Integer.parseInt(key.toString()));
}
else
{
pstmt.setString(1, key.toString());
}
|
rs = pstmt.executeQuery();
while (rs.next())
{
if (directValue != null)
{
logger.error("Not unique (first returned) for {} (SQL={})", key, sql);
break;
}
final String name = rs.getString(MLookupInfo.SqlQuery.COLUMNINDEX_DisplayName);
final String description = rs.getString(MLookupInfo.SqlQuery.COLUMNINDEX_Description);
final NamePair item;
if (isNumber)
{
final int itemId = rs.getInt(MLookupInfo.SqlQuery.COLUMNINDEX_Key);
item = KeyNamePair.of(itemId, name, description);
}
else
{
final String itemValue = rs.getString(MLookupInfo.SqlQuery.COLUMNINDEX_Value);
item = ValueNamePair.of(itemValue, name, description);
}
// 04617: apply java validation rules
final INamePairPredicate postQueryFilter = lookupInfo.getValidationRule().getPostQueryFilter();
if (!postQueryFilter.accept(validationCtx, item))
{
continue;
}
directValue = item;
}
}
catch (final SQLException e)
{
throw DBException.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("sql", sql)
.setParameter("param", key);
}
finally
{
DB.close(rs, pstmt);
}
return directValue;
} // getDirect
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\LookupDAO.java
| 2
|
请完成以下Java代码
|
public static byte[] sha(byte[] data) {
return getSha512Digest().digest(data);
}
/**
* Calculates the SHA digest and returns the value as a <code>byte[]</code>.
* @param data Data to digest
* @return SHA digest
*/
public static byte[] sha(String data) {
return sha(data.getBytes());
}
/**
* Calculates the SHA digest and returns the value as a hex string.
* @param data Data to digest
|
* @return SHA digest as a hex string
*/
public static String shaHex(byte[] data) {
return new String(Hex.encode(sha(data)));
}
/**
* Calculates the SHA digest and returns the value as a hex string.
* @param data Data to digest
* @return SHA digest as a hex string
*/
public static String shaHex(String data) {
return new String(Hex.encode(sha(data)));
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\Sha512DigestUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void onRepartitionEvent() {
otherUsageStates.entrySet().removeIf(entry ->
partitionService.resolve(ServiceType.TB_CORE, entry.getValue().getTenantId(), entry.getKey()).isMyPartition());
updateLock.lock();
try {
myUsageStates.values().forEach(BaseApiUsageState::onRepartitionEvent);
} finally {
updateLock.unlock();
}
}
@Override
protected Map<TopicPartitionInfo, List<ListenableFuture<?>>> onAddedPartitions(Set<TopicPartitionInfo> addedPartitions) {
var result = new HashMap<TopicPartitionInfo, List<ListenableFuture<?>>>();
try {
log.info("Initializing tenant states.");
updateLock.lock();
try {
PageDataIterable<Tenant> tenantIterator = new PageDataIterable<>(tenantService::findTenants, 1024);
for (Tenant tenant : tenantIterator) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenant.getId(), tenant.getId());
if (addedPartitions.contains(tpi)) {
if (!myUsageStates.containsKey(tenant.getId()) && tpi.isMyPartition()) {
log.debug("[{}] Initializing tenant state.", tenant.getId());
result.computeIfAbsent(tpi, tmp -> new ArrayList<>()).add(dbExecutor.submit(() -> {
try {
updateTenantState((TenantApiUsageState) getOrFetchState(tenant.getId(), tenant.getId()), tenantProfileCache.get(tenant.getTenantProfileId()));
log.debug("[{}] Initialized tenant state.", tenant.getId());
} catch (Exception e) {
|
log.warn("[{}] Failed to initialize tenant API state", tenant.getId(), e);
}
return null;
}));
}
} else {
log.debug("[{}][{}] Tenant doesn't belong to current partition. tpi [{}]", tenant.getName(), tenant.getId(), tpi);
}
}
} finally {
updateLock.unlock();
}
} catch (Exception e) {
log.warn("Unknown failure", e);
}
return result;
}
@PreDestroy
private void destroy() {
super.stop();
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\DefaultTbApiUsageStateService.java
| 2
|
请完成以下Java代码
|
protected boolean beforeSave(final boolean newRecord)
{
if (getC_Location_ID() <= 0)
{
throw new FillMandatoryException(COLUMNNAME_C_Location_ID);
}
// Set New Name only if new record
if (newRecord)
{
final int cBPartnerId = getC_BPartner_ID();
// gh12157: Please, keep in sync with de.metas.bpartner.quick_input.callout.C_BPartner_Location_QuickInput.onLocationChanged
setName(MakeUniqueLocationNameCommand.builder()
.name(getName())
.address(getC_Location())
.companyName(bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(cBPartnerId)))
.existingNames(getOtherLocationNames(cBPartnerId, getC_BPartner_Location_ID()))
.maxLength(getPOInfo().getFieldLength(I_C_BPartner_Location.COLUMNNAME_Name))
.build()
.execute());
|
}
return true;
}
private static List<String> getOtherLocationNames(
final int bpartnerId,
final int bpartnerLocationIdToExclude)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addNotEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, bpartnerLocationIdToExclude)
.create()
.listDistinct(I_C_BPartner_Location.COLUMNNAME_Name, String.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPartnerLocation.java
| 1
|
请完成以下Java代码
|
public long iterateUsingKeySetAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer key : map.keySet()) {
sum += map.get(key);
}
return sum;
}
public long iterateUsingStreamAPIAndEntrySet(Map<Integer, Integer> map) {
return map.entrySet()
.stream()
.mapToLong(Map.Entry::getValue)
.sum();
}
public long iterateUsingStreamAPIAndKeySet(Map<Integer, Integer> map) {
return map.keySet()
.stream()
.mapToLong(map::get)
.sum();
}
public long iterateKeysUsingKeySetAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer key : map.keySet()) {
sum += map.get(key);
}
return sum;
}
public long iterateValuesUsingValuesMethodAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer value : map.values()) {
sum += value;
}
return sum;
}
public long iterateUsingMapIteratorApacheCollection(IterableMap<Integer, Integer> map) {
long sum = 0;
MapIterator<Integer, Integer> iterate = map.mapIterator();
while (iterate.hasNext()) {
iterate.next();
|
sum += iterate.getValue();
}
return sum;
}
public long iterateEclipseMap(MutableMap<Integer, Integer> mutableMap) throws IOException {
AtomicLong sum = new AtomicLong(0);
mutableMap.forEachKeyValue((key, value) -> {
sum.addAndGet(value);
});
return sum.get();
}
public long iterateMapUsingParallelStreamApi(Map<Integer, Integer> map) throws IOException {
return map.entrySet()
.parallelStream()
.mapToLong(Map.Entry::getValue)
.sum();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIteration.java
| 1
|
请完成以下Java代码
|
private Context resolveContext() {
return this.context != null
? this.context
: Optional.ofNullable(LoggerFactory.getILoggerFactory())
.filter(Context.class::isInstance)
.map(Context.class::cast)
.orElse(null);
}
private String resolveName() {
return this.name != null && !this.name.trim().isEmpty() ? this.name : DEFAULT_NAME;
}
private StringAppenderWrapper resolveStringAppenderWrapper() {
return this.useSynchronization
? StringBufferAppenderWrapper.create()
: StringBuilderAppenderWrapper.create();
}
public StringAppender build() {
StringAppender stringAppender =
new StringAppender(resolveStringAppenderWrapper());
stringAppender.setContext(resolveContext());
stringAppender.setName(resolveName());
getDelegate().ifPresent(delegate -> {
Appender appender = this.replace ? stringAppender
: CompositeAppender.compose(delegate.getAppender(), stringAppender);
delegate.setAppender(appender);
});
getLogger().ifPresent(logger -> logger.addAppender(stringAppender));
return stringAppender;
}
public StringAppender buildAndStart() {
StringAppender stringAppender = build();
stringAppender.start();
return stringAppender;
}
|
}
private final StringAppenderWrapper stringAppenderWrapper;
protected StringAppender(StringAppenderWrapper stringAppenderWrapper) {
if (stringAppenderWrapper == null) {
throw new IllegalArgumentException("StringAppenderWrapper must not be null");
}
this.stringAppenderWrapper = stringAppenderWrapper;
}
public String getLogOutput() {
return getStringAppenderWrapper().toString();
}
protected StringAppenderWrapper getStringAppenderWrapper() {
return this.stringAppenderWrapper;
}
@Override
protected void append(ILoggingEvent loggingEvent) {
Optional.ofNullable(loggingEvent)
.map(event -> preProcessLogMessage(toString(event)))
.filter(this::isValidLogMessage)
.ifPresent(getStringAppenderWrapper()::append);
}
protected boolean isValidLogMessage(String message) {
return message != null && !message.isEmpty();
}
protected String preProcessLogMessage(String message) {
return message != null ? message.trim() : null;
}
protected String toString(ILoggingEvent loggingEvent) {
return loggingEvent != null ? loggingEvent.getFormattedMessage() : null;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\StringAppender.java
| 1
|
请完成以下Java代码
|
public final class RequestMatcherDelegatingAccessDeniedHandler implements AccessDeniedHandler {
private final LinkedHashMap<RequestMatcher, AccessDeniedHandler> handlers;
private final AccessDeniedHandler defaultHandler;
/**
* Creates a new instance
* @param handlers a map of {@link RequestMatcher}s to {@link AccessDeniedHandler}s
* that should be used. Each is considered in the order they are specified and only
* the first {@link AccessDeniedHandler} is used.
* @param defaultHandler the default {@link AccessDeniedHandler} that should be used
* if none of the matchers match.
*/
public RequestMatcherDelegatingAccessDeniedHandler(LinkedHashMap<RequestMatcher, AccessDeniedHandler> handlers,
AccessDeniedHandler defaultHandler) {
Assert.notEmpty(handlers, "handlers cannot be null or empty");
Assert.notNull(defaultHandler, "defaultHandler cannot be null");
this.handlers = new LinkedHashMap<>(handlers);
this.defaultHandler = defaultHandler;
|
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
for (Entry<RequestMatcher, AccessDeniedHandler> entry : this.handlers.entrySet()) {
RequestMatcher matcher = entry.getKey();
if (matcher.matches(request)) {
AccessDeniedHandler handler = entry.getValue();
handler.handle(request, response, accessDeniedException);
return;
}
}
this.defaultHandler.handle(request, response, accessDeniedException);
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandler.java
| 1
|
请完成以下Java代码
|
public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request)
{
return InvoiceCandidateGenerateResult.of(this);
}
/** Does nothing */
@Override
public void invalidateCandidatesFor(final Object model)
{
// nothing to do
}
/**
* @return {@link #MANUAL} (i.e. not a real table name).
*/
@Override
public String getSourceTable()
{
return ManualCandidateHandler.MANUAL;
}
/** @return {@code true}. */
@Override
public boolean isUserInChargeUserEditable()
{
return true;
}
/**
* Does nothing.
|
*/
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
// nothing to do
}
/**
* Does nothing.
*/
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
// nothing to do
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
// nothing to do
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\ManualCandidateHandler.java
| 1
|
请完成以下Java代码
|
public void setIsSubcontracting (final boolean IsSubcontracting)
{
set_Value (COLUMNNAME_IsSubcontracting, IsSubcontracting);
}
@Override
public boolean isSubcontracting()
{
return get_ValueAsBoolean(COLUMNNAME_IsSubcontracting);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPP_WF_Node_Product_ID (final int PP_WF_Node_Product_ID)
{
if (PP_WF_Node_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, PP_WF_Node_Product_ID);
}
@Override
public int getPP_WF_Node_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_WF_Node_Product_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSpecification (final @Nullable java.lang.String Specification)
{
set_Value (COLUMNNAME_Specification, Specification);
}
@Override
public java.lang.String getSpecification()
{
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setYield (final @Nullable BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Product.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractUpdateProcessInstancesSuspendStateCmd<T> implements Command<T> {
protected UpdateProcessInstancesSuspensionStateBuilderImpl builder;
protected CommandExecutor commandExecutor;
protected boolean suspending;
public AbstractUpdateProcessInstancesSuspendStateCmd(CommandExecutor commandExecutor, UpdateProcessInstancesSuspensionStateBuilderImpl builder, boolean suspending) {
this.commandExecutor = commandExecutor;
this.builder = builder;
this.suspending = suspending;
}
protected BatchElementConfiguration collectProcessInstanceIds(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
List<String> processInstanceIds = builder.getProcessInstanceIds();
EnsureUtil.ensureNotContainsNull(BadUserRequestException.class,
"Cannot be null.", "Process Instance ids", processInstanceIds);
if (!CollectionUtil.isEmpty(processInstanceIds)) {
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(processInstanceIds));
elementConfiguration.addDeploymentMappings(
commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), processInstanceIds);
}
ProcessInstanceQueryImpl processInstanceQuery = (ProcessInstanceQueryImpl) builder.getProcessInstanceQuery();
if( processInstanceQuery != null) {
elementConfiguration.addDeploymentMappings(processInstanceQuery.listDeploymentIdMappings());
}
HistoricProcessInstanceQueryImpl historicProcessInstanceQuery = (HistoricProcessInstanceQueryImpl ) builder.getHistoricProcessInstanceQuery();
if( historicProcessInstanceQuery != null) {
elementConfiguration.addDeploymentMappings(historicProcessInstanceQuery.listDeploymentIdMappings());
}
return elementConfiguration;
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances,
boolean async) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
|
propertyChanges.add(new PropertyChange("async", null, async));
String operationType;
if(suspending) {
operationType = UserOperationLogEntry.OPERATION_TYPE_SUSPEND_JOB;
} else {
operationType = UserOperationLogEntry.OPERATION_TYPE_ACTIVATE_JOB;
}
commandContext.getOperationLogManager()
.logProcessInstanceOperation(operationType,
null,
null,
null,
propertyChanges);
}
protected void writeUserOperationLogAsync(CommandContext commandContext, int numInstances) {
writeUserOperationLog(commandContext, numInstances, true);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractUpdateProcessInstancesSuspendStateCmd.java
| 1
|
请完成以下Java代码
|
public Segment enablePartOfSpeechTagging(boolean enable)
{
return super.enablePartOfSpeechTagging(enable);
}
/**
* 词性标注
*
* @param charArray 字符数组
* @param wordNet 词语长度
* @param natureArray 输出词性
*/
protected void posTag(char[] charArray, int[] wordNet, Nature[] natureArray)
{
if (config.speechTagging)
{
for (int i = 0; i < natureArray.length; )
{
if (natureArray[i] == null)
{
int j = i + 1;
for (; j < natureArray.length; ++j)
{
if (natureArray[j] != null) break;
}
List<AtomNode> atomNodeList = quickAtomSegment(charArray, i, j);
for (AtomNode atomNode : atomNodeList)
{
if (atomNode.sWord.length() >= wordNet[i])
{
wordNet[i] = atomNode.sWord.length();
natureArray[i] = atomNode.getNature();
i += wordNet[i];
}
}
i = j;
}
|
else
{
++i;
}
}
}
}
@Override
public Segment enableCustomDictionary(boolean enable)
{
if (enable)
{
logger.warning("为基于词典的分词器开启用户词典太浪费了,建议直接将所有词典的路径传入构造函数,这样速度更快、内存更省");
}
return super.enableCustomDictionary(enable);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\DictionaryBasedSegment.java
| 1
|
请完成以下Java代码
|
/* package */final class AllocationRequest implements IAllocationRequest
{
@Getter
private final IHUContext huContext;
@Getter
private final ProductId productId;
@Getter
private final Quantity quantity;
@Getter
private final ZonedDateTime date;
@Getter
private final boolean forceQtyAllocation;
@Getter
@Nullable
private final ClearanceStatusInfo clearanceStatusInfo;
private final boolean deleteEmptyAndJustCreatedAggregatedTUs;
// Reference
private final TableRecordReference fromTableRecord;
public AllocationRequest(
@NonNull final IHUContext huContext,
@NonNull final ProductId productId,
@NonNull final Quantity quantity,
@NonNull final ZonedDateTime date,
final TableRecordReference fromTableRecord,
final boolean forceQtyAllocation,
@Nullable final ClearanceStatusInfo clearanceStatusInfo,
final boolean deleteEmptyAndJustCreatedAggregatedTUs)
{
Check.assumeNotNull(quantity.signum() >= 0, "qty >= 0 ({})", quantity);
this.huContext = huContext;
this.productId = productId;
this.quantity = quantity;
this.date = date;
// Check.assumeNotNull(fromTableRecord, "fromTableRecord not null");
this.fromTableRecord = fromTableRecord;
this.forceQtyAllocation = forceQtyAllocation;
this.clearanceStatusInfo = clearanceStatusInfo;
this.deleteEmptyAndJustCreatedAggregatedTUs = deleteEmptyAndJustCreatedAggregatedTUs;
}
@Override
public String toString()
{
final String fromTableRecordStr = fromTableRecord == null ? null : "" + fromTableRecord.getTableName() + "/" + fromTableRecord.getRecord_ID();
return "AllocationRequest ["
+ "product=" + productId
+ ", qty=" + (isInfiniteQty() ? "inifinite" : quantity)
+ ", date=" + date
+ ", fromTableRecord=" + fromTableRecordStr
+ ", forceQtyAllocation=" + forceQtyAllocation
|
+ ", clearanceStatusInfo=" + clearanceStatusInfo
+ "]";
}
@Override
public BigDecimal getQty()
{
return quantity.toBigDecimal();
}
@Override
public boolean isZeroQty()
{
return quantity.isZero();
}
@Override
public boolean isInfiniteQty()
{
return quantity.isInfinite();
}
@Override
public I_C_UOM getC_UOM()
{
return quantity.getUOM();
}
@Override
public TableRecordReference getReference()
{
return fromTableRecord;
}
@Override
public boolean isDeleteEmptyAndJustCreatedAggregatedTUs()
{
return deleteEmptyAndJustCreatedAggregatedTUs;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<UploadResultResource> uploadFile(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) {
UploadResultResource result = new UploadResultResource(file, text, text1, text2, upstream);
return new ResponseEntity<>(result, HttpStatus.OK);
}
public static class UploadResultResource {
private final String file;
private final String text;
private final String text1;
private final String text2;
private final String upstream;
public UploadResultResource(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) {
this.file = format(file);
this.text = text;
this.text1 = text1;
this.text2 = text2;
this.upstream = format(upstream);
}
private static String format(MultipartFile file) {
return file == null ? null : file.getOriginalFilename() + " (size: " + file.getSize() + " bytes)";
}
|
public String getFile() {
return file;
}
public String getText() {
return text;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
public String getUpstream() {
return upstream;
}
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\web\controller\MultipartFileUploadStubController.java
| 2
|
请完成以下Java代码
|
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set V_Date.
@param V_Date V_Date */
public void setV_Date (Timestamp V_Date)
{
set_Value (COLUMNNAME_V_Date, V_Date);
}
/** Get V_Date.
@return V_Date */
public Timestamp getV_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_V_Date);
}
/** Set V_Number.
@param V_Number V_Number */
public void setV_Number (String V_Number)
|
{
set_Value (COLUMNNAME_V_Number, V_Number);
}
/** Get V_Number.
@return V_Number */
public String getV_Number ()
{
return (String)get_Value(COLUMNNAME_V_Number);
}
/** Set V_String.
@param V_String V_String */
public void setV_String (String V_String)
{
set_Value (COLUMNNAME_V_String, V_String);
}
/** Get V_String.
@return V_String */
public String getV_String ()
{
return (String)get_Value(COLUMNNAME_V_String);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute_Value.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SAPGLJournalCreateRequest
{
@NonNull DocTypeId docTypeId;
@NonNull SAPGLJournalCurrencyConversionCtx conversionCtx;
@NonNull AcctSchemaId acctSchemaId;
@NonNull PostingType postingType;
@NonNull Instant dateDoc;
@NonNull Money totalAcctDR;
@NonNull Money totalAcctCR;
@NonNull OrgId orgId;
@NonNull String description;
@NonNull GLCategoryId glCategoryId;
@NonNull Dimension dimension;
@NonNull ImmutableList<SAPGLJournalLineCreateRequest> lines;
@Nullable
SAPGLJournalId reversalId;
@NonNull
public static SAPGLJournalCreateRequest of(
@NonNull final SAPGLJournal journal,
@NonNull final Instant dateDoc,
final boolean negateAmounts)
{
|
return SAPGLJournalCreateRequest.builder()
.docTypeId(journal.getDocTypeId())
.conversionCtx(journal.getConversionCtx())
.dateDoc(dateDoc)
.acctSchemaId(journal.getAcctSchemaId())
.postingType(journal.getPostingType())
.totalAcctDR(journal.getTotalAcctDR().negateIf(negateAmounts))
.totalAcctCR(journal.getTotalAcctCR().negateIf(negateAmounts))
.orgId(journal.getOrgId())
.dimension(journal.getDimension())
.description(journal.getDescription())
.glCategoryId(journal.getGlCategoryId())
.reversalId(null)
//
.lines(journal.getLines()
.stream()
.map(line -> SAPGLJournalLineCreateRequest.of(line, negateAmounts))
.collect(ImmutableList.toImmutableList()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalCreateRequest.java
| 2
|
请完成以下Java代码
|
public String getName()
{
return name;
}
public Map<String, String> getNameTrls()
{
return nameTrls;
}
private void setName(final String adLanguage, final String nameTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if(nameTrl == null)
{
return;
}
if(nameTrls == null)
{
nameTrls = new HashMap<>();
}
nameTrls.put(adLanguage, nameTrl);
}
public String getDescription()
{
return description;
}
public Map<String, String> getDescriptionTrls()
{
return descriptionTrls;
}
private void setDescription(final String adLanguage, final String descriptionTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if(descriptionTrl == null)
{
return;
}
if(descriptionTrls == null)
{
descriptionTrls = new HashMap<>();
}
descriptionTrls.put(adLanguage, descriptionTrl);
}
public String getHelp()
{
return help;
}
public Map<String, String> getHelpTrls()
{
return helpTrls;
}
private void setHelp(final String adLanguage, final String helpTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if(helpTrl == null)
{
return;
}
if(helpTrls == null)
{
helpTrls = new HashMap<>();
}
helpTrls.put(adLanguage, helpTrl);
}
void setReadWrite(final boolean readWrite)
{
this._isReadWrite = readWrite;
}
|
public boolean isReadWrite()
{
return Boolean.TRUE.equals(_isReadWrite);
}
private void setIsSOTrx(final boolean isSOTrx)
{
this._isSOTrx = isSOTrx;
}
public boolean isSOTrx()
{
return _isSOTrx;
}
public int getAD_Color_ID()
{
return AD_Color_ID;
}
public int getAD_Image_ID()
{
return AD_Image_ID;
}
public int getWinWidth()
{
return WinWidth;
}
public int getWinHeight()
{
return WinHeight;
}
public String getWindowType()
{
return WindowType;
}
private int getBaseTable_ID()
{
return _BaseTable_ID;
}
boolean isLoadAllLanguages()
{
return loadAllLanguages;
}
boolean isApplyRolePermissions()
{
return applyRolePermissions;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java
| 1
|
请完成以下Java代码
|
public HistoricProcessInstanceQuery externallyTerminated() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_EXTERNALLY_TERMINATED);
return this;
}
@Override
public HistoricProcessInstanceQuery internallyTerminated() {
if(!isOrQueryActive) {
ensureEmpty(BadUserRequestException.class, "Already querying for historic process instance with another state", state);
}
state.add(HistoricProcessInstance.STATE_INTERNALLY_TERMINATED);
return this;
}
@Override
public HistoricProcessInstanceQuery or() {
if (this != queries.get(0)) {
|
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
HistoricProcessInstanceQueryImpl orQuery = new HistoricProcessInstanceQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public HistoricProcessInstanceQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricProcessInstanceQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PPOrderWeightingRunService
{
private final PPOrderWeightingRunRepository ppOrderWeightingRunRepository;
public PPOrderWeightingRunService(
@NonNull final PPOrderWeightingRunRepository ppOrderWeightingRunRepository)
{
this.ppOrderWeightingRunRepository = ppOrderWeightingRunRepository;
}
public PPOrderWeightingRun getById(@NonNull final PPOrderWeightingRunId id)
{
return ppOrderWeightingRunRepository.getById(id);
}
public void process(final PPOrderWeightingRunId id)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::process);
}
public void unprocess(final PPOrderWeightingRunId id)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::unprocess);
}
public SeqNo getNextLineNo(final PPOrderWeightingRunId weightingRunId)
{
return ppOrderWeightingRunRepository.getNextLineNo(weightingRunId);
}
public void updateFromChecks(final Collection<PPOrderWeightingRunId> ids)
{
// NOTE: we usually expect only one element here, so it's OK to iterate
for (final PPOrderWeightingRunId id : ids)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::updateToleranceExceededFlag);
}
|
}
public UomId getUomId(final PPOrderWeightingRunId id)
{
return ppOrderWeightingRunRepository.getUomId(id);
}
public PPOrderWeightingRunCheckId addRunCheck(
@NonNull PPOrderWeightingRunId weightingRunId,
@NonNull final BigDecimal weightBD)
{
PPOrderWeightingRun weightingRun = getById(weightingRunId);
final Quantity weight = Quantity.of(weightBD, weightingRun.getUOM());
final SeqNo lineNo = weightingRun.getNextLineNo();
final OrgId orgId = weightingRun.getOrgId();
final PPOrderWeightingRunCheckId weightingRunCheckId = ppOrderWeightingRunRepository.addRunCheck(weightingRunId, lineNo, weight, orgId);
weightingRun = getById(weightingRunId);
weightingRun.updateToleranceExceededFlag();
ppOrderWeightingRunRepository.save(weightingRun);
return weightingRunCheckId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunService.java
| 2
|
请完成以下Java代码
|
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
protected HistoricBatchQuery createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricBatchQuery();
}
protected void applyFilters(HistoricBatchQuery query) {
if (batchId != null) {
query.batchId(batchId);
}
if (type != null) {
query.type(type);
}
if (completed != null) {
query.completed(completed);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
|
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
}
protected void applySortBy(HistoricBatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) {
query.orderById();
}
if (sortBy.equals(SORT_BY_BATCH_START_TIME_VALUE)) {
query.orderByStartTime();
}
if (sortBy.equals(SORT_BY_BATCH_END_TIME_VALUE)) {
query.orderByEndTime();
}
if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchQueryDto.java
| 1
|
请完成以下Java代码
|
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
public ByteArrayEntity getContent() {
return content;
}
public void setContent(ByteArrayEntity content) {
this.content = content;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public Date getRemovalTime() {
|
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", description=" + description
+ ", type=" + type
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", url=" + url
+ ", contentId=" + contentId
+ ", content=" + content
+ ", tenantId=" + tenantId
+ ", createTime=" + createTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java
| 1
|
请完成以下Java代码
|
private static void setAbsoluteColumnWidthsInTableWidth(PdfPTable table) throws DocumentException {
table.setTotalWidth(new float[] {72f, 144f, 216f}); // First column 1 inch, second 2 inches, third 3 inches
table.setLockedWidth(true);
}
private static void setRelativeColumnWidths(PdfPTable table) throws DocumentException {
// Set column widths (relative)
table.setWidths(new float[] {1, 2, 1});
table.setWidthPercentage(80); // Table width as 80% of page width
}
private static void addRows(PdfPTable table) {
table.addCell("row 1, col 1");
table.addCell("row 1, col 2");
table.addCell("row 1, col 3");
}
|
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
Image img = Image.getInstance(path.toAbsolutePath().toString());
img.scalePercent(10);
PdfPCell imageCell = new PdfPCell(img);
table.addCell(imageCell);
PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(horizontalAlignCell);
PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(verticalAlignCell);
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDFSampleMain.java
| 1
|
请完成以下Java代码
|
private static LocalDate parseDate(String birthDateAsString) throws DateParseException {
LocalDate birthDate;
try {
birthDate = LocalDate.parse(birthDateAsString);
} catch (DateTimeParseException ex) {
throw new InvalidFormatException(birthDateAsString, ex);
}
if (birthDate.isAfter(LocalDate.now())) {
throw new DateOutOfRangeException(birthDateAsString);
}
return birthDate;
}
}
static class CalculationException extends Exception {
CalculationException(DateParseException ex) {
super(ex);
}
}
static class DateParseException extends Exception {
DateParseException(String input) {
super(input);
}
|
DateParseException(String input, Throwable thr) {
super(input, thr);
}
}
static class InvalidFormatException extends DateParseException {
InvalidFormatException(String input, Throwable thr) {
super("Invalid date format: " + input, thr);
}
}
static class DateOutOfRangeException extends DateParseException {
DateOutOfRangeException(String date) {
super("Date out of range: " + date);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-exceptions-2\src\main\java\com\baeldung\rootcausefinder\RootCauseFinder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class HazelcastJCacheCustomizationConfiguration {
@Bean
HazelcastPropertiesCustomizer hazelcastPropertiesCustomizer(ObjectProvider<HazelcastInstance> hazelcastInstance,
CacheProperties cacheProperties) {
return new HazelcastPropertiesCustomizer(hazelcastInstance.getIfUnique(), cacheProperties);
}
static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer {
private final @Nullable HazelcastInstance hazelcastInstance;
private final CacheProperties cacheProperties;
HazelcastPropertiesCustomizer(@Nullable HazelcastInstance hazelcastInstance, CacheProperties cacheProperties) {
this.hazelcastInstance = hazelcastInstance;
this.cacheProperties = cacheProperties;
}
@Override
public void customize(Properties properties) {
Resource configLocation = this.cacheProperties
.resolveConfigLocation(this.cacheProperties.getJcache().getConfig());
if (configLocation != null) {
// Hazelcast does not use the URI as a mean to specify a custom config.
|
properties.setProperty("hazelcast.config.location", toUri(configLocation).toString());
}
else if (this.hazelcastInstance != null) {
properties.put("hazelcast.instance.itself", this.hazelcastInstance);
}
}
private static URI toUri(Resource config) {
try {
return config.getURI();
}
catch (IOException ex) {
throw new IllegalArgumentException("Could not get URI from " + config, ex);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\HazelcastJCacheCustomizationConfiguration.java
| 2
|
请完成以下Java代码
|
public Comparator<Integer> findProductIdsComparator()
{
final I_C_DocLine_Sort docLineSort = find();
if (docLineSort == null)
{
return NullComparator.getInstance();
}
return new DocLineSortProductIdsComparator(docLineSort);
}
@Override
public IDocLineSortItemFinder setContext(final Properties ctx)
{
_ctx = ctx;
return this;
}
private final Properties getCtx()
{
Check.assumeNotNull(_ctx, "_ctx not null");
return _ctx;
}
@Override
public DocLineSortItemFinder setDocBaseType(final String docBaseType)
{
_docTypeSet = true;
_docBaseType = docBaseType;
return this;
}
@Override
public DocLineSortItemFinder setC_DocType(final I_C_DocType docType)
{
_docTypeSet = true;
_docType = docType;
return this;
|
}
private final String getDocBaseType()
{
Check.assume(_docTypeSet, "DocType or DocbaseType was set");
if (_docType != null)
{
return _docType.getDocBaseType();
}
else if (_docBaseType != null)
{
return _docBaseType;
}
else
{
// throw new AdempiereException("DocBaseType not found"); // can be null
return null;
}
}
@Override
public DocLineSortItemFinder setC_BPartner_ID(final int bpartnerId)
{
_bpartnerIdSet = true;
_bpartnerId = bpartnerId;
return this;
}
private final int getC_BPartner_ID()
{
Check.assume(_bpartnerIdSet, "C_BPartner_ID was set");
return _bpartnerId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\docline\sort\api\impl\DocLineSortItemFinder.java
| 1
|
请完成以下Java代码
|
public final class Constants {
private Constants() {
}
/** id of bankstatement window */
public static final AdWindowId BANKSTATEMENT_WINDOW_ID = AdWindowId.ofRepoId(194);
/** system config entry for recurrent payment invoice document type */
public static final String RECURRENT_PAYMENT_INVOICE_DOCUMENTTYPE_ID = "RecurrentPaymentInvoice_DocumentTypeID";
public static final String DIRECT_DEBIT_ACCOUNT_NO = "DIRECT_DEBIT_ACCOUNT_NO";
public static final String DIRECT_DEBIT_ROUTING_NO = "DIRECT_DEBIT_ROUTING_NO";
public static final String C_Invoice_C_RecurrentPaymentLine_ID = "C_RecurrentPaymentLine_ID";
public static final String LOCATION_NAME = null;
public static final String SAG = null;
public static final String TEST_MAILADDRESS = null;
|
public static final String CCPAYMENT_REVIEW_MAILS = null;
public static final String LIVESYSTEM_SERVERNAME = null;
public static final String TIME_BEFORE_PROMISED_CC = null;
public static final String CC_PAYMENT_BANKACCOUNT_ID = null;
public static final String UPS_ACCESS_LICENSE_NUMBER = null;
public static final String UPS_USER_ID = null;
public static final String UPS_PASSWORD = null;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\constants\Constants.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getOwner() {
return ownerId;
}
@Override
public String getAssignee() {
return assigneeId;
}
@Override
public String getTaskDefinitionId() {
return taskDefinitionId;
}
@Override
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
@Override
public Date getDueDate() {
return dueDate;
}
@Override
public String getCategory() {
return category;
}
@Override
public String getParentTaskId() {
return parentTaskId;
|
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() {
return identityLinks;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
| 2
|
请完成以下Java代码
|
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getLoginType() {
return loginType;
}
public void setLoginType(Integer loginType) {
this.loginType = loginType;
}
public String getProvince() {
|
return province;
}
public void setProvince(String province) {
this.province = province;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", createTime=").append(createTime);
sb.append(", ip=").append(ip);
sb.append(", city=").append(city);
sb.append(", loginType=").append(loginType);
sb.append(", province=").append(province);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLoginLog.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.di
|
alect.MySQL8Dialect
spring.jpa.open-in-view=false
spring.flyway.schemas=bookstoredb
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLDatabase\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
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 void setCardSeqNb(String value) {
this.cardSeqNb = value;
}
/**
* Gets the value of the fctvDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFctvDt() {
return fctvDt;
}
/**
* Sets the value of the fctvDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFctvDt(XMLGregorianCalendar value) {
this.fctvDt = value;
}
/**
* Gets the value of the xpryDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getXpryDt() {
return xpryDt;
}
/**
* Sets the value of the xpryDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setXpryDt(XMLGregorianCalendar value) {
this.xpryDt = value;
}
/**
* Gets the value of the svcCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSvcCd() {
return svcCd;
}
/**
* Sets the value of the svcCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSvcCd(String value) {
this.svcCd = value;
}
/**
|
* Gets the value of the trckData 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 trckData property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTrckData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TrackData1 }
*
*
*/
public List<TrackData1> getTrckData() {
if (trckData == null) {
trckData = new ArrayList<TrackData1>();
}
return this.trckData;
}
/**
* Gets the value of the cardSctyCd property.
*
* @return
* possible object is
* {@link CardSecurityInformation1 }
*
*/
public CardSecurityInformation1 getCardSctyCd() {
return cardSctyCd;
}
/**
* Sets the value of the cardSctyCd property.
*
* @param value
* allowed object is
* {@link CardSecurityInformation1 }
*
*/
public void setCardSctyCd(CardSecurityInformation1 value) {
this.cardSctyCd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PlainCardData1.java
| 1
|
请完成以下Java代码
|
public void notify(DelegateExecution execution) {
if (script == null) {
throw new IllegalArgumentException("The field 'script' should be set on the ExecutionListener");
}
if (language == null) {
throw new IllegalArgumentException("The field 'language' should be set on the ExecutionListener");
}
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
Object result = scriptingEngines.evaluate(script.getExpressionText(), language.getExpressionText(), execution);
if (resultVariable != null) {
|
execution.setVariable(resultVariable.getExpressionText(), result);
}
}
public void setScript(Expression script) {
this.script = script;
}
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ScriptExecutionListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//校验用户
auth.userDetailsService( userDetailsService ).passwordEncoder( new PasswordEncoder() {
//对密码进行加密
@Override
public String encode(CharSequence charSequence) {
System.out.println(charSequence.toString());
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
}
//对密码进行判断匹配
@Override
public boolean matches(CharSequence charSequence, String s) {
String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
boolean res = s.equals( encode );
return res;
}
} );
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
//因为使用JWT,所以不需要HttpSession
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
//OPTIONS请求全部放行
.antMatchers( HttpMethod.OPTIONS, "/**").permitAll()
|
//登录接口放行
.antMatchers("/auth/login").permitAll()
//其他接口全部接受验证
.anyRequest().authenticated();
//使用自定义的 Token过滤器 验证请求的Token是否合法
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
@Bean
public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
|
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public static BigDecimal divide(Object a, Object b, int scale) {
BigDecimal bdA = toBigDecimal(a);
BigDecimal bdB = toBigDecimal(b);
return bdA.divide(bdB, scale, RoundingMode.HALF_UP);
}
/**
* 分转元
* @param obj 分的金额
* @return 转换后的元,保留两位小数
*/
public static BigDecimal centsToYuan(Object obj) {
BigDecimal cents = toBigDecimal(obj);
return cents.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
}
/**
* 元转分
* @param obj 元的金额
* @return 转换后的分
*/
public static Long yuanToCents(Object obj) {
|
BigDecimal yuan = toBigDecimal(obj);
return yuan.multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.HALF_UP).longValue();
}
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.123");
BigDecimal num2 = new BigDecimal("2.456");
System.out.println("加法结果: " + add(num1, num2));
System.out.println("减法结果: " + subtract(num1, num2));
System.out.println("乘法结果: " + multiply(num1, num2));
System.out.println("除法结果: " + divide(num1, num2));
Long cents = 12345L;
System.out.println("分转元结果: " + centsToYuan(cents));
BigDecimal yuan = new BigDecimal("123.45");
System.out.println("元转分结果: " + yuanToCents(yuan));
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\BigDecimalUtils.java
| 1
|
请完成以下Java代码
|
public final DefaultPaymentBuilder invoiceId(@Nullable final InvoiceId invoiceId)
{
assertNotBuilt();
payment.setC_Invoice_ID(InvoiceId.toRepoId(invoiceId));
return this;
}
public final DefaultPaymentBuilder description(final String description)
{
assertNotBuilt();
payment.setDescription(description);
return this;
}
public final DefaultPaymentBuilder externalId(@Nullable final ExternalId externalId)
{
assertNotBuilt();
if (externalId != null)
{
payment.setExternalId(externalId.getValue());
}
return this;
}
public final DefaultPaymentBuilder orderId(@Nullable final OrderId orderId)
{
assertNotBuilt();
if (orderId != null)
{
payment.setC_Order_ID(orderId.getRepoId());
}
return this;
}
public final DefaultPaymentBuilder orderExternalId(@Nullable final String orderExternalId)
{
assertNotBuilt();
if (Check.isNotBlank(orderExternalId))
{
|
payment.setExternalOrderId(orderExternalId);
}
return this;
}
public final DefaultPaymentBuilder isAutoAllocateAvailableAmt(final boolean isAutoAllocateAvailableAmt)
{
assertNotBuilt();
payment.setIsAutoAllocateAvailableAmt(isAutoAllocateAvailableAmt);
return this;
}
private DefaultPaymentBuilder fromOrder(@NonNull final I_C_Order order)
{
adOrgId(OrgId.ofRepoId(order.getAD_Org_ID()));
orderId(OrderId.ofRepoId(order.getC_Order_ID()));
bpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
currencyId(CurrencyId.ofRepoId(order.getC_Currency_ID()));
final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx());
direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, false));
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\DefaultPaymentBuilder.java
| 1
|
请完成以下Java代码
|
public void setUrl2(final String url2)
{
this.url2 = url2;
this.url2Set = true;
}
public void setUrl3(final String url3)
{
this.url3 = url3;
this.url3Set = true;
}
public void setGroup(final String group)
{
this.group = group;
this.groupSet = true;
}
public void setGlobalId(final String globalId)
{
this.globalId = globalId;
this.globalIdset = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
|
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
public void setMemo(final String memo)
{
this.memo = memo;
this.memoIsSet = true;
}
public void setPriceListId(@Nullable final JsonMetasfreshId priceListId)
{
if (JsonMetasfreshId.toValue(priceListId) != null)
{
this.priceListId = priceListId;
this.priceListIdSet = true;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestBPartner.java
| 1
|
请完成以下Java代码
|
public void setES_FieldPath (final @Nullable java.lang.String ES_FieldPath)
{
set_Value (COLUMNNAME_ES_FieldPath, ES_FieldPath);
}
@Override
public java.lang.String getES_FieldPath()
{
return get_ValueAsString(COLUMNNAME_ES_FieldPath);
}
@Override
public void setIsGroupBy (final boolean IsGroupBy)
{
set_Value (COLUMNNAME_IsGroupBy, IsGroupBy);
}
@Override
public boolean isGroupBy()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupBy);
}
@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 setOffsetName (final @Nullable java.lang.String OffsetName)
{
set_Value (COLUMNNAME_OffsetName, OffsetName);
}
@Override
public java.lang.String getOffsetName()
{
return get_ValueAsString(COLUMNNAME_OffsetName);
}
@Override
public void setSQL_Select (final @Nullable java.lang.String SQL_Select)
{
set_Value (COLUMNNAME_SQL_Select, SQL_Select);
}
@Override
public java.lang.String getSQL_Select()
{
return get_ValueAsString(COLUMNNAME_SQL_Select);
}
@Override
public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol)
{
set_Value (COLUMNNAME_UOMSymbol, UOMSymbol);
}
@Override
public java.lang.String getUOMSymbol()
{
return get_ValueAsString(COLUMNNAME_UOMSymbol);
}
@Override
public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID)
{
if (WEBUI_KPI_Field_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID);
}
@Override
public int getWEBUI_KPI_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class);
}
@Override
public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI)
{
set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java
| 1
|
请完成以下Java代码
|
public void segment(String sentence, String normalized, List<String> wordList)
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
analyzer.segment(sentence, normalized, wordList);
}
@Override
public List<String> segment(String sentence)
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.segment(sentence);
}
@Override
public String[] recognize(String[] wordArray, String[] posArray)
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.recognize(wordArray, posArray);
}
@Override
public String[] tag(String... words)
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.tag(words);
}
@Override
public String[] tag(List<String> wordList)
|
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.tag(wordList);
}
@Override
public NERTagSet getNERTagSet()
{
LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null)
throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe");
return analyzer.getNERTagSet();
}
@Override
public Sentence analyze(String sentence)
{
return new Sentence(flow(sentence));
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\LexicalAnalyzerPipeline.java
| 1
|
请完成以下Java代码
|
public class SessionNameRequest {
private Date requestDate;
private NameRequest nameRequest;
public SessionNameRequest() {
super();
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public NameRequest getNameRequest() {
return nameRequest;
}
public void setNameRequest(NameRequest nameRequest) {
this.nameRequest = nameRequest;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((requestDate == null) ? 0 : requestDate.hashCode());
result = prime * result + ((nameRequest == null) ? 0 : nameRequest.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;
SessionNameRequest other = (SessionNameRequest) obj;
|
if (requestDate == null) {
if (other.requestDate != null)
return false;
} else if (!requestDate.equals(other.requestDate))
return false;
if (nameRequest == null) {
if (other.nameRequest != null)
return false;
} else if (!nameRequest.equals(other.nameRequest))
return false;
return true;
}
@Override
public String toString() {
return "SessionNameRequest [requestDate=" + requestDate + ", nameRequest=" + nameRequest + "]";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\web\beans\SessionNameRequest.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.