instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
protected boolean supports(Class<?> clazz) {
return OAuth2AccessTokenResponse.class.isAssignableFrom(clazz);
}
@Override
@SuppressWarnings("unchecked")
protected OAuth2AccessTokenResponse readInternal(Class<? extends OAuth2AccessTokenResponse> clazz,
HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
try {
Map<String, Object> tokenResponseParameters = (Map<String, Object>) this.jsonMessageConverter
.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
return this.accessTokenResponseConverter.convert(tokenResponseParameters);
}
catch (Exception ex) {
throw new HttpMessageNotReadableException(
"An error occurred reading the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex,
inputMessage);
}
}
@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter
.convert(tokenResponse);
this.jsonMessageConverter.write(tokenResponseParameters, STRING_OBJECT_MAP.getType(),
MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
}
|
/**
* Sets the {@link Converter} used for converting the OAuth 2.0 Access Token Response
* parameters to an {@link OAuth2AccessTokenResponse}.
* @param accessTokenResponseConverter the {@link Converter} used for converting to an
* {@link OAuth2AccessTokenResponse}
* @since 5.6
*/
public final void setAccessTokenResponseConverter(
Converter<Map<String, Object>, OAuth2AccessTokenResponse> accessTokenResponseConverter) {
Assert.notNull(accessTokenResponseConverter, "accessTokenResponseConverter cannot be null");
this.accessTokenResponseConverter = accessTokenResponseConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2AccessTokenResponse} to a {@code Map} representation of the OAuth 2.0
* Access Token Response parameters.
* @param accessTokenResponseParametersConverter the {@link Converter} used for
* converting to a {@code Map} representation of the Access Token Response parameters
* @since 5.6
*/
public final void setAccessTokenResponseParametersConverter(
Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter) {
Assert.notNull(accessTokenResponseParametersConverter, "accessTokenResponseParametersConverter cannot be null");
this.accessTokenResponseParametersConverter = accessTokenResponseParametersConverter;
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2AccessTokenResponseHttpMessageConverter.java
| 1
|
请完成以下Java代码
|
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
/**
* Use this {@link ServerWebExchangeMatcher} to narrow which requests are redirected
* to HTTPS.
*
* The filter already first checks for HTTPS in the uri scheme, so it is not necessary
* to include that check in this matcher.
* @param requiresHttpsRedirectMatcher the {@link ServerWebExchangeMatcher} to use
*/
public void setRequiresHttpsRedirectMatcher(ServerWebExchangeMatcher requiresHttpsRedirectMatcher) {
Assert.notNull(requiresHttpsRedirectMatcher, "requiresHttpsRedirectMatcher cannot be null");
this.requiresHttpsRedirectMatcher = requiresHttpsRedirectMatcher;
}
|
private boolean isInsecure(ServerWebExchange exchange) {
return !"https".equals(exchange.getRequest().getURI().getScheme());
}
private URI createRedirectUri(ServerWebExchange exchange) {
int port = exchange.getRequest().getURI().getPort();
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(exchange.getRequest().getURI());
if (port > 0) {
Integer httpsPort = this.portMapper.lookupHttpsPort(port);
Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port");
builder.port(httpsPort);
}
return builder.scheme("https").build().toUri();
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\transport\HttpsRedirectWebFilter.java
| 1
|
请完成以下Java代码
|
private TULoaderInstance newTULoaderInstance(@NonNull final TULoaderInstanceKey key)
{
return TULoaderInstance.builder()
.huContext(huContext)
.tuPI(tuPI)
.capacity(capacity)
.bpartnerId(key.getBpartnerId())
.bpartnerLocationRepoId(key.getBpartnerLocationRepoId())
.locatorId(key.getLocatorId())
.huStatus(key.getHuStatus())
.clearanceStatusInfo(key.getClearanceStatusInfo())
.build();
}
//
//
//
@Value
private static class TULoaderInstanceKey
{
@Nullable BPartnerId bpartnerId;
|
int bpartnerLocationRepoId;
@Nullable LocatorId locatorId;
@Nullable String huStatus;
@Nullable ClearanceStatusInfo clearanceStatusInfo;
@Builder
private TULoaderInstanceKey(
@Nullable final BPartnerId bpartnerId,
final int bpartnerLocationRepoId,
@Nullable final LocatorId locatorId,
@Nullable final String huStatus,
@Nullable final ClearanceStatusInfo clearanceStatusInfo)
{
this.bpartnerId = bpartnerId;
this.bpartnerLocationRepoId = bpartnerLocationRepoId > 0 ? bpartnerLocationRepoId : -1;
this.locatorId = locatorId;
this.huStatus = StringUtils.trimBlankToNull(huStatus);
this.clearanceStatusInfo = clearanceStatusInfo;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrdersDataSourceConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.orders")
public DataSourceProperties ordersDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource ordersDataSource() {
DataSourceProperties primaryDataSourceProperties = ordersDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(primaryDataSourceProperties.getDriverClassName())
.url(primaryDataSourceProperties.getUrl())
.username(primaryDataSourceProperties.getUsername())
.password(primaryDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager ordersTransactionManager()
{
EntityManagerFactory factory = ordersEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean ordersEntityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(ordersDataSource());
factory.setPackagesToScan(new String[]{"net.alanbinu.springboot.springbootmultipledatasources.orders.entities"});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
|
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
@Bean
public DataSourceInitializer ordersDataSourceInitializer()
{
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(ordersDataSource());
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("orders-data.sql"));
dataSourceInitializer.setDatabasePopulator(databasePopulator);
dataSourceInitializer.setEnabled(env.getProperty("datasource.orders.initialize", Boolean.class, false));
return dataSourceInitializer;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\config\OrdersDataSourceConfig.java
| 2
|
请完成以下Java代码
|
public GatewayFilter apply(Config config) {
// token 和 userId 的映射
Map<String, Integer> tokenMap = new HashMap<>();
tokenMap.put("yunai", 1);
// 创建 GatewayFilter 对象
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获得 token
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(config.getTokenHeaderName());
// 如果没有 token,则不进行认证。因为可能是无需认证的 API 接口
if (!StringUtils.hasText(token)) {
return chain.filter(exchange);
}
// 进行认证
ServerHttpResponse response = exchange.getResponse();
Integer userId = tokenMap.get(token);
// 通过 token 获取不到 userId,说明认证不通过
if (userId == null) {
// 响应 401 状态码
response.setStatusCode(HttpStatus.UNAUTHORIZED);
// 响应提示
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap("认证不通过".getBytes());
return response.writeWith(Flux.just(buffer));
}
// 认证通过,将 userId 添加到 Header 中
request = request.mutate().header(config.getUserIdHeaderName(), String.valueOf(userId))
.build();
return chain.filter(exchange.mutate().request(request).build());
}
};
}
public static class Config {
|
private static final String DEFAULT_TOKEN_HEADER_NAME = "token";
private static final String DEFAULT_HEADER_NAME = "user-id";
private String tokenHeaderName = DEFAULT_TOKEN_HEADER_NAME;
private String userIdHeaderName = DEFAULT_HEADER_NAME;
public String getTokenHeaderName() {
return tokenHeaderName;
}
public String getUserIdHeaderName() {
return userIdHeaderName;
}
public Config setTokenHeaderName(String tokenHeaderName) {
this.tokenHeaderName = tokenHeaderName;
return this;
}
public Config setUserIdHeaderName(String userIdHeaderName) {
this.userIdHeaderName = userIdHeaderName;
return this;
}
}
}
|
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo05-custom-gateway-filter\src\main\java\cn\iocoder\springcloud\labx08\gatewaydemo\filter\AuthGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public ExpressionNode getRoot() {
return root;
}
public boolean isDeferred() {
return deferred;
}
@Override
public String toString() {
return getRoot().getStructuralId(null);
}
/**
* Create a bindings.
* @param fnMapper the function mapper to use
* @param varMapper the variable mapper to use
* @return tree bindings
*/
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper) {
return bind(fnMapper, varMapper, null);
}
/**
* Create a bindings.
* @param fnMapper the function mapper to use
* @param varMapper the variable mapper to use
* @param converter custom type converter
* @return tree bindings
*/
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper, TypeConverter converter) {
Method[] methods = null;
if (!functions.isEmpty()) {
if (fnMapper == null) {
throw new ELException(LocalMessages.get("error.function.nomapper"));
}
methods = new Method[functions.size()];
for (int i = 0; i < functions.size(); i++) {
|
FunctionNode node = functions.get(i);
String image = node.getName();
Method method = null;
int colon = image.indexOf(':');
if (colon < 0) {
method = fnMapper.resolveFunction("", image);
} else {
method = fnMapper.resolveFunction(image.substring(0, colon), image.substring(colon + 1));
}
if (method == null) {
throw new ELException(LocalMessages.get("error.function.notfound", image));
}
if (node.isVarArgs() && method.isVarArgs()) {
if (method.getParameterTypes().length > node.getParamCount() + 1) {
throw new ELException(LocalMessages.get("error.function.params", image));
}
} else {
if (method.getParameterTypes().length != node.getParamCount()) {
throw new ELException(LocalMessages.get("error.function.params", image));
}
}
methods[node.getIndex()] = method;
}
}
ValueExpression[] expressions = null;
if (identifiers.size() > 0) {
expressions = new ValueExpression[identifiers.size()];
for (int i = 0; i < identifiers.size(); i++) {
IdentifierNode node = identifiers.get(i);
ValueExpression expression = null;
if (varMapper != null) {
expression = varMapper.resolveVariable(node.getName());
}
expressions[node.getIndex()] = expression;
}
}
return new Bindings(methods, expressions, converter);
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Tree.java
| 1
|
请完成以下Java代码
|
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isInterrupting() {
return isInterrupting;
}
public void setInterrupting(boolean isInterrupting) {
this.isInterrupting = isInterrupting;
}
public List<FormProperty> getFormProperties() {
return formProperties;
}
public void setFormProperties(List<FormProperty> formProperties) {
this.formProperties = formProperties;
}
public String getValidateFormFields() {
return validateFormFields;
}
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
|
@Override
public StartEvent clone() {
StartEvent clone = new StartEvent();
clone.setValues(this);
return clone;
}
public void setValues(StartEvent otherEvent) {
super.setValues(otherEvent);
setInitiator(otherEvent.getInitiator());
setFormKey(otherEvent.getFormKey());
setSameDeployment(otherEvent.isInterrupting);
setInterrupting(otherEvent.isInterrupting);
setValidateFormFields(otherEvent.validateFormFields);
formProperties = new ArrayList<>();
if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) {
for (FormProperty property : otherEvent.getFormProperties()) {
formProperties.add(property.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\StartEvent.java
| 1
|
请完成以下Java代码
|
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public void setValue(byte[] bytes) {
this.value = bytes;
}
@Override
public InputStream getValue() {
if (value == null) {
return null;
}
return new ByteArrayInputStream(value);
}
@Override
public ValueType getType() {
return type;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setEncoding(Charset encoding) {
this.encoding = encoding.name();
}
@Override
public Charset getEncodingAsCharset() {
if (encoding == null) {
return null;
}
return Charset.forName(encoding);
}
@Override
public String getEncoding() {
|
return encoding;
}
/**
* Get the byte array directly without wrapping it inside a stream to evade
* not needed wrapping. This method is intended for the internal API, which
* needs the byte array anyways.
*/
public byte[] getByteArray() {
return value;
}
@Override
public String toString() {
return "FileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", isTransient=" + isTransient + "]";
}
@Override
public boolean isTransient() {
return isTransient;
}
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\FileValueImpl.java
| 1
|
请完成以下Java代码
|
public TaxRecordPeriod1Code getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link TaxRecordPeriod1Code }
*
*/
public void setTp(TaxRecordPeriod1Code value) {
this.tp = value;
}
/**
* Gets the value of the frToDt property.
*
* @return
* possible object is
* {@link DatePeriodDetails }
*
*/
public DatePeriodDetails getFrToDt() {
|
return frToDt;
}
/**
* Sets the value of the frToDt property.
*
* @param value
* allowed object is
* {@link DatePeriodDetails }
*
*/
public void setFrToDt(DatePeriodDetails value) {
this.frToDt = 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_02\TaxPeriod1.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public boolean isDeleted() {
return deleted;
}
public boolean isNotDeleted() {
return notDeleted;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isWithException() {
return withJobException;
|
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public class PartySEPA2 {
@XmlElement(name = "PrvtId", required = true)
protected PersonIdentificationSEPA2 prvtId;
/**
* Gets the value of the prvtId property.
*
* @return
* possible object is
* {@link PersonIdentificationSEPA2 }
*
*/
public PersonIdentificationSEPA2 getPrvtId() {
return prvtId;
|
}
/**
* Sets the value of the prvtId property.
*
* @param value
* allowed object is
* {@link PersonIdentificationSEPA2 }
*
*/
public void setPrvtId(PersonIdentificationSEPA2 value) {
this.prvtId = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PartySEPA2.java
| 1
|
请完成以下Java代码
|
public void setDataEntry_Section_ID (final int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, DataEntry_Section_ID);
}
@Override
public int getDataEntry_Section_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_Section_ID);
}
@Override
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab()
{
return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class);
}
@Override
public void setDataEntry_SubTab(final de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab)
{
set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab);
}
@Override
public void setDataEntry_SubTab_ID (final int DataEntry_SubTab_ID)
{
if (DataEntry_SubTab_ID < 1)
set_Value (COLUMNNAME_DataEntry_SubTab_ID, null);
else
set_Value (COLUMNNAME_DataEntry_SubTab_ID, DataEntry_SubTab_ID);
}
@Override
public int getDataEntry_SubTab_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_SubTab_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsInitiallyClosed (final boolean IsInitiallyClosed)
{
set_Value (COLUMNNAME_IsInitiallyClosed, IsInitiallyClosed);
|
}
@Override
public boolean isInitiallyClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitiallyClosed);
}
@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 setSectionName (final java.lang.String SectionName)
{
set_Value (COLUMNNAME_SectionName, SectionName);
}
@Override
public java.lang.String getSectionName()
{
return get_ValueAsString(COLUMNNAME_SectionName);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Section.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "oneEvent.event")
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public void setResource(String resource) {
this.resource = resource;
}
|
@ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneEvent.event", value = "Contains the actual deployed event definition JSON.")
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is an event definition for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\EventDefinitionResponse.java
| 2
|
请完成以下Java代码
|
public int getParameterCount()
{
return 2;
}
@Override
public String getLabel(int index)
{
if (index == 0)
return Msg.translate(Env.getCtx(), "NearCity");
else if (index == 1)
return Msg.translate(Env.getCtx(), "RadiusKM");
else
return null;
}
@Override
public Object getParameterToComponent(int index)
|
{
return null;
}
@Override
public Object getParameterValue(int index, boolean returnValueTo)
{
return null;
}
public IInfoSimple getParent()
{
return parent;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPRadiusAbstract.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BookController {
@Autowired
private BookRepository repository;
// Find
@GetMapping("/books")
List<Book> findAll() {
return repository.findAll();
}
// Save
@PostMapping("/books")
//return 201 instead of 200
@ResponseStatus(HttpStatus.CREATED)
Book newBook(@RequestBody Book newBook) {
return repository.save(newBook);
}
// Find
@GetMapping("/books/{id}")
Book findOne(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
}
// Save or update
@PutMapping("/books/{id}")
Book saveOrUpdate(@RequestBody Book newBook, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
x.setName(newBook.getName());
x.setAuthor(newBook.getAuthor());
x.setPrice(newBook.getPrice());
return repository.save(x);
})
.orElseGet(() -> {
newBook.setId(id);
return repository.save(newBook);
});
}
// update author only
@PatchMapping("/books/{id}")
Book patch(@RequestBody Map<String, String> update, @PathVariable Long id) {
|
return repository.findById(id)
.map(x -> {
String author = update.get("author");
if (!StringUtils.isEmpty(author)) {
x.setAuthor(author);
// better create a custom method to update a value = :newValue where id = :id
return repository.save(x);
} else {
throw new BookUnSupportedFieldPatchException(update.keySet());
}
})
.orElseGet(() -> {
throw new BookNotFoundException(id);
});
}
@DeleteMapping("/books/{id}")
void deleteBook(@PathVariable Long id) {
repository.deleteById(id);
}
}
|
repos\spring-boot-master\spring-rest-hello-world\src\main\java\com\mkyong\BookController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringAsyncExecutor extends DefaultAsyncJobExecutor {
protected SpringRejectedJobsHandler rejectedJobsHandler;
public SpringAsyncExecutor() {
super();
}
public SpringAsyncExecutor(AsyncJobExecutorConfiguration configuration) {
super(configuration);
}
public SpringRejectedJobsHandler getRejectedJobsHandler() {
return rejectedJobsHandler;
}
/**
* {@link SpringRejectedJobsHandler} implementation that will be used when jobs were rejected by the task executor.
*
* @param rejectedJobsHandler
*/
public void setRejectedJobsHandler(SpringRejectedJobsHandler rejectedJobsHandler) {
this.rejectedJobsHandler = rejectedJobsHandler;
}
@Override
public boolean executeAsyncJob(JobInfo job) {
|
try {
taskExecutor.execute(createRunnableForJob(job));
return true;
} catch (RejectedExecutionException e) {
sendRejectedEvent(job);
if (rejectedJobsHandler == null) {
unacquireJobAfterRejection(job);
} else {
rejectedJobsHandler.jobRejected(this, job);
}
return false;
}
}
@Override
protected void initAsyncJobExecutionThreadPool() {
// Do nothing, using the Spring taskExecutor
}
}
|
repos\flowable-engine-main\modules\flowable-job-spring-service\src\main\java\org\flowable\spring\job\service\SpringAsyncExecutor.java
| 2
|
请完成以下Java代码
|
private static Charset getCharset(final @NonNull ContentCachingResponseWrapper responseWrapper)
{
final String charset = StringUtils.trimBlankToNull(responseWrapper.getCharacterEncoding());
return charset != null ? Charset.forName(charset) : StandardCharsets.UTF_8;
}
@Nullable
private Object getBody(@NonNull final ContentCachingResponseWrapper responseWrapper)
{
if (responseWrapper.getContentSize() <= 0)
{
return null;
}
final MediaType contentType = getContentType(responseWrapper);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return new String(responseWrapper.getContentAsByteArray());
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(responseWrapper.getContentAsByteArray(), Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return responseWrapper.getContentAsByteArray();
}
}
@Nullable
private Object getBody(@Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate)
{
|
if (bodyCandidate == null)
{
return null;
}
final MediaType contentType = getContentType(httpHeaders);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return bodyCandidate;
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(bodyCandidate, Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return bodyCandidate;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponseMapper.java
| 1
|
请完成以下Java代码
|
public void setAD_Language (String AD_Language)
{
set_Value (COLUMNNAME_AD_Language, AD_Language);
}
/** Get Language.
@return Language for this entity
*/
public String getAD_Language ()
{
return (String)get_Value(COLUMNNAME_AD_Language);
}
/** Set Validation code.
@param Code
Validation Code
*/
public void setCode (String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
|
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Error.java
| 1
|
请完成以下Java代码
|
public List<OLCandValidationResult> clearOLCandidates(
@NonNull final List<I_C_OLCand> olCandList,
@Nullable final AsyncBatchId asyncBatchId)
{
final List<OLCandValidationResult> olCandValidationResults = validateOLCandRecords(olCandList);
final boolean allFine = olCandValidationResults.stream().allMatch(OLCandValidationResult::isOk);
if (!allFine)
{
//don't update anything
return olCandValidationResults;
}
final ICompositeQueryUpdater<org.adempiere.process.rpl.model.I_C_OLCand> updater = queryBL.createCompositeQueryUpdater(org.adempiere.process.rpl.model.I_C_OLCand.class);
if (asyncBatchId != null)
{
updater.addSetColumnValue(I_C_OLCand.COLUMNNAME_C_Async_Batch_ID, asyncBatchId.getRepoId());
}
final Set<Integer> olCandIdsToUpdate = olCandList.stream()
.map(I_C_OLCand::getC_OLCand_ID)
.collect(Collectors.toSet());
queryBL.createQueryBuilder(org.adempiere.process.rpl.model.I_C_OLCand.class)
.addInArrayFilter(org.adempiere.process.rpl.model.I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIdsToUpdate)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false)
.create()
.update(updater);
return olCandValidationResults;
}
@NonNull
public ImmutableList<OLCand> validateOLCands(@NonNull final List<OLCand> olCandList)
{
setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
final OLCandFactory olCandFactory = new OLCandFactory();
final ImmutableList.Builder<OLCand> validatedOlCands = ImmutableList.builder();
try
{
for (final OLCand cand : olCandList)
{
final I_C_OLCand olCandRecord = cand.unbox();
|
validate(olCandRecord);
InterfaceWrapperHelper.save(olCandRecord); // will only access the DB is there are changes in cand
validatedOlCands.add(olCandFactory.toOLCand(olCandRecord));
}
return validatedOlCands.build();
}
finally
{
setValidationProcessInProgress(false);
}
}
@NonNull
private List<OLCandValidationResult> validateOLCandRecords(@NonNull final List<I_C_OLCand> olCandList)
{
setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
final ImmutableList.Builder<OLCandValidationResult> olCandValidationResultBuilder = ImmutableList.builder();
try
{
for (final I_C_OLCand cand : olCandList)
{
validate(cand);
InterfaceWrapperHelper.save(cand); // will only access the DB is there are changes in cand
olCandValidationResultBuilder.add(cand.isError()
? OLCandValidationResult.error(OLCandId.ofRepoId(cand.getC_OLCand_ID()))
: OLCandValidationResult.ok(OLCandId.ofRepoId(cand.getC_OLCand_ID())));
}
return olCandValidationResultBuilder.build();
}
finally
{
setValidationProcessInProgress(false);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandValidatorService.java
| 1
|
请完成以下Java代码
|
public class VerfuegbarkeitsanfrageBulkAntwort {
@XmlElement(name = "Pzn", type = Long.class)
protected List<Long> pzn;
@XmlAttribute(name = "Id", required = true)
protected String id;
/**
* Gets the value of the pzn 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 pzn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPzn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Long }
*
*
*/
public List<Long> getPzn() {
if (pzn == null) {
pzn = new ArrayList<Long>();
}
return this.pzn;
}
|
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsanfrageBulkAntwort.java
| 1
|
请完成以下Java代码
|
public class ReferenceList {
@XmlElementRefs({
@XmlElementRef(name = "DataReference", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false),
@XmlElementRef(name = "KeyReference", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false)
})
protected List<JAXBElement<ReferenceType>> dataReferenceOrKeyReference;
/**
* Gets the value of the dataReferenceOrKeyReference 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 dataReferenceOrKeyReference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDataReferenceOrKeyReference().add(newItem);
* </pre>
*
|
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
* {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
*
*
*/
public List<JAXBElement<ReferenceType>> getDataReferenceOrKeyReference() {
if (dataReferenceOrKeyReference == null) {
dataReferenceOrKeyReference = new ArrayList<JAXBElement<ReferenceType>>();
}
return this.dataReferenceOrKeyReference;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ReferenceList.java
| 1
|
请完成以下Java代码
|
public static boolean isCompensationThrowing(PvmExecutionImpl execution) {
ActivityImpl currentActivity = execution.getActivity();
if (currentActivity != null) {
Boolean isCompensationThrowing = (Boolean) currentActivity.getProperty(BpmnParse.PROPERTYNAME_THROWS_COMPENSATION);
if (isCompensationThrowing != null && isCompensationThrowing) {
return true;
}
}
return false;
}
/**
* Determines whether an execution is responsible for default compensation handling.
*
* This is the case if
* <ul>
* <li>the execution has an activity
* <li>the execution is a scope
* <li>the activity is a scope
* <li>the execution has children
* <li>the execution does not throw compensation
* </ul>
*/
public static boolean executesDefaultCompensationHandler(PvmExecutionImpl scopeExecution) {
ActivityImpl currentActivity = scopeExecution.getActivity();
|
if (currentActivity != null) {
return scopeExecution.isScope()
&& currentActivity.isScope()
&& !scopeExecution.getNonEventScopeExecutions().isEmpty()
&& !isCompensationThrowing(scopeExecution);
}
else {
return false;
}
}
public static String getParentActivityInstanceId(PvmExecutionImpl execution) {
Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping = execution.createActivityExecutionMapping();
PvmExecutionImpl parentScopeExecution = activityExecutionMapping.get(execution.getActivity().getFlowScope());
return parentScopeExecution.getParentActivityInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\CompensationBehavior.java
| 1
|
请完成以下Java代码
|
public class SchemaOperationsEngineDropDbCmd implements Command<Void> {
protected final String engineScopeType;
public SchemaOperationsEngineDropDbCmd(String engineScopeType) {
this.engineScopeType = engineScopeType;
}
@Override
public Void execute(CommandContext commandContext) {
AbstractEngineConfiguration engineConfiguration = commandContext.getEngineConfigurations()
.get(engineScopeType);
if (engineConfiguration == null) {
throw new FlowableIllegalArgumentException("There is no engine configuration for scope " + engineScopeType);
}
List<SchemaManager> schemaManagers = new ArrayList<>();
schemaManagers.add(engineConfiguration.getCommonSchemaManager());
schemaManagers.add(engineConfiguration.getSchemaManager());
Map<String, SchemaManager> additionalSchemaManagers = engineConfiguration.getAdditionalSchemaManagers();
if (additionalSchemaManagers != null) {
schemaManagers.addAll(additionalSchemaManagers.values());
|
}
// The drop is executed in the reverse order
ListIterator<SchemaManager> listIterator = schemaManagers.listIterator(schemaManagers.size());
while (listIterator.hasPrevious()) {
SchemaManager schemaManager = listIterator.previous();
try {
schemaManager.schemaDrop();
} catch (RuntimeException e) {
// ignore
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\SchemaOperationsEngineDropDbCmd.java
| 1
|
请完成以下Java代码
|
public void addInput(HistoricDecisionInputInstance decisionInputInstance) {
if(inputs == null) {
inputs = new ArrayList<HistoricDecisionInputInstance>();
}
inputs.add(decisionInputInstance);
}
public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) {
if(outputs == null) {
outputs = new ArrayList<HistoricDecisionOutputInstance>();
}
outputs.add(decisionOutputInstance);
}
public Double getCollectResultValue() {
return collectResultValue;
}
public void setCollectResultValue(Double collectResultValue) {
this.collectResultValue = collectResultValue;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
|
public void setRootDecisionInstanceId(String rootDecisionInstanceId) {
this.rootDecisionInstanceId = rootDecisionInstanceId;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
// getEntitiesByKey() will be removed and probably replaced with #iterateEntities()
Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey();
entitiesByKey.forEach((key, value) -> System.out.println(key + ": " + value));
for (Object entry : entitiesByKey.values()) {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
|
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
};
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public boolean hasChildElements() {
return false;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
CmmnModel model = conversionHelper.getCmmnModel();
model.setId(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_ID));
model.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
model.setExpressionLanguage(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPRESSION_LANGUAGE));
model.setExporter(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER));
model.setExporterVersion(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER_VERSION));
model.setAuthor(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_AUTHOR));
model.setTargetNamespace(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TARGET_NAMESPACE));
String creationDateString = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_CREATION_DATE);
if (StringUtils.isNotEmpty(creationDateString)) {
try {
Date creationDate = new SimpleDateFormat(XSD_DATETIME_FORMAT).parse(creationDateString);
model.setCreationDate(creationDate);
} catch (ParseException e) {
LOGGER.warn("Ignoring creationDate attribute: invalid date format", e);
}
}
for (int i = 0; i < xtr.getNamespaceCount(); i++) {
String prefix = xtr.getNamespacePrefix(i);
if (StringUtils.isNotEmpty(prefix)) {
model.addNamespace(prefix, xtr.getNamespaceURI(i));
}
}
|
for (int i = 0; i < xtr.getAttributeCount(); i++) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute();
extensionAttribute.setName(xtr.getAttributeLocalName(i));
extensionAttribute.setValue(xtr.getAttributeValue(i));
String namespace = xtr.getAttributeNamespace(i);
if (model.getNamespaces().containsValue(namespace)) {
if (StringUtils.isNotEmpty(namespace)) {
extensionAttribute.setNamespace(namespace);
}
if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
}
model.addDefinitionsAttribute(extensionAttribute);
}
}
return null;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\DefinitionsXmlConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public T save(T entity) {
if (entity.getId() == null) {
entity.setId(nextId());
}
T processedEntity = preProcess(entity);
if (processedEntity != null) {
allRules.put(processedEntity.getId(), processedEntity);
machineRules.computeIfAbsent(MachineInfo.of(processedEntity.getApp(), processedEntity.getIp(),
processedEntity.getPort()), e -> new ConcurrentHashMap<>(32))
.put(processedEntity.getId(), processedEntity);
appRules.computeIfAbsent(processedEntity.getApp(), v -> new ConcurrentHashMap<>(32))
.put(processedEntity.getId(), processedEntity);
}
return processedEntity;
}
@Override
public List<T> saveAll(List<T> rules) {
// TODO: check here.
allRules.clear();
machineRules.clear();
appRules.clear();
if (rules == null) {
return null;
}
List<T> savedRules = new ArrayList<>(rules.size());
for (T rule : rules) {
savedRules.add(save(rule));
}
return savedRules;
}
@Override
public T delete(Long id) {
T entity = allRules.remove(id);
if (entity != null) {
if (appRules.get(entity.getApp()) != null) {
appRules.get(entity.getApp()).remove(id);
}
machineRules.get(MachineInfo.of(entity.getApp(), entity.getIp(), entity.getPort())).remove(id);
}
return entity;
|
}
@Override
public T findById(Long id) {
return allRules.get(id);
}
@Override
public List<T> findAllByMachine(MachineInfo machineInfo) {
Map<Long, T> entities = machineRules.get(machineInfo);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
}
@Override
public List<T> findAllByApp(String appName) {
AssertUtil.notEmpty(appName, "appName cannot be empty");
Map<Long, T> entities = appRules.get(appName);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
}
public void clearAll() {
allRules.clear();
machineRules.clear();
appRules.clear();
}
protected T preProcess(T entity) {
return entity;
}
/**
* Get next unused id.
*
* @return next unused id
*/
abstract protected long nextId();
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\repository\rule\InMemoryRuleRepositoryAdapter.java
| 2
|
请完成以下Java代码
|
public static boolean isProcessApplication(DeploymentUnit deploymentUnit) {
return deploymentUnit.hasAttachment(MARKER);
}
/**
* Returns the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PA_COMPONENT);
}
/**
* Attach the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static void attachProcessApplicationComponent(DeploymentUnit deploymentUnit, ComponentDescription componentDescription){
deploymentUnit.putAttachment(PA_COMPONENT, componentDescription);
}
/**
* Attach the {@link AnnotationInstance}s for the PostDeploy methods
*/
public static void attachPostDeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(POST_DEPLOY_METHOD, annotation);
}
/**
* Attach the {@link AnnotationInstance}s for the PreUndeploy methods
*/
public static void attachPreUndeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(PRE_UNDEPLOY_METHOD, annotation);
|
}
/**
* @return the description of the PostDeploy method
*/
public static AnnotationInstance getPostDeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(POST_DEPLOY_METHOD);
}
/**
* @return the description of the PreUndeploy method
*/
public static AnnotationInstance getPreUndeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PRE_UNDEPLOY_METHOD);
}
private ProcessApplicationAttachments() {
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\marker\ProcessApplicationAttachments.java
| 1
|
请完成以下Java代码
|
public Stream<WebuiDocumentReference> evaluateAndStream(@NonNull final RelatedDocumentsEvaluationContext context)
{
return relatedDocumentsCandidateGroup.evaluateAndStream(context)
.map(relatedDocuments -> toDocumentReference(relatedDocuments, filterCaption));
}
public static WebuiDocumentReference toDocumentReference(
@NonNull final RelatedDocuments relatedDocuments,
@NonNull final ITranslatableString filterCaption)
{
return WebuiDocumentReference.builder()
.id(WebuiDocumentReferenceId.ofRelatedDocumentsId(relatedDocuments.getId()))
.internalName(relatedDocuments.getInternalName())
.caption(relatedDocuments.getCaption())
.targetWindow(toDocumentReferenceTargetWindow(relatedDocuments.getTargetWindow()))
.priority(relatedDocuments.getPriority())
|
.documentsCount(relatedDocuments.getRecordCount())
.filter(MQueryDocumentFilterHelper.createDocumentFilterFromMQuery(relatedDocuments.getQuery(), filterCaption))
.loadDuration(relatedDocuments.getRecordCountDuration())
.build();
}
private static WebuiDocumentReferenceTargetWindow toDocumentReferenceTargetWindow(@NonNull final RelatedDocumentsTargetWindow relatedDocumentsTargetWindow)
{
final WindowId windowId = WindowId.of(relatedDocumentsTargetWindow.getAdWindowId());
final String category = relatedDocumentsTargetWindow.getCategory();
return category != null
? WebuiDocumentReferenceTargetWindow.ofWindowIdAndCategory(windowId, category)
: WebuiDocumentReferenceTargetWindow.ofWindowId(windowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\WebuiDocumentReferenceCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static class ContributorConfigDataLocationResolverContext implements ConfigDataLocationResolverContext {
private final ConfigDataEnvironmentContributors contributors;
private final ConfigDataEnvironmentContributor contributor;
private final @Nullable ConfigDataActivationContext activationContext;
private volatile @Nullable Binder binder;
ContributorConfigDataLocationResolverContext(ConfigDataEnvironmentContributors contributors,
ConfigDataEnvironmentContributor contributor, @Nullable ConfigDataActivationContext activationContext) {
this.contributors = contributors;
this.contributor = contributor;
this.activationContext = activationContext;
}
@Override
public Binder getBinder() {
Binder binder = this.binder;
if (binder == null) {
binder = this.contributors.getBinder(this.activationContext);
this.binder = binder;
}
return binder;
}
@Override
public @Nullable ConfigDataResource getParent() {
return this.contributor.getResource();
}
@Override
public ConfigurableBootstrapContext getBootstrapContext() {
return this.contributors.getBootstrapContext();
}
}
private class InactiveSourceChecker implements BindHandler {
|
private final @Nullable ConfigDataActivationContext activationContext;
InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) {
this.activationContext = activationContext;
}
@Override
public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Object result) {
for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) {
if (!contributor.isActive(this.activationContext)) {
InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name);
}
}
return result;
}
}
/**
* Binder options that can be used with
* {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}.
*/
enum BinderOption {
/**
* Throw an exception if an inactive contributor contains a bound value.
*/
FAIL_ON_BIND_TO_INACTIVE_SOURCE
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
| 2
|
请完成以下Java代码
|
public Iterable<Tag> repositoryTags(RepositoryMethodInvocation invocation) {
Tags tags = Tags.empty();
tags = and(tags, invocation.getRepositoryInterface(), "repository", this::getSimpleClassName);
tags = and(tags, invocation.getMethod(), "method", Method::getName);
RepositoryMethodInvocationResult result = invocation.getResult();
if (result != null) {
tags = and(tags, result.getState(), "state", State::name);
tags = and(tags, result.getError(), "exception", this::getExceptionName, EXCEPTION_NONE);
}
return tags;
}
private <T> Tags and(Tags tags, @Nullable T instance, String key, Function<T, String> value) {
return and(tags, instance, key, value, null);
}
private <T> Tags and(Tags tags, @Nullable T instance, String key, Function<T, String> value,
@Nullable Tag fallback) {
if (instance != null) {
|
return tags.and(key, value.apply(instance));
}
return (fallback != null) ? tags.and(fallback) : tags;
}
private String getExceptionName(Throwable error) {
return getSimpleClassName(error.getClass());
}
private String getSimpleClassName(Class<?> type) {
String simpleName = type.getSimpleName();
return (!StringUtils.hasText(simpleName)) ? type.getName() : simpleName;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\DefaultRepositoryTagsProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Response say(Message message) throws Exception {
Thread.sleep(1000);
return new Response("Welcome, " + message.getName() + "!");
}
//http://localhost:8080/Welcome1
@RequestMapping("/Welcome1")
@ResponseBody
public String say2()throws Exception
{
ws.sendMessage();
return "is ok";
}
@MessageMapping("/chat")
//在springmvc 中可以直接获得principal,principal 中包含当前用户的信息
public void handleChat(Principal principal, Message message) {
/**
* 此处是一段硬编码。如果发送人是wyf 则发送给 wisely 如果发送人是wisely 就发送给 wyf。
* 通过当前用户,然后查找消息,如果查找到未读消息,则发送给当前用户。
|
*/
if (principal.getName().equals("admin")) {
//通过convertAndSendToUser 向用户发送信息,
// 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身
messagingTemplate.convertAndSendToUser("abel",
"/queue/notifications", principal.getName() + "-send:"
+ message.getName());
/**
* 72 行操作相等于
* messagingTemplate.convertAndSend("/user/abel/queue/notifications",principal.getName() + "-send:"
+ message.getName());
*/
} else {
messagingTemplate.convertAndSendToUser("admin",
"/queue/notifications", principal.getName() + "-send:"
+ message.getName());
}
}
}
|
repos\springBoot-master\springWebSocket\src\main\java\com\us\example\controller\WebSocketController.java
| 2
|
请完成以下Java代码
|
private String createIssue(String projectKey, Long issueType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
private Issue getIssue(String issueKey) {
return restClient.getIssueClient().getIssue(issueKey).claim();
}
private void voteForAnIssue(Issue issue) {
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
}
private int getTotalVotesCount(String issueKey) {
BasicVotes votes = getIssue(issueKey).getVotes();
return votes == null ? 0 : votes.getVotes();
}
private void addComment(Issue issue, String commentBody) {
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
}
|
private List<Comment> getAllComments(String issueKey) {
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
.collect(Collectors.toList());
}
private void updateIssueDescription(String issueKey, String newDescription) {
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
restClient.getIssueClient().updateIssue(issueKey, input).claim();
}
private void deleteIssue(String issueKey, boolean deleteSubtasks) {
restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim();
}
private JiraRestClient getJiraRestClient() {
return new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password);
}
private URI getJiraUri() {
return URI.create(this.jiraUrl);
}
}
|
repos\tutorials-master\saas-modules\jira-rest-integration\src\main\java\com\baeldung\saas\jira\MyJiraClient.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<I_C_BPartner> retrieveVendors(@NonNull final QueryLimit limit)
{
return queryBL.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMNNAME_IsVendor, true)
.addOnlyActiveRecordsFilter()
.orderBy(I_C_BPartner.COLUMNNAME_Name)
.orderBy(I_C_BPartner.COLUMNNAME_C_BPartner_ID)
.setLimit(limit)
.create()
.listImmutable(I_C_BPartner.class);
}
@Override
public Optional<SalesRegionId> getSalesRegionIdByBPLocationId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpLocation = getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
return bpLocation != null ? SalesRegionId.optionalOfRepoId(bpLocation.getC_SalesRegion_ID()) : Optional.empty();
}
|
@Override
@NonNull
public List<String> getOtherLocationNamesOfBPartner(@NonNull final BPartnerId bPartnerId, @Nullable final BPartnerLocationId bPartnerLocationId)
{
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, bPartnerLocationId)
.create()
.listDistinct(I_C_BPartner_Location.COLUMNNAME_Name, String.class);
}
@Override
public Optional<ShipperId> getShipperIdByBPLocationId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpLocation = getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
return bpLocation != null ? ShipperId.optionalOfRepoId(bpLocation.getM_Shipper_ID()) : Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerDAO.java
| 2
|
请完成以下Java代码
|
public void onCreate(@Nullable Connection connection) {
this.delegates.forEach(delegate -> delegate.onCreate(connection));
}
@Override
public void onClose(Connection connection) {
this.delegates.forEach(delegate -> delegate.onClose(connection));
}
@Override
public void onShutDown(ShutdownSignalException signal) {
this.delegates.forEach(delegate -> delegate.onShutDown(signal));
}
@Override
public void onFailed(Exception exception) {
this.delegates.forEach(delegate -> delegate.onFailed(exception));
}
|
public void setDelegates(List<? extends ConnectionListener> delegates) {
this.delegates = new ArrayList<>(delegates);
}
public void addDelegate(ConnectionListener delegate) {
this.delegates.add(delegate);
}
public boolean removeDelegate(ConnectionListener delegate) {
return this.delegates.remove(delegate);
}
public void clearDelegates() {
this.delegates.clear();
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\CompositeConnectionListener.java
| 1
|
请完成以下Java代码
|
private void initTotalRetries(CommandContext commandContext) {
totalRetries = commandContext.getProcessEngineConfiguration().getFailedJobListenerMaxRetries();
}
protected void fireHistoricJobFailedEvt(JobEntity job) {
CommandContext commandContext = Context.getCommandContext();
// the given job failed and a rollback happened,
// that's why we have to increment the job
// sequence counter once again
job.incrementSequenceCounter();
commandContext
.getHistoricJobLogManager()
.fireJobFailedEvent(job, jobFailureCollector.getFailure());
}
protected void logJobFailure(CommandContext commandContext) {
if (commandContext.getProcessEngineConfiguration().isMetricsEnabled()) {
commandContext.getProcessEngineConfiguration()
.getMetricsRegistry()
.markOccurrence(Metrics.JOB_FAILED);
}
}
public void incrementCountRetries() {
this.countRetries++;
}
public int getRetriesLeft() {
return Math.max(0, totalRetries - countRetries);
|
}
protected class FailedJobListenerCmd implements Command<Void> {
protected String jobId;
protected Command<Object> cmd;
public FailedJobListenerCmd(String jobId, Command<Object> cmd) {
this.jobId = jobId;
this.cmd = cmd;
}
@Override
public Void execute(CommandContext commandContext) {
JobEntity job = commandContext
.getJobManager()
.findJobById(jobId);
if (job != null) {
job.setFailedActivityId(jobFailureCollector.getFailedActivityId());
fireHistoricJobFailedEvt(job);
cmd.execute(commandContext);
} else {
LOG.debugFailedJobNotFound(jobId);
}
return null;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\FailedJobListener.java
| 1
|
请完成以下Java代码
|
private WarehouseId getOnly_Warehouse_ID()
{
try
{
final String only_Warehouse = Env.getContext(Env.getCtx(), m_WindowNo, "M_Warehouse_ID", true);
if (only_Warehouse != null && only_Warehouse.length() > 0)
{
return WarehouseId.ofRepoIdOrNull(Integer.parseInt(only_Warehouse));
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
} // getOnly_Warehouse_ID
/**
* Get Product restriction if any.
*
* @return M_Product_ID or 0
*/
private int getOnly_Product_ID()
{
if (!Env.isSOTrx(Env.getCtx(), m_WindowNo))
{
return 0; // No product restrictions for PO
}
//
String only_Product = Env.getContext(Env.getCtx(), m_WindowNo, "M_Product_ID", true);
int only_Product_ID = 0;
try
{
if (only_Product != null && only_Product.length() > 0)
{
only_Product_ID = Integer.parseInt(only_Product);
}
}
catch (Exception ex)
{
}
return only_Product_ID;
} // getOnly_Product_ID
/**
|
* Set the default locator if this field is mandatory
* and we have a warehouse restriction.
*
* @since 3.1.4
*/
private void setDefault_Locator_ID()
{
// teo_sarca, FR [ 1661546 ] Mandatory locator fields should use defaults
if (!isMandatory() || m_mLocator == null)
{
return;
}
final WarehouseId warehouseId = getOnly_Warehouse_ID();
if (warehouseId == null)
{
return;
}
final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId);
if (locatorId == null)
{
return;
}
setValue(locatorId.getRepoId());
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VLocator
/*****************************************************************************/
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocator.java
| 1
|
请完成以下Java代码
|
public final class ErrorMessage
{
public static ErrorMessage of(final String message)
{
final Throwable exception = null;
return new ErrorMessage(message, exception);
}
public static ErrorMessage of(final Throwable exception)
{
String message = AdempiereException.extractMessage(exception);
return new ErrorMessage(message, exception);
}
private final String message;
private final transient Throwable exception;
private ErrorMessage(
final String message,
@Nullable final Throwable exception)
{
this.message = message;
|
this.exception = exception;
}
@Override
@Deprecated
public String toString()
{
return message == null ? "" : message;
}
public String getMessage()
{
return message;
}
public AdempiereException toException()
{
return exception != null
? AdempiereException.wrapIfNeeded(exception)
: new AdempiereException(message);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ErrorMessage.java
| 1
|
请完成以下Java代码
|
public FetchAndLockBuilderImpl orderByCreateTime() {
orderingProperties.add(new QueryOrderingProperty(CREATE_TIME, null));
return this;
}
public FetchAndLockBuilderImpl asc() throws NotValidException {
configureLastOrderingPropertyDirection(ASCENDING);
return this;
}
public FetchAndLockBuilderImpl desc() throws NotValidException {
configureLastOrderingPropertyDirection(DESCENDING);
return this;
}
@Override
public ExternalTaskQueryTopicBuilder subscribe() {
checkQueryOk();
return new ExternalTaskQueryTopicBuilderImpl(commandExecutor, workerId, maxTasks, usePriority, orderingProperties);
}
|
protected void configureLastOrderingPropertyDirection(Direction direction) {
QueryOrderingProperty lastProperty = !orderingProperties.isEmpty() ? getLastElement(orderingProperties) : null;
ensureNotNull(NotValidException.class, "You should call any of the orderBy methods first before specifying a direction", "currentOrderingProperty", lastProperty);
if (lastProperty.getDirection() != null) {
ensureNull(NotValidException.class, "Invalid query: can specify only one direction desc() or asc() for an ordering constraint", "direction", direction);
}
lastProperty.setDirection(direction);
}
protected void checkQueryOk() {
for (QueryOrderingProperty orderingProperty : orderingProperties) {
ensureNotNull(NotValidException.class, "Invalid query: call asc() or desc() after using orderByXX()", "direction", orderingProperty.getDirection());
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\FetchAndLockBuilderImpl.java
| 1
|
请完成以下Java代码
|
public IHUTransactionCandidate getCounterpart()
{
return counterpartTrx;
}
private void setCounterpart(@NonNull final IHUTransactionCandidate counterpartTrx)
{
Check.assume(this != counterpartTrx, "counterpartTrx != this");
if (this.counterpartTrx == null)
{
this.counterpartTrx = counterpartTrx;
}
else if (this.counterpartTrx == counterpartTrx)
{
// do nothing; it was already set
}
else
{
throw new HUException("Posible development error: changing the counterpart transaction is not allowed"
+ "\n Transaction: " + this
+ "\n Counterpart trx (old): " + this.counterpartTrx
+ "\n Counterpart trx (new): " + counterpartTrx);
}
}
@Override
public void pair(final IHUTransactionCandidate counterpartTrx)
|
{
Check.errorUnless(counterpartTrx instanceof HUTransactionCandidate,
"Param counterPartTrx needs to be a HUTransaction counterPartTrx={}",
counterpartTrx);
this.setCounterpart(counterpartTrx);
// by casting to HUTransaction (which currently is the only implementation of IHUTransaction), we don't have to make setCounterpart() public.
((HUTransactionCandidate)counterpartTrx).setCounterpart(this);
}
@Override
public LocatorId getLocatorId()
{
return locatorId;
}
@Override
public void setSkipProcessing()
{
skipProcessing = true;
}
@Override
public String getHUStatus()
{
return huStatus;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTransactionCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addPricingAttributes(final Collection<IPricingAttribute> pricingAttributesToAdd)
{
if (pricingAttributesToAdd == null || pricingAttributesToAdd.isEmpty())
{
return;
}
pricingAttributes.addAll(pricingAttributesToAdd);
}
/**
* Supposed to be called by the pricing engine.
* <p>
* task https://github.com/metasfresh/metasfresh/issues/4376
*/
public void updatePriceScales()
{
priceStd = scaleToPrecision(priceStd);
priceLimit = scaleToPrecision(priceLimit);
priceList = scaleToPrecision(priceList);
}
@Nullable
private BigDecimal scaleToPrecision(@Nullable final BigDecimal priceToRound)
{
if (priceToRound == null || precision == null)
{
|
return priceToRound;
}
return precision.round(priceToRound);
}
@Override
public boolean isCampaignPrice()
{
return campaignPrice;
}
@Override
public IPricingResult setLoggableMessages(@NonNull final ImmutableList<String> loggableMessages)
{
this.loggableMessages = loggableMessages;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingResult.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
}
private boolean isConfiguration(MetadataReader metadataReader) {
return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName());
}
private boolean isAutoConfiguration(MetadataReader metadataReader) {
boolean annotatedWithAutoConfiguration = metadataReader.getAnnotationMetadata()
.isAnnotated(AutoConfiguration.class.getName());
|
return annotatedWithAutoConfiguration
|| getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName());
}
protected List<String> getAutoConfigurations() {
List<String> autoConfigurations = this.autoConfigurations;
if (autoConfigurations == null) {
ImportCandidates importCandidates = ImportCandidates.load(AutoConfiguration.class, this.beanClassLoader);
autoConfigurations = importCandidates.getCandidates();
this.autoConfigurations = autoConfigurations;
}
return autoConfigurations;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationExcludeFilter.java
| 2
|
请完成以下Java代码
|
public Operation getOperation() {
return operationRefChild.getReferenceTargetElement(this);
}
public void setOperation(Operation operation) {
operationRefChild.setReferenceTargetElement(this, operation);
}
/** camunda extensions */
public String getCamundaClass() {
return camundaClassAttribute.getValue(this);
}
public void setCamundaClass(String camundaClass) {
camundaClassAttribute.setValue(this, camundaClass);
}
public String getCamundaDelegateExpression() {
return camundaDelegateExpressionAttribute.getValue(this);
}
public void setCamundaDelegateExpression(String camundaExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
|
public String getCamundaTopic() {
return camundaTopicAttribute.getValue(this);
}
public void setCamundaTopic(String camundaTopic) {
camundaTopicAttribute.setValue(this, camundaTopic);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MessageEventDefinitionImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HUReservation
{
@Getter(AccessLevel.PRIVATE)
@NonNull ImmutableMap<HuId, HUReservationEntry> entriesByVHUId;
@NonNull HUReservationDocRef documentRef;
@Nullable BPartnerId customerId;
@NonNull Quantity reservedQtySum;
private HUReservation(@NonNull final Collection<HUReservationEntry> entries)
{
Check.assumeNotEmpty(entries, "entries is not empty");
this.entriesByVHUId = Maps.uniqueIndex(entries, HUReservationEntry::getVhuId);
this.documentRef = extractSingleDocumentRefOrFail(entries);
customerId = extractSingleCustomerIdOrNull(entries);
reservedQtySum = computeReservedQtySum(entries);
}
public static HUReservation ofEntries(@NonNull final Collection<HUReservationEntry> entries)
{
return new HUReservation(entries);
}
private static HUReservationDocRef extractSingleDocumentRefOrFail(final Collection<HUReservationEntry> entries)
{
//noinspection OptionalGetWithoutIsPresent
return entries
.stream()
.map(HUReservationEntry::getDocumentRef)
.distinct()
.reduce((documentRef1, documentRef2) -> {
throw new AdempiereException("Entries shall be for a single document reference: " + entries);
})
.get();
}
@Nullable
private static BPartnerId extractSingleCustomerIdOrNull(final Collection<HUReservationEntry> entries)
|
{
final ImmutableSet<BPartnerId> customerIds = entries
.stream()
.map(HUReservationEntry::getCustomerId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return customerIds.size() == 1 ? customerIds.iterator().next() : null;
}
private static Quantity computeReservedQtySum(final Collection<HUReservationEntry> entries)
{
//noinspection OptionalGetWithoutIsPresent
return entries
.stream()
.map(HUReservationEntry::getQtyReserved)
.reduce(Quantity::add)
.get();
}
public ImmutableSet<HuId> getVhuIds()
{
return entriesByVHUId.keySet();
}
public Quantity getReservedQtyByVhuId(@NonNull final HuId vhuId)
{
final HUReservationEntry entry = entriesByVHUId.get(vhuId);
if (entry == null)
{
throw new AdempiereException("@NotFound@ @VHU_ID@");
}
return entry.getQtyReserved();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservation.java
| 2
|
请完成以下Spring Boot application配置
|
grpc:
client:
hello:
address: localhost:9090
negotiation-type: plaintext
logging:
pattern:
console: "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5level [%t] [%logger - %line]: %m%n"
|
level:
com.baeldung.helloworld.consumer: info
include-application-name: false
|
repos\tutorials-master\spring-boot-modules\spring-boot-3-grpc\helloworld-grpc-consumer\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public I_I_Request retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
final PO po = TableModelLoader.instance.getPO(ctx, I_I_Request.Table_Name, rs, ITrx.TRXNAME_ThreadInherited);
return InterfaceWrapperHelper.create(po, I_I_Request.class);
}
/*
* @param isInsertOnly ignored. This import is only for updates.
*/
@Override
protected ImportRecordResult importRecord(
final @NonNull IMutable<Object> state_NOTUSED,
final @NonNull I_I_Request importRecord,
final boolean isInsertOnly_NOTUSED)
{
//
// Create a new request
final I_R_Request request = InterfaceWrapperHelper.newInstance(I_R_Request.class, importRecord);
request.setAD_Org_ID(importRecord.getAD_Org_ID());
//
// BPartner
{
int bpartnerId = importRecord.getC_BPartner_ID();
if (bpartnerId <= 0)
{
throw new AdempiereException("BPartner not found");
}
request.setC_BPartner_ID(bpartnerId);
}
//
// request type
{
int requesTypeId = importRecord.getR_RequestType_ID();
if (requesTypeId <= 0)
{
throw new AdempiereException("Request Type not found");
}
request.setR_RequestType_ID(requesTypeId);
}
//
// status
|
{
int statusId = importRecord.getR_Status_ID();
if (statusId <= 0)
{
throw new AdempiereException("Status not found");
}
request.setR_Status_ID(statusId);
}
//
// set data from the other fields
request.setDateTrx(importRecord.getDateTrx());
request.setDateNextAction(importRecord.getDateNextAction());
request.setSummary(importRecord.getSummary());
request.setDocumentNo(importRecord.getDocumentNo());
int userid = Env.getAD_User_ID(getCtx());
request.setSalesRep_ID(userid);
//
InterfaceWrapperHelper.save(request);
//
// Link back the request to current import record
importRecord.setR_Request(request);
//
return ImportRecordResult.Inserted;
}
@Override
protected void markImported(final I_I_Request importRecord)
{
importRecord.setI_IsImported(X_I_Request.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\request\impexp\RequestImportProcess.java
| 1
|
请完成以下Java代码
|
public Set<OrderId> retrieveAllContractOrderList(@NonNull final OrderId orderId)
{
final Set<OrderId> orderIds = new HashSet<>();
final OrderId ancestorId = retrieveOriginalContractOrder(orderId);
orderIds.add(ancestorId);
buildAllContractOrderList(ancestorId, orderIds);
return orderIds;
}
/**
* <ul>
* * retrieves original order through column <code>I_C_Order.COLUMNNAME_Ref_FollowupOrder_ID</code>,
* going recursively until the original one
* </ul>
* <ul>
* * if the order given as parameter does not have any ancestor, will be that returned
* </ul>
*/
public OrderId retrieveOriginalContractOrder(@NonNull final OrderId orderId)
{
OrderId ancestor = retrieveLinkedFollowUpContractOrder(orderId);
if (ancestor != null)
{
final OrderId nextAncestor = retrieveOriginalContractOrder(ancestor);
if (nextAncestor != null)
{
ancestor = nextAncestor;
}
}
return orderId;
}
/**
* Builds up a list of contract orders based on column <code>I_C_Order.COLUMNNAME_Ref_FollowupOrder_ID</code>.
*/
private void buildAllContractOrderList(@NonNull final OrderId orderId, @NonNull final Set<OrderId> contractOrderIds)
{
final I_C_Order order = InterfaceWrapperHelper.load(orderId, I_C_Order.class);
final OrderId nextAncestorId = OrderId.ofRepoIdOrNull(order.getRef_FollowupOrder_ID());
if (nextAncestorId != null)
{
contractOrderIds.add(nextAncestorId);
buildAllContractOrderList(nextAncestorId, contractOrderIds);
}
}
public I_C_Flatrate_Term retrieveTopExtendedTerm(@NonNull final I_C_Flatrate_Term term)
{
I_C_Flatrate_Term nextTerm = term.getC_FlatrateTerm_Next();
if (nextTerm != null)
{
nextTerm = retrieveTopExtendedTerm(nextTerm);
}
return nextTerm == null ? term : nextTerm;
|
}
@Nullable
public OrderId getContractOrderId(@NonNull final I_C_Flatrate_Term term)
{
if (term.getC_OrderLine_Term_ID() <= 0)
{
return null;
}
final IOrderDAO orderRepo = Services.get(IOrderDAO.class);
final de.metas.interfaces.I_C_OrderLine ol = orderRepo.getOrderLineById(term.getC_OrderLine_Term_ID());
if (ol == null)
{
return null;
}
return OrderId.ofRepoId(ol.getC_Order_ID());
}
public boolean isContractSalesOrder(@NonNull final OrderId orderId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId)
.addNotNull(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID)
.create()
.anyMatch();
}
public void save(@NonNull final I_C_Order order)
{
InterfaceWrapperHelper.save(order);
}
public void setOrderContractStatusAndSave(@NonNull final I_C_Order order, @NonNull final String contractStatus)
{
order.setContractStatus(contractStatus);
save(order);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\ContractOrderService.java
| 1
|
请完成以下Java代码
|
protected String processBusinessKey(MethodInvocation invocation) throws Throwable {
Map<BusinessKey, String> businessKeyAnnotations = this.mapOfAnnotationValues( BusinessKey.class ,invocation);
if (businessKeyAnnotations.size() == 1) {
BusinessKey processId = businessKeyAnnotations.keySet().iterator().next();
return businessKeyAnnotations.get(processId);
}
return null;
}
@SuppressWarnings("unchecked")
private <K extends Annotation, V> Map<K, V> mapOfAnnotationValues(Class<K> annotationType, MethodInvocation invocation) {
Method method = invocation.getMethod();
Annotation[][] annotations = method.getParameterAnnotations();
Map<K, V> vars = new HashMap<K, V>();
int paramIndx = 0;
for (Annotation[] annPerParam : annotations) {
for (Annotation annotation : annPerParam) {
if (!annotationType.isAssignableFrom(annotation.getClass())) {
continue;
}
K pv = (K) annotation;
V v = (V) invocation.getArguments()[paramIndx];
vars.put(pv, v);
}
paramIndx += 1;
}
|
return vars;
}
/**
* if there any arguments with the {@link org.camunda.bpm.engine.annotations.ProcessVariable} annotation,
* then we feed those parameters into the business process
*
* @param invocation the invocation of the method as passed to the {@link org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)} method
* @return returns the map of process variables extracted from the parameters
* @throws Throwable thrown anything goes wrong
*/
protected Map<String, Object> processVariablesFromAnnotations(MethodInvocation invocation) throws Throwable {
Map<ProcessVariable, Object> vars = this.mapOfAnnotationValues(ProcessVariable.class, invocation);
Map<String, Object> varNameToValueMap = new HashMap<String, Object>();
for (ProcessVariable processVariable : vars.keySet()) {
varNameToValueMap.put(processVariable.value(), vars.get(processVariable));
}
return varNameToValueMap;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ProcessStartingMethodInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setNextImportStartingTimestamp(@NonNull final DateAndImportStatus dateAndImportStatus)
{
if (this.nextImportStartingTimestamp == null)
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return;
}
if (this.nextImportStartingTimestamp.isOkToImport())
{
if (dateAndImportStatus.isOkToImport()
&& dateAndImportStatus.getTimestamp().isAfter(this.nextImportStartingTimestamp.getTimestamp()))
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return;
}
if (!dateAndImportStatus.isOkToImport())
|
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return;
}
}
if (!this.nextImportStartingTimestamp.isOkToImport()
&& !dateAndImportStatus.isOkToImport()
&& dateAndImportStatus.getTimestamp().isBefore(this.nextImportStartingTimestamp.getTimestamp()))
{
this.nextImportStartingTimestamp = dateAndImportStatus;
}
}
}
|
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\EbayImportOrdersRouteContext.java
| 2
|
请完成以下Java代码
|
public Optional<BPartnerId> getBpartnerId()
{
return rowsData.getBpartnerId();
}
public SOTrx getSoTrx()
{
return rowsData.getSoTrx();
}
public CurrencyId getCurrencyId()
{
return rowsData.getCurrencyId();
}
public Set<ProductId> getProductIds()
{
return rowsData.getProductIds();
}
public Optional<PriceListVersionId> getSinglePriceListVersionId()
{
return rowsData.getSinglePriceListVersionId();
}
public Optional<PriceListVersionId> getBasePriceListVersionId()
{
return rowsData.getBasePriceListVersionId();
}
public PriceListVersionId getBasePriceListVersionIdOrFail()
{
return rowsData.getBasePriceListVersionId()
.orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@"));
}
public List<ProductsProposalRow> getAllRows()
{
return ImmutableList.copyOf(getRows());
|
}
public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests)
{
rowsData.addOrUpdateRows(requests);
invalidateAll();
}
public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request)
{
rowsData.patchRow(rowId, request);
}
public void removeRowsByIds(final Set<DocumentId> rowIds)
{
rowsData.removeRowsByIds(rowIds);
invalidateAll();
}
public ProductsProposalView filter(final ProductsProposalViewFilter filter)
{
rowsData.filter(filter);
return this;
}
@Override
public DocumentFilterList getFilters()
{
return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
| 1
|
请完成以下Java代码
|
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Tax Indicator.
@param TaxIndicator
Short form for Tax to be printed on documents
*/
public void setTaxIndicator (String TaxIndicator)
{
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
/** Get Tax Indicator.
@return Short form for Tax to be printed on documents
*/
public String getTaxIndicator ()
|
{
return (String)get_Value(COLUMNNAME_TaxIndicator);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java
| 1
|
请完成以下Java代码
|
void init() {
Configuration cacheConfig = new ConfigurationBuilder()
.clustering().cacheMode(CacheMode.LOCAL)
.memory().maxCount(10)
.expiration().lifespan(600, TimeUnit.MILLISECONDS)
.persistence().passivation(true).build();
demoCache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache(CACHE_NAME, cacheConfig);
}
public void put(String key, String value) {
demoCache.put(key, value);
}
public String get(String key) {
return demoCache.get(key);
}
public void bulkPut(Map<String, String> entries) {
demoCache.putAll(entries);
}
|
public int size() {
return demoCache.size();
}
public void clear() {
demoCache.clear();
}
public boolean isPassivationEnabled() {
return cacheManager.getCacheConfiguration(CACHE_NAME).persistence().passivation();
}
public void stop() {
cacheManager.stop();
}
}
|
repos\tutorials-master\quarkus-modules\quarkus-infinispan-embedded\src\main\java\com\baeldung\quarkus\infinispan\InfinispanCacheService.java
| 1
|
请完成以下Java代码
|
public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException {
if ((newBase < 2 || newBase > 10) && newBase != 16) {
throw new IllegalArgumentException("New base must be from 2 - 10 or 16");
}
String result = "";
int remainder;
while (num > 0) {
remainder = num % newBase;
if (newBase == 16) {
if (remainder == 10) {
result += 'A';
} else if (remainder == 11) {
result += 'B';
} else if (remainder == 12) {
result += 'C';
} else if (remainder == 13) {
result += 'D';
} else if (remainder == 14) {
result += 'E';
} else if (remainder == 15) {
result += 'F';
} else {
result += remainder;
}
} else {
result += remainder;
}
num /= newBase;
|
}
return new StringBuffer(result).reverse().toString();
}
public static int convertFromAnyBaseToDecimal(String num, int base) {
if (base < 2 || (base > 10 && base != 16)) {
return -1;
}
int val = 0;
int power = 1;
for (int i = num.length() - 1; i >= 0; i--) {
int digit = charToDecimal(num.charAt(i));
if (digit < 0 || digit >= base) {
return -1;
}
val += digit * power;
power = power * base;
}
return val;
}
public static int charToDecimal(char c) {
if (c >= '0' && c <= '9') {
return (int) c - '0';
} else {
return (int) c - 'A' + 10;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-5\src\main\java\com\baeldung\convertnumberbases\ConvertNumberBases.java
| 1
|
请完成以下Java代码
|
public String getComputerIp() {
return computerIp;
}
public void setComputerIp(String computerIp) {
this.computerIp = computerIp;
}
public String getUserDir() {
return userDir;
}
public void setUserDir(String userDir) {
this.userDir = userDir;
}
public String getOsName() {
|
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public String getOsArch() {
return osArch;
}
public void setOsArch(String osArch) {
this.osArch = osArch;
}
}
|
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Sys.java
| 1
|
请完成以下Java代码
|
public class DateRangeOverlapChecker {
public static boolean isOverlapUsingCalendarAndDuration(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
long overlap = Math.min(end1.getTimeInMillis(), end2.getTimeInMillis()) - Math.max(start1.getTimeInMillis(), start2.getTimeInMillis());
return overlap >= 0;
}
public static boolean isOverlapUsingLocalDateAndDuration(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
long overlap = Math.min(end1.toEpochDay(), end2.toEpochDay()) - Math.max(start1.toEpochDay(), start2.toEpochDay());
return overlap >= 0;
}
public static boolean isOverlapUsingJodaTime(DateTime start1, DateTime end1, DateTime start2, DateTime end2) {
Interval interval1 = new Interval(start1, end1);
Interval interval2 = new Interval(start2, end2);
return interval1.overlaps(interval2);
}
public static boolean isOverlapUsingCalendarAndCondition(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
return !(end1.before(start2) || start1.after(end2));
}
|
public static boolean isOverlapUsingLocalDateAndCondition(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
return !(end1.isBefore(start2) || start1.isAfter(end2));
}
public static boolean isOverlapUsingCalendarAndFindMin(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
long overlap1 = Math.min(end1.getTimeInMillis() - start1.getTimeInMillis(), end1.getTimeInMillis() - start2.getTimeInMillis());
long overlap2 = Math.min(end2.getTimeInMillis() - start2.getTimeInMillis(), end2.getTimeInMillis() - start1.getTimeInMillis());
return Math.min(overlap1, overlap2) / (24 * 60 * 60 * 1000) >= 0;
}
public static boolean isOverlapUsingLocalDateAndFindMin(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
long overlap1 = Math.min(end1.toEpochDay() - start1.toEpochDay(), end1.toEpochDay() - start2.toEpochDay());
long overlap2 = Math.min(end2.toEpochDay() - start2.toEpochDay(), end2.toEpochDay() - start1.toEpochDay());
return Math.min(overlap1, overlap2) >= 0;
}
}
|
repos\tutorials-master\core-java-modules\core-java-8-datetime-3\src\main\java\com\baeldung\daterangeoverlap\DateRangeOverlapChecker.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getSuspendedJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) {
Job job = getSuspendedJobById(jobId);
String stackTrace = managementService.getSuspendedJobExceptionStacktrace(job.getId());
if (stackTrace == null) {
throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' doesn't have an exception stacktrace.", String.class);
}
response.setContentType("text/plain");
return stackTrace;
}
@ApiOperation(value = "Get the exception stacktrace for a deadletter job", tags = { "Jobs" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."),
@ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.")
|
})
@GetMapping("/cmmn-management/deadletter-jobs/{jobId}/exception-stacktrace")
public String getDeadLetterJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) {
Job job = getDeadLetterJobById(jobId);
String stackTrace = managementService.getDeadLetterJobExceptionStacktrace(job.getId());
if (stackTrace == null) {
throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' doesn't have an exception stacktrace.", String.class);
}
response.setContentType("text/plain");
return stackTrace;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobExceptionStacktraceResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SettBiz {
private static final Log LOG = LogFactory.getLog(SettBiz.class);
@Autowired
private DailySettCollectBiz dailySettCollectBiz;
@Autowired
private RpUserPayConfigService rpUserPayConfigService;
@Autowired
private RpSettHandleService rpSettHandleService;
/**
* 发起每日待结算数据统计汇总.<br/>
*
* @param userEnterpriseList
* 结算商户.<br/>
* @param collectDate
* 统计截止日期(一般为昨天的日期)
*/
public void launchDailySettCollect(List<RpAccount> accountList, Date endDate) {
if (accountList == null || accountList.isEmpty()) {
return;
}
// 单商户发起结算
for (RpAccount rpAccount : accountList) {
try {
LOG.debug(rpAccount.getUserNo() + ":开始汇总");
dailySettCollectBiz.dailySettCollect(rpAccount, endDate);
LOG.debug(rpAccount.getUserNo() + ":汇总结束");
} catch (Exception e) {
LOG.error(rpAccount.getUserNo()+":汇总异常", e);
}
}
}
/**
|
* 发起定期自动结算.<br/>
*
* @param userEnterpriseList
* 结算商户.<br/>
*/
public void launchAutoSett(List<RpAccount> accountList) {
if (accountList == null || accountList.isEmpty()) {
return;
}
// 单商户发起结算
for (RpAccount rpAccount : accountList) {
try {
RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByUserNo(rpAccount.getUserNo());
if (rpUserPayConfig == null) {
LOG.info(rpAccount.getUserNo() + "没有商家设置信息,不进行结算");
continue;
}
if (rpUserPayConfig.getIsAutoSett().equals(PublicEnum.YES.name())) {
LOG.debug(rpAccount.getUserNo() + ":开始自动结算");
rpSettHandleService.launchAutoSett(rpAccount.getUserNo());
LOG.debug(rpAccount.getUserNo() + ":自动结算结束");
} else {
LOG.info(rpAccount.getUserNo() + ":非自动结算商家");
}
} catch (Exception e) {
LOG.error("自动结算异常:" + rpAccount.getUserNo(), e);
}
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\biz\SettBiz.java
| 2
|
请完成以下Java代码
|
private void initFeatureMatrix(String[] termArray, FeatureMap featureMap)
{
featureMatrix = new int[termArray.length][];
for (int i = 0; i < featureMatrix.length; i++)
{
featureMatrix[i] = extractFeature(termArray, featureMap, i);
}
}
public static POSInstance create(String segmentedTaggedSentence, FeatureMap featureMap)
{
return create(Sentence.create(segmentedTaggedSentence), featureMap);
}
public static POSInstance create(Sentence sentence, FeatureMap featureMap)
{
if (sentence == null || featureMap == null)
|
{
return null;
}
List<Word> wordList = sentence.toSimpleWordList();
String[] termArray = new String[wordList.size()];
String[] posArray = new String[wordList.size()];
int i = 0;
for (Word word : wordList)
{
termArray[i] = word.getValue();
posArray[i] = word.getLabel();
++i;
}
return new POSInstance(termArray, posArray, featureMap);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\instance\POSInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DestinationsConfig {
private Map<String,DestinationInfo> queues = new HashMap<>();
private Map<String,DestinationInfo> topics = new HashMap<>();
public Map<String, DestinationInfo> getQueues() {
return queues;
}
public void setQueues(Map<String, DestinationInfo> queues) {
this.queues = queues;
}
public Map<String, DestinationInfo> getTopics() {
return topics;
}
public void setTopics(Map<String, DestinationInfo> topics) {
this.topics = topics;
}
// DestinationInfo stores the Exchange name and routing key used
// by our producers when posting messages
static class DestinationInfo {
private String exchange;
private String routingKey;
public String getExchange() {
return exchange;
|
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getRoutingKey() {
return routingKey;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-webflux-amqp\src\main\java\com\baeldung\spring\amqp\DestinationsConfig.java
| 2
|
请完成以下Java代码
|
public boolean invokeHandlers(final String tableName, final Object[] ids, final IContextAware ctx)
{
boolean atLeastOneHandlerFixedIt = false;
for (final INoDataFoundHandler currentHandler : noDataFoundHandlers)
{
final boolean currentHandlerFixedIt = invokeCurrentHandler(currentHandler, tableName, ids, ctx);
if (currentHandlerFixedIt && !atLeastOneHandlerFixedIt)
{
atLeastOneHandlerFixedIt = true;
}
}
return atLeastOneHandlerFixedIt;
}
/**
* Invoke the current handler, unless the current invocation is already happening within an earlier invocation.
* So this method might actually <i>not</i> call the given handler in order to avoid a {@link StackOverflowError} .
*
* @task https://github.com/metasfresh/metasfresh/issues/1076
*/
@VisibleForTesting
/* package */ boolean invokeCurrentHandler(final INoDataFoundHandler handler,
final String tableName,
final Object[] ids,
final IContextAware ctx)
{
final ArrayKeyBuilder keyBuilder = ArrayKey.builder().append(tableName);
for (final Object id : ids)
{
keyBuilder.append(id);
}
final ArrayKey key = keyBuilder.build();
final Set<ArrayKey> currentlyInvokedOnRecords = currentlyActiveHandlers.get()
|
.computeIfAbsent(handler, h -> new HashSet<>());
if (!currentlyInvokedOnRecords.add(key))
{
logger.debug(
"The current handler was already invoked with tableName={} and ids={} earlier in this same stack. Returning to avoid a stack overflowError; key={}; handler={}",
tableName, ids, key, handler);
return false;
}
try
{
return handler.invoke(tableName, ids, ctx);
}
finally
{
currentlyInvokedOnRecords.remove(key);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\po\NoDataFoundHandlers.java
| 1
|
请完成以下Java代码
|
protected boolean isValidEvent(ActivitiEvent event) {
boolean valid = false;
if (event instanceof ActivitiEntityEvent) {
if (entityClass == null) {
valid = true;
} else {
valid = entityClass.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass());
}
}
return valid;
}
/**
* Called when an entity create event is received.
*/
protected void onCreate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity initialized event is received.
*/
protected void onInitialized(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity delete event is received.
*/
protected void onDelete(ActivitiEvent event) {
// Default implementation is a NO-OP
}
|
/**
* Called when an entity update event is received.
*/
protected void onUpdate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an event is received, which is not a create, an update or delete.
*/
protected void onEntityEvent(ActivitiEvent event) {
// Default implementation is a NO-OP
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\BaseEntityEventListener.java
| 1
|
请完成以下Java代码
|
private static Validation extractValidation(@NonNull final I_AD_BusinessRule record)
{
return Validation.adValRule(AdValRuleId.ofRepoId(record.getValidation_Rule_ID()));
}
private static BusinessRulePrecondition fromRecord(@NonNull final I_AD_BusinessRule_Precondition record)
{
return BusinessRulePrecondition.builder()
.id(BusinessRulePreconditionId.ofRepoId(record.getAD_BusinessRule_Precondition_ID()))
.validation(extractValidation(record))
.build();
}
private static Validation extractValidation(@NonNull final I_AD_BusinessRule_Precondition record)
{
final ValidationType type = ValidationType.ofCode(record.getPreconditionType());
switch (type)
{
case SQL:
//noinspection DataFlowIssue
return Validation.sql(record.getPreconditionSQL());
case ValidationRule:
return Validation.adValRule(AdValRuleId.ofRepoId(record.getPrecondition_Rule_ID()));
default:
throw new AdempiereException("Unknown validation type: " + type);
}
}
private static BusinessRuleTrigger fromRecord(@NonNull final I_AD_BusinessRule_Trigger record)
{
return BusinessRuleTrigger.builder()
.id(BusinessRuleTriggerId.ofRepoId(record.getAD_BusinessRule_Trigger_ID()))
.triggerTableId(AdTableId.ofRepoId(record.getSource_Table_ID()))
.timings(extractTimings(record))
.condition(extractCondition(record))
.targetRecordMappingSQL(record.getTargetRecordMappingSQL())
.build();
}
private static @NonNull ImmutableSet<TriggerTiming> extractTimings(final I_AD_BusinessRule_Trigger record)
{
final ImmutableSet.Builder<TriggerTiming> timings = ImmutableSet.builder();
if (record.isOnNew())
{
timings.add(TriggerTiming.NEW);
}
if (record.isOnUpdate())
{
timings.add(TriggerTiming.UPDATE);
|
}
if (record.isOnDelete())
{
timings.add(TriggerTiming.DELETE);
}
return timings.build();
}
@Nullable
private static Validation extractCondition(final I_AD_BusinessRule_Trigger record)
{
return StringUtils.trimBlankToOptional(record.getConditionSQL())
.map(Validation::sql)
.orElse(null);
}
private static BusinessRuleWarningTarget fromRecord(@NonNull final I_AD_BusinessRule_WarningTarget record)
{
final String lookupSQL = StringUtils.trimBlankToNull(record.getLookupSQL());
if (lookupSQL == null)
{
throw new FillMandatoryException(I_AD_BusinessRule_WarningTarget.COLUMNNAME_LookupSQL);
}
return BusinessRuleWarningTarget.sqlLookup(
AdTableId.ofRepoId(record.getAD_Table_ID()),
lookupSQL
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\BusinessRuleLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<SysTenant> getTenantListByUserId(String userId) {
return tenantMapper.getTenantListByUserId(userId);
}
@Override
public void deleteUser(SysUser sysUser, Integer tenantId) {
//被删除人的用户id
String userId = sysUser.getId();
//被删除人的密码
String password = sysUser.getPassword();
//当前登录用户
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//step1 判断当前用户是否为当前租户的创建者才可以删除
SysTenant sysTenant = this.getById(tenantId);
if(null == sysTenant || !user.getUsername().equals(sysTenant.getCreateBy())){
throw new JeecgBootException("您不是当前组织的创建者,无法删除用户!");
}
//step2 判断除了当前组织之外是否还有加入了其他组织
LambdaQueryWrapper<SysUserTenant> query = new LambdaQueryWrapper<>();
query.eq(SysUserTenant::getUserId,userId);
query.ne(SysUserTenant::getTenantId,tenantId);
List<SysUserTenant> sysUserTenants = userTenantMapper.selectList(query);
if(CollectionUtils.isNotEmpty(sysUserTenants)){
throw new JeecgBootException("该用户还存在于其它组织中,无法删除用户!");
}
//step3 验证创建时间和密码
SysUser sysUserData = userService.getById(userId);
this.verifyCreateTimeAndPassword(sysUserData,password);
//step4 真实删除用户
userService.deleteUser(userId);
userService.removeLogicDeleted(Collections.singletonList(userId));
}
/**
* 为用户添加租户下所有套餐
*
* @param userId 用户id
|
* @param tenantId 租户id
*/
public void addPackUser(String userId, String tenantId) {
//根据租户id和产品包的code获取租户套餐id
List<String> packIds = sysTenantPackMapper.getPackIdByPackCodeAndTenantId(oConvertUtils.getInt(tenantId));
if (CollectionUtil.isNotEmpty(packIds)) {
for (String packId : packIds) {
SysTenantPackUser sysTenantPackUser = new SysTenantPackUser();
sysTenantPackUser.setUserId(userId);
sysTenantPackUser.setTenantId(oConvertUtils.getInt(tenantId));
sysTenantPackUser.setPackId(packId);
sysTenantPackUser.setStatus(CommonConstant.STATUS_1_INT);
try {
this.addTenantPackUser(sysTenantPackUser);
} catch (Exception e) {
log.warn("添加用户套餐包失败,原因:" + e.getMessage());
}
}
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTenantServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static DDOrderQuery toActiveNotAssignedDDOrderQuery(final @NonNull DDOrderReferenceQuery query)
{
final DistributionFacetIdsCollection activeFacetIds = query.getActiveFacetIds();
final InSetPredicate<WarehouseId> warehouseToIds = extractWarehouseToIds(query);
return newDDOrdersQuery()
.orderBys(query.getSorting().toDDOrderQueryOrderBys())
.responsibleId(ValueRestriction.isNull())
.warehouseFromIds(activeFacetIds.getWarehouseFromIds())
.warehouseToIds(warehouseToIds)
.locatorToIds(InSetPredicate.onlyOrAny(query.getLocatorToId()))
.salesOrderIds(activeFacetIds.getSalesOrderIds())
.manufacturingOrderIds(activeFacetIds.getManufacturingOrderIds())
.datesPromised(activeFacetIds.getDatesPromised())
.productIds(activeFacetIds.getProductIds())
.qtysEntered(activeFacetIds.getQuantities())
.plantIds(activeFacetIds.getPlantIds())
.build();
}
@Nullable
private static InSetPredicate<WarehouseId> extractWarehouseToIds(final @NotNull DDOrderReferenceQuery query)
{
|
final Set<WarehouseId> facetWarehouseToIds = query.getActiveFacetIds().getWarehouseToIds();
final WarehouseId onlyWarehouseToId = query.getWarehouseToId();
if (onlyWarehouseToId != null)
{
if (facetWarehouseToIds.isEmpty() || facetWarehouseToIds.contains(onlyWarehouseToId))
{
return InSetPredicate.only(onlyWarehouseToId);
}
else
{
return InSetPredicate.none();
}
}
else if (!facetWarehouseToIds.isEmpty())
{
return InSetPredicate.only(facetWarehouseToIds);
}
else
{
return InSetPredicate.any();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobQueries.java
| 2
|
请完成以下Java代码
|
public void executeHandler(DeleteProcessInstanceBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
commandContext.executeWithOperationLogPrevented(
new DeleteProcessInstancesCmd(
batchConfiguration.getIds(),
batchConfiguration.getDeleteReason(),
batchConfiguration.isSkipCustomListeners(),
true,
batchConfiguration.isSkipSubprocesses(),
batchConfiguration.isFailIfNotExists(),
batchConfiguration.isSkipIoMappings()
));
}
@Override
protected void createJobEntities(BatchEntity batch, DeleteProcessInstanceBatchConfiguration configuration, String deploymentId, List<String> processIds,
|
int invocationsPerBatchJob) {
// handle legacy batch entities (no up-front deployment mapping has been done)
if (deploymentId == null && (configuration.getIdMappings() == null || configuration.getIdMappings().isEmpty())) {
// create deployment mappings for the ids to process
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(configuration.getIds()));
elementConfiguration.addDeploymentMappings(query.listDeploymentIdMappings(), configuration.getIds());
// create jobs by deployment id
elementConfiguration.getMappings().forEach(mapping -> super.createJobEntities(batch, configuration, mapping.getDeploymentId(),
mapping.getIds(processIds), invocationsPerBatchJob));
} else {
super.createJobEntities(batch, configuration, deploymentId, processIds, invocationsPerBatchJob);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\deletion\DeleteProcessInstancesJobHandler.java
| 1
|
请完成以下Java代码
|
public class RemoveTaskVariablesCmd extends NeedsActiveTaskCmd<Void> {
private static final long serialVersionUID = 1L;
private final Collection<String> variableNames;
private final boolean isLocal;
public RemoveTaskVariablesCmd(String taskId, Collection<String> variableNames, boolean isLocal) {
super(taskId);
this.variableNames = variableNames;
this.isLocal = isLocal;
}
@Override
protected Void execute(CommandContext commandContext, TaskEntity task) {
|
if (isLocal) {
task.removeVariablesLocal(variableNames);
} else {
task.removeVariables(variableNames);
}
return null;
}
@Override
protected String getSuspendedTaskExceptionPrefix() {
return "Cannot remove variables from";
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\RemoveTaskVariablesCmd.java
| 1
|
请完成以下Java代码
|
public MapFormat setArguments(final Map<String, ?> map)
{
if (map == null)
{
this._argumentsMap = ImmutableMap.of();
}
else
{
this._argumentsMap = new HashMap<>(map);
}
return this;
}
public MapFormat setArguments(final List<Object> list)
{
setArguments(toArgumentsMap(list));
return this;
}
private static final Map<String, Object> toArgumentsMap(final List<Object> list)
{
if (list == null || list.isEmpty())
{
return ImmutableMap.of();
}
else
{
final int size = list.size();
final Map<String, Object> map = new HashMap<>();
for (int i = 0; i < size; i++)
{
map.put(String.valueOf(i), list.get(i));
}
return map;
}
}
/** Pre-compiled pattern */
private static final class Pattern
{
private static final int BUFSIZE = 255;
/** Offsets to {} expressions */
private int[] offsets;
/** Keys enclosed by {} brackets */
private String[] arguments;
/** Max used offset */
private int maxOffset;
private final String patternPrepared;
public Pattern(final String patternStr, final String leftDelimiter, final String rightDelimiter, final boolean exactMatch)
{
super();
int idx = 0;
int offnum = -1;
final StringBuffer outpat = new StringBuffer();
offsets = new int[BUFSIZE];
arguments = new String[BUFSIZE];
maxOffset = -1;
while (true)
{
int rightDelimiterIdx = -1;
final int leftDelimiterIdx = patternStr.indexOf(leftDelimiter, idx);
if (leftDelimiterIdx >= 0)
{
rightDelimiterIdx = patternStr.indexOf(rightDelimiter, leftDelimiterIdx + leftDelimiter.length());
}
else
{
break;
}
|
if (++offnum >= BUFSIZE)
{
throw new IllegalArgumentException("TooManyArguments");
}
if (rightDelimiterIdx < 0)
{
if (exactMatch)
{
throw new IllegalArgumentException("UnmatchedBraces");
}
else
{
break;
}
}
outpat.append(patternStr.substring(idx, leftDelimiterIdx));
offsets[offnum] = outpat.length();
arguments[offnum] = patternStr.substring(leftDelimiterIdx + leftDelimiter.length(), rightDelimiterIdx);
idx = rightDelimiterIdx + rightDelimiter.length();
maxOffset++;
}
outpat.append(patternStr.substring(idx));
this.patternPrepared = outpat.toString();
}
public String substring(int beginIndex, int endIndex)
{
return patternPrepared.substring(beginIndex, endIndex);
}
public int length()
{
return patternPrepared.length();
}
public int getMaxOffset()
{
return maxOffset;
}
public int getOffsetIndex(final int i)
{
return offsets[i];
}
public String getArgument(final int i)
{
return arguments[i];
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java-legacy\org\adempiere\util\text\MapFormat.java
| 1
|
请完成以下Java代码
|
public String getImportType() {
return importTypeAttribute.getValue(this);
}
public void setImportType(String importType) {
importTypeAttribute.setValue(this, importType);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Import.class, CMMN_ELEMENT_IMPORT)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Import>() {
public Import newInstance(ModelTypeInstanceContext instanceContext) {
return new ImportImpl(instanceContext);
}
});
|
namespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAMESPACE)
.build();
locationAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_LOCATION)
.required()
.build();
importTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPORT_TYPE)
.required()
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ImportImpl.java
| 1
|
请完成以下Java代码
|
public class ByteArrayRef implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private ByteArrayEntity entity;
protected boolean deleted;
public ByteArrayRef() {}
// Only intended to be used by ByteArrayRefTypeHandler
public ByteArrayRef(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public byte[] getBytes() {
ensureInitialized();
return (entity != null ? entity.getBytes() : null);
}
public void setValue(String name, byte[] bytes) {
this.name = name;
setBytes(bytes);
}
private void setBytes(byte[] bytes) {
if (id == null) {
if (bytes != null) {
ByteArrayEntityManager byteArrayEntityManager = Context.getCommandContext().getByteArrayEntityManager();
entity = byteArrayEntityManager.create();
entity.setName(name);
entity.setBytes(bytes);
byteArrayEntityManager.insert(entity);
id = entity.getId();
|
}
} else {
ensureInitialized();
entity.setBytes(bytes);
}
}
public ByteArrayEntity getEntity() {
ensureInitialized();
return entity;
}
public void delete() {
if (!deleted && id != null) {
if (entity != null) {
// if the entity has been loaded already,
// we might as well use the safer optimistic locking delete.
Context.getCommandContext().getByteArrayEntityManager().delete(entity);
} else {
Context.getCommandContext().getByteArrayEntityManager().deleteByteArrayById(id);
}
entity = null;
id = null;
deleted = true;
}
}
private void ensureInitialized() {
if (id != null && entity == null) {
entity = Context.getCommandContext().getByteArrayEntityManager().findById(id);
name = entity.getName();
}
}
public boolean isDeleted() {
return deleted;
}
@Override
public String toString() {
return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]");
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayRef.java
| 1
|
请完成以下Java代码
|
public void setX (final @Nullable java.lang.String X)
{
set_Value (COLUMNNAME_X, X);
}
@Override
public java.lang.String getX()
{
return get_ValueAsString(COLUMNNAME_X);
}
@Override
public void setX1 (final @Nullable java.lang.String X1)
{
set_Value (COLUMNNAME_X1, X1);
}
@Override
public java.lang.String getX1()
{
return get_ValueAsString(COLUMNNAME_X1);
}
@Override
public void setY (final @Nullable java.lang.String Y)
{
set_Value (COLUMNNAME_Y, Y);
}
@Override
public java.lang.String getY()
|
{
return get_ValueAsString(COLUMNNAME_Y);
}
@Override
public void setZ (final @Nullable java.lang.String Z)
{
set_Value (COLUMNNAME_Z, Z);
}
@Override
public java.lang.String getZ()
{
return get_ValueAsString(COLUMNNAME_Z);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
| 1
|
请完成以下Java代码
|
public static Builder withId(@NonNull String registeredClientId, @NonNull String principalName) {
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return new Builder(registeredClientId, principalName);
}
/**
* A builder for {@link OAuth2AuthorizationConsent}.
*/
public static final class Builder {
private final String registeredClientId;
private final String principalName;
private final Set<GrantedAuthority> authorities = new HashSet<>();
private Builder(String registeredClientId, String principalName) {
this(registeredClientId, principalName, Collections.emptySet());
}
private Builder(String registeredClientId, String principalName, Set<GrantedAuthority> authorities) {
this.registeredClientId = registeredClientId;
this.principalName = principalName;
if (!CollectionUtils.isEmpty(authorities)) {
this.authorities.addAll(authorities);
}
}
/**
* Adds a scope to the collection of {@code authorities} in the resulting
* {@link OAuth2AuthorizationConsent}, wrapping it in a
* {@link SimpleGrantedAuthority}, prefixed by {@code SCOPE_}. For example, a
* {@code message.write} scope would be stored as {@code SCOPE_message.write}.
* @param scope the scope
* @return the {@code Builder} for further configuration
*/
public Builder scope(String scope) {
authority(new SimpleGrantedAuthority(AUTHORITIES_SCOPE_PREFIX + scope));
|
return this;
}
/**
* Adds a {@link GrantedAuthority} to the collection of {@code authorities} in the
* resulting {@link OAuth2AuthorizationConsent}.
* @param authority the {@link GrantedAuthority}
* @return the {@code Builder} for further configuration
*/
public Builder authority(GrantedAuthority authority) {
this.authorities.add(authority);
return this;
}
/**
* A {@code Consumer} of the {@code authorities}, allowing the ability to add,
* replace or remove.
* @param authoritiesConsumer a {@code Consumer} of the {@code authorities}
* @return the {@code Builder} for further configuration
*/
public Builder authorities(Consumer<Set<GrantedAuthority>> authoritiesConsumer) {
authoritiesConsumer.accept(this.authorities);
return this;
}
/**
* Validate the authorities and build the {@link OAuth2AuthorizationConsent}.
* There must be at least one {@link GrantedAuthority}.
* @return the {@link OAuth2AuthorizationConsent}
*/
public OAuth2AuthorizationConsent build() {
Assert.notEmpty(this.authorities, "authorities cannot be empty");
return new OAuth2AuthorizationConsent(this.registeredClientId, this.principalName, this.authorities);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationConsent.java
| 1
|
请完成以下Java代码
|
public class RootUriBuilderFactory extends RootUriTemplateHandler implements UriBuilderFactory {
/**
* Create an instance with the root URI to use.
* @param rootUri the root URI
* @param delegate the {@link UriTemplateHandler} to delegate to
*/
public RootUriBuilderFactory(String rootUri, UriTemplateHandler delegate) {
super(rootUri, delegate);
}
@Override
public UriBuilder uriString(String uriTemplate) {
return UriComponentsBuilder.fromUriString(apply(uriTemplate));
}
|
@Override
public UriBuilder builder() {
return UriComponentsBuilder.newInstance();
}
/**
* Apply a {@link RootUriBuilderFactory} instance to the given {@link RestTemplate}.
* @param restTemplate the {@link RestTemplate} to add the builder factory to
* @param rootUri the root URI
*/
static void applyTo(RestTemplate restTemplate, String rootUri) {
Assert.notNull(restTemplate, "'restTemplate' must not be null");
RootUriBuilderFactory handler = new RootUriBuilderFactory(rootUri, restTemplate.getUriTemplateHandler());
restTemplate.setUriTemplateHandler(handler);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\RootUriBuilderFactory.java
| 1
|
请完成以下Java代码
|
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getRemote_Addr());
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
public I_W_ClickCount getW_ClickCount() throws RuntimeException
{
return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name)
.getPO(getW_ClickCount_ID(), get_TrxName()); }
/** Set Click Count.
@param W_ClickCount_ID
Web Click Management
*/
public void setW_ClickCount_ID (int W_ClickCount_ID)
|
{
if (W_ClickCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID));
}
/** Get Click Count.
@return Web Click Management
*/
public int getW_ClickCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Click.
@param W_Click_ID
Individual Web Click
*/
public void setW_Click_ID (int W_Click_ID)
{
if (W_Click_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Click_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID));
}
/** Get Web Click.
@return Individual Web Click
*/
public int getW_Click_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Click.java
| 1
|
请完成以下Java代码
|
public IHUDisplayNameBuilder setShowHUPINameNextLine(final boolean showHUPINameNextLine)
{
this.showHUPINameNextLine = showHUPINameNextLine;
return this;
}
protected String getHUValue()
{
final I_M_HU hu = getM_HU();
String huValue = hu.getValue();
if (Check.isEmpty(huValue, true))
{
huValue = String.valueOf(hu.getM_HU_ID());
}
return huValue;
}
@Override
public final String getPIName()
{
final I_M_HU hu = getM_HU();
final String piNameRaw;
if (handlingUnitsBL.isAggregateHU(hu))
{
piNameRaw = getAggregateHuPiName(hu);
}
else
{
final I_M_HU_PI pi = handlingUnitsBL.getPI(hu);
piNameRaw = pi != null ? pi.getName() : "?";
}
return escape(piNameRaw);
}
private String getAggregateHuPiName(final I_M_HU hu)
{
// note: if HU is an aggregate HU, then there won't be an NPE here.
final I_M_HU_Item parentItem = hu.getM_HU_Item_Parent();
final I_M_HU_PI_Item parentPIItem = handlingUnitsBL.getPIItem(parentItem);
if (parentPIItem == null)
{
// new HUException("Aggregate HU's parent item has no M_HU_PI_Item; parent-item=" + parentItem)
// .setParameter("parent M_HU_PI_Item_ID", parentItem != null ? parentItem.getM_HU_PI_Item_ID() : null)
// .throwIfDeveloperModeOrLogWarningElse(logger);
return "?";
}
HuPackingInstructionsId includedPIId = HuPackingInstructionsId.ofRepoIdOrNull(parentPIItem.getIncluded_HU_PI_ID());
if (includedPIId == null)
{
//noinspection ThrowableNotThrown
|
new HUException("Aggregate HU's parent item has M_HU_PI_Item without an Included_HU_PI; parent-item=" + parentItem).throwIfDeveloperModeOrLogWarningElse(logger);
return "?";
}
final I_M_HU_PI included_HU_PI = handlingUnitsBL.getPI(includedPIId);
return included_HU_PI.getName();
}
// NOTE: this method can be overridden by extending classes in order to optimize how the HUs are counted.
@Override
public int getIncludedHUsCount()
{
// NOTE: we need to iterate the HUs and count them (instead of doing a COUNT directly on database),
// because we rely on HU&Items caching
// and also because in case of aggregated HUs, we need special handling
final IncludedHUsCounter includedHUsCounter = new IncludedHUsCounter(getM_HU());
final HUIterator huIterator = new HUIterator();
huIterator.setListener(includedHUsCounter.toHUIteratorListener());
huIterator.setEnableStorageIteration(false);
huIterator.iterate(getM_HU());
return includedHUsCounter.getHUsCount();
}
protected String escape(final String string)
{
return StringUtils.maskHTML(string);
}
@Override
public IHUDisplayNameBuilder setShowIfDestroyed(final boolean showIfDestroyed)
{
this.showIfDestroyed = showIfDestroyed;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDisplayNameBuilder.java
| 1
|
请完成以下Java代码
|
public class GrpcServerShutdownEvent extends GrpcServerLifecycleEvent {
private static final long serialVersionUID = 1L;
/**
* Creates a new GrpcServerShutdownEvent.
*
* @param lifecyle The lifecycle that caused this event.
* @param clock The clock used to determine the timestamp.
* @param server The server related to this event.
*/
public GrpcServerShutdownEvent(
final GrpcServerLifecycle lifecyle,
final Clock clock,
final Server server) {
|
super(lifecyle, clock, server);
}
/**
* Creates a new GrpcServerShutdownEvent.
*
* @param lifecyle The lifecycle that caused this event.
* @param server The server related to this event.
*/
public GrpcServerShutdownEvent(
final GrpcServerLifecycle lifecyle,
final Server server) {
super(lifecyle, server);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\event\GrpcServerShutdownEvent.java
| 1
|
请完成以下Java代码
|
public boolean isDropShip()
{
return BPartnerLocationId.ofRepoIdOrNull(getDropShip_BPartner_ID(), getDropShip_Location_ID()) != null;
}
@Override
public int getM_Warehouse_ID()
{
return delegate.getM_Warehouse_ID();
}
@Override
public int getDropShip_BPartner_ID()
{
return delegate.getDropShip_BPartner_ID();
}
@Override
public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID)
{
delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID);
}
@Override
public int getDropShip_Location_ID()
{
return delegate.getDropShip_Location_ID();
}
@Override
public void setDropShip_Location_ID(final int DropShip_Location_ID)
{
delegate.setDropShip_Location_ID(DropShip_Location_ID);
}
@Override
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
|
}
@Override
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DropShipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new DropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DropShipLocationAdapter.java
| 1
|
请完成以下Java代码
|
public class SEPA_Main_Validator implements ModelValidator
{
private int m_AD_Client_ID = -1;
@Override
public void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
engine.addModelValidator(new SEPA_Export_Line(), client); // task 07789
engine.addModelValidator(new C_BP_BankAccount(), client); // 08477 Supporting IBAN and BIC
}
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing to do
|
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing to do
}
@Override
public String docValidate(final PO po, final int timing)
{
return null; // nothing to do
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\model\validator\SEPA_Main_Validator.java
| 1
|
请完成以下Java代码
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine()
{
return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class);
}
|
@Override
public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine)
{
set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine);
}
@Override
public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID);
}
@Override
public int getS_TimeExpenseLine_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
| 1
|
请完成以下Java代码
|
private IHUQueryBuilder createHUQuery(
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final BPartnerId bpartnerId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final HUReservationDocRef reservedToDocumentOrNotReservedAtAll)
{
final Set<WarehouseId> pickingWarehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(warehouseId);
final IHUQueryBuilder huQuery = handlingUnitsDAO
.createHUQueryBuilder()
.addOnlyInWarehouseIds(pickingWarehouseIds)
.addOnlyWithProductId(productId)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active);
// ASI
if (asiId != null)
{
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(asiId);
huQuery.addOnlyWithAttributeValuesMatchingPartnerAndProduct(bpartnerId, productId, attributeSet);
huQuery.allowSqlWhenFilteringAttributes(isAllowSqlWhenFilteringHUAttributes());
}
// Reservation
if (reservedToDocumentOrNotReservedAtAll == null)
{
huQuery.setExcludeReserved();
}
else
{
huQuery.setExcludeReservedToOtherThan(reservedToDocumentOrNotReservedAtAll);
}
return huQuery;
|
}
// FIXME: move it to AttributeDAO
@Deprecated
public boolean isAllowSqlWhenFilteringHUAttributes()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowSqlWhenFilteringHUAttributes, true);
}
public void transferReservation(
@NonNull final HUReservationDocRef from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> vhuIds)
{
huReservationRepository.transferReservation(ImmutableSet.of(from), to, vhuIds);
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to)
{
final Set<HuId> vhuIds = ImmutableSet.of();
huReservationRepository.transferReservation(from, to, vhuIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationService.java
| 1
|
请完成以下Java代码
|
public void addCacheResetListener(@NonNull final BusinessRulesChangedListener listener)
{
final ICacheResetListener cacheResetListener = (request) -> {
listener.onRulesChanged();
return 1L;
};
final CacheMgt cacheMgt = CacheMgt.get();
cacheMgt.addCacheResetListener(I_AD_BusinessRule.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_Precondition.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_Trigger.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_WarningTarget.Table_Name, cacheResetListener);
}
public BusinessRulesCollection getAll()
{
return cache.getOrLoad(0, this::retrieveAll);
}
private BusinessRulesCollection retrieveAll() {return newLoader().retrieveAll();}
|
private BusinessRuleLoader newLoader()
{
return BusinessRuleLoader.builder()
.queryBL(queryBL)
.build();
}
public void validate(final I_AD_BusinessRule record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_Precondition record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_Trigger record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_WarningTarget record) {newLoader().validate(record);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\BusinessRuleRepository.java
| 1
|
请完成以下Java代码
|
public boolean isPostOnlyForSomeOrgs()
{
return !postOnlyForOrgIds.isEmpty();
}
public boolean isAllowPostingForOrg(@NonNull final OrgId orgId)
{
if (postOnlyForOrgIds.isEmpty())
{
return true;
}
else
{
return postOnlyForOrgIds.contains(orgId);
}
}
public boolean isDisallowPostingForOrg(@NonNull final OrgId orgId)
{
return !isAllowPostingForOrg(orgId);
}
public boolean isElementEnabled(@NonNull final AcctSchemaElementType elementType)
{
|
return getSchemaElements().isElementEnabled(elementType);
}
public AcctSchemaElement getSchemaElementByType(@NonNull final AcctSchemaElementType elementType)
{
return getSchemaElements().getByElementType(elementType);
}
public ImmutableSet<AcctSchemaElementType> getSchemaElementTypes()
{
return getSchemaElements().getElementTypes();
}
public ChartOfAccountsId getChartOfAccountsId()
{
return getSchemaElements().getChartOfAccountsId();
}
public boolean isAccountingCurrency(@NonNull final CurrencyId currencyId)
{
return CurrencyId.equals(this.currencyId, currencyId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchema.java
| 1
|
请完成以下Java代码
|
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getExternalTaskManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
public String getExternalTaskId() {
return externalTaskId;
}
public String getWorkerId() {
return workerId;
}
public Date getLockExpirationBefore() {
return lockExpirationBefore;
}
public Date getLockExpirationAfter() {
return lockExpirationAfter;
}
public String getTopicName() {
return topicName;
}
public Boolean getLocked() {
return locked;
}
public Boolean getNotLocked() {
return notLocked;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
return activityId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getRetriesLeft() {
return retriesLeft;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java
| 1
|
请完成以下Java代码
|
public class SAP_GLJournal_ReverseDocument extends JavaProcess implements IProcessPrecondition
{
private final static AdMessageKey DOCUMENT_MUST_BE_COMPLETED_MSG = AdMessageKey.of("gljournal_sap.Document_has_to_be_Completed");
private final SAPGLJournalService glJournalService = SpringContextHolder.instance.getBean(SAPGLJournalService.class);
@Param(mandatory = true, parameterName = "DateDoc")
private Instant dateDoc;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(context.getSingleSelectedRecordId());
final DocStatus docStatus = glJournalService.getDocStatus(glJournalId);
if (!docStatus.isCompleted())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(DOCUMENT_MUST_BE_COMPLETED_MSG));
}
return ProcessPreconditionsResolution.accept();
}
|
@Override
protected String doIt()
{
final SAPGLJournal createdJournal = glJournalService.reverse(SAPGLJournalReverseRequest.builder()
.sourceJournalId(SAPGLJournalId.ofRepoId(getRecord_ID()))
.dateDoc(dateDoc)
.build());
getResult().setRecordToOpen(TableRecordReference.of(I_SAP_GLJournal.Table_Name, createdJournal.getId()),
getProcessInfo().getAD_Window_ID(),
ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\process\SAP_GLJournal_ReverseDocument.java
| 1
|
请完成以下Spring Boot application配置
|
spring.application.name=spring-security-app
server.servlet.context-path=/app
server.port=8085
api.auth.header.name=x-auth-secret-key
logging.level.org.springframework.security=DEBUG
spring.profiles.active=inmemory
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=password
spring.dat
|
asource.driver-class-name=org.h2.Driver
spring.sql.init.schema-locations=classpath:org/springframework/security/core/userdetails/jdbc/users.ddl
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-5\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public String getInternalName()
{
if (internalName == null)
{
return Integer.toString(getNode_ID()); // fallback to avoid NPE.
}
return internalName;
}
public void setInternalName(final String internalName)
{
this.internalName = internalName;
}
private int AD_Window_ID = -1;
private int AD_Process_ID = -1;
private int AD_Form_ID = -1;
private int AD_Workflow_ID = -1;
private int AD_Task_ID = -1;
private int WEBUI_Board_ID = -1;
private boolean isCreateNewRecord = false;
private String webuiNameBrowse;
private String webuiNameNew;
private String webuiNameNewBreadcrumb;
private String mainTableName;
public int getAD_Window_ID()
{
return AD_Window_ID;
}
public void setAD_Window_ID(int aD_Window_ID)
{
AD_Window_ID = aD_Window_ID;
}
public int getAD_Process_ID()
{
return AD_Process_ID;
}
public void setAD_Process_ID(int aD_Process_ID)
{
AD_Process_ID = aD_Process_ID;
}
public int getAD_Form_ID()
{
return AD_Form_ID;
}
public void setAD_Form_ID(int aD_Form_ID)
{
AD_Form_ID = aD_Form_ID;
}
public int getAD_Workflow_ID()
{
return AD_Workflow_ID;
}
public void setAD_Workflow_ID(int aD_Workflow_ID)
{
AD_Workflow_ID = aD_Workflow_ID;
}
public int getAD_Task_ID()
{
return AD_Task_ID;
}
public void setAD_Task_ID(int aD_Task_ID)
{
AD_Task_ID = aD_Task_ID;
}
public int getWEBUI_Board_ID()
{
return WEBUI_Board_ID;
}
public void setWEBUI_Board_ID(final int WEBUI_Board_ID)
{
this.WEBUI_Board_ID = WEBUI_Board_ID;
}
public void setIsCreateNewRecord(final boolean isCreateNewRecord)
{
this.isCreateNewRecord = isCreateNewRecord;
}
public boolean isCreateNewRecord()
{
return isCreateNewRecord;
}
public void setWEBUI_NameBrowse(final String webuiNameBrowse)
{
|
this.webuiNameBrowse = webuiNameBrowse;
}
public String getWEBUI_NameBrowse()
{
return webuiNameBrowse;
}
public void setWEBUI_NameNew(final String webuiNameNew)
{
this.webuiNameNew = webuiNameNew;
}
public String getWEBUI_NameNew()
{
return webuiNameNew;
}
public void setWEBUI_NameNewBreadcrumb(final String webuiNameNewBreadcrumb)
{
this.webuiNameNewBreadcrumb = webuiNameNewBreadcrumb;
}
public String getWEBUI_NameNewBreadcrumb()
{
return webuiNameNewBreadcrumb;
}
/**
* @param mainTableName table name of main tab or null
*/
public void setMainTableName(String mainTableName)
{
this.mainTableName = mainTableName;
}
/**
* @return table name of main tab or null
*/
public String getMainTableName()
{
return mainTableName;
}
} // MTreeNode
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTreeNode.java
| 1
|
请完成以下Java代码
|
public final I_AD_PrinterHW retrieveAttachToPrintPackagePrinter(final Properties ctx, final String hostkey, final String trxName)
{
final IQuery<I_AD_Printer_Config> queryConfig = queryBL.createQueryBuilder(I_AD_Printer_Config.class)
.addEqualsFilter(I_AD_Printer_Config.COLUMN_ConfigHostKey, hostkey)
.create();
final IQuery<I_AD_Printer_Matching> queryMatchings = queryBL.createQueryBuilder(I_AD_Printer_Matching.class)
.addInSubQueryFilter(I_AD_Printer_Matching.COLUMNNAME_AD_Printer_Config_ID, I_AD_Printer_Config.COLUMNNAME_AD_Printer_Config_ID, queryConfig)
.create();
return queryBL.createQueryBuilder(I_AD_PrinterHW.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_PrinterHW.COLUMNNAME_OutputType, X_AD_PrinterHW.OUTPUTTYPE_Attach)
.addInArrayFilter(I_AD_PrinterHW.COLUMN_HostKey, hostkey, null)
.addInSubQueryFilter(I_AD_Printer_Matching.COLUMNNAME_AD_PrinterHW_ID, I_AD_PrinterHW.COLUMNNAME_AD_PrinterHW_ID, queryMatchings)
.orderBy()
.addColumnDescending(I_AD_PrinterHW.COLUMNNAME_HostKey).endOrderBy()
.create()
.first(I_AD_PrinterHW.class);
}
@Override
public List<I_AD_Printer_Tray> retrieveTrays(final LogicalPrinterId printerId)
{
return queryBL.createQueryBuilder(I_AD_Printer_Tray.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Printer_Tray.COLUMNNAME_AD_Printer_ID, printerId)
.create()
.list();
}
@Override
public Stream<I_AD_PrinterHW> streamActiveHardwarePrinters()
{
return queryBL.createQueryBuilder(I_AD_PrinterHW.class)
|
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_PrinterHW.COLUMNNAME_AD_PrinterHW_ID)
.create()
.stream();
}
@Override
public List<I_AD_PrinterHW_MediaTray> retrieveMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId)
{
return queryBL.createQueryBuilder(I_AD_PrinterHW_MediaTray.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_ID, hardwarePrinterId)
.create()
.list();
}
@Override
public Stream<I_AD_PrinterHW_MediaTray> streamActiveMediaTrays()
{
return queryBL.createQueryBuilder(I_AD_PrinterHW_MediaTray.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_ID)
.orderBy(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_MediaTray_ID)
.create()
.stream();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\AbstractPrintingDAO.java
| 1
|
请完成以下Java代码
|
public void foundTomcatDeploymentDescriptor(String bpmPlatformFileLocation, String fileLocation) {
logInfo(
"046",
"Found Camunda Platform configuration in CATALINA_BASE/CATALINA_HOME conf directory [{}] at '{}'", bpmPlatformFileLocation, fileLocation);
}
public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) {
throw new ProcessEngineException(exceptionMessage(
"047",
"'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e);
}
public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) {
logInfo(
"048",
"Camunda Platform sucessfully started at '{}'.", serverInfo);
}
public void camundaBpmPlatformStopped(String serverInfo) {
logInfo(
"049",
"Camunda Platform stopped at '{}'", serverInfo);
|
}
public void paDeployed(String name) {
logInfo(
"050",
"Process application {} successfully deployed", name);
}
public void paUndeployed(String name) {
logInfo(
"051",
"Process application {} undeployed", name);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java
| 1
|
请完成以下Java代码
|
public Class<? extends DeploymentEntity> getManagedEntityClass() {
return DeploymentEntityImpl.class;
}
@Override
public DeploymentEntity create() {
return new DeploymentEntityImpl();
}
@Override
public DeploymentEntity findLatestDeploymentByName(String deploymentName) {
List<?> list = getDbSqlSession().selectList("selectDeploymentsByName", deploymentName, 0, 1);
if (list != null && !list.isEmpty()) {
return (DeploymentEntity) list.get(0);
}
return null;
}
@Override
public DeploymentEntity findDeploymentByVersion(Integer version) {
return getDbSqlSession().getSqlSession().selectOne("selectDeploymentByVersion", version);
}
@Override
public long findDeploymentCountByQueryCriteria(DeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByQueryCriteria", deploymentQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByQueryCriteria(DeploymentQueryImpl deploymentQuery, Page page) {
final String query = "selectDeploymentsByQueryCriteria";
return getDbSqlSession().selectList(query, deploymentQuery, page);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return getDbSqlSession().getSqlSession().selectList("selectResourceNamesByDeploymentId", deploymentId);
|
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectDeploymentByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByNativeQuery", parameterMap);
}
@Override
public Deployment selectLatestDeployment(String deploymentName) {
return (Deployment) getDbSqlSession().selectOne("selectLatestDeployment", deploymentName);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisDeploymentDataManager.java
| 1
|
请完成以下Java代码
|
public int getM_InventoryLineMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLineMA_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Quantity of a product moved.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty)
{
|
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Quantity of a product moved.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLineMA.java
| 1
|
请完成以下Java代码
|
public void init(){
// 实例化连接工厂
connectionFactory=new ActiveMQConnectionFactory(JMSProducerThread.USERNAME, JMSProducerThread.PASSWORD, JMSProducerThread.BROKEURL);
try {
connection=connectionFactory.createConnection(); // 通过连接工厂获取连接
connection.start();
} catch (JMSException e) {
e.printStackTrace();
}
}
public void produce(){
try {
MessageProducer messageProducer; // 消息生产者
session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建Session
destination=session.createQueue("queue1");
messageProducer=session.createProducer(destination); // 创建消息生产者
for(int i=0;i<JMSProducerThread.SENDNUM;i++){
TextMessage message=session.createTextMessage("ActiveMQ中"+Thread.currentThread().getName()+"线程发送的数据"+":"+i);
System.out.println(Thread.currentThread().getName()+"线程"+"发送消息:"+"ActiveMQ 发布的消息"+":"+i);
messageProducer.send(message);
session.commit();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
|
/**
* 发送消息
* @param session
* @param messageProducer
* @throws Exception
*/
public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
for(int i=0;i<JMSProducerThread.SENDNUM;i++){
TextMessage message=session.createTextMessage("ActiveMQ 发送的消息"+i);
System.out.println("发送消息:"+"ActiveMQ 发布的消息"+i);
messageProducer.send(message);
}
}
}
|
repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\client\JMSProducerThread.java
| 1
|
请完成以下Java代码
|
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
|
/** Set SLA Criteria.
@param PA_SLA_Criteria_ID
Service Level Agreement Criteria
*/
public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID)
{
if (PA_SLA_Criteria_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID));
}
/** Get SLA Criteria.
@return Service Level Agreement Criteria
*/
public int getPA_SLA_Criteria_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Criteria.java
| 1
|
请完成以下Java代码
|
private void makeElementColumnMandatory(final I_AD_Column elementIdColumn)
{
elementIdColumn.setIsMandatory(true);
save(elementIdColumn);
final TableDDLSyncService syncService = SpringContextHolder.instance.getBean(TableDDLSyncService.class);
syncService.syncToDatabase(AdColumnId.ofRepoId(elementIdColumn.getAD_Column_ID()));
}
@Override
public I_AD_Element getById(final int elementId)
{
return loadOutOfTrx(elementId, I_AD_Element.class);
}
|
@Override
public AdElementId createNewElement(@NonNull final CreateADElementRequest request)
{
final I_AD_Element record = newInstance(I_AD_Element.class);
record.setName(request.getName());
record.setPrintName(request.getPrintName());
record.setDescription(request.getDescription());
record.setHelp(request.getHelp());
record.setCommitWarning(request.getTabCommitWarning());
saveRecord(record);
return AdElementId.ofRepoId(record.getAD_Element_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\impl\ADElementDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getComment() {
return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
}
/**
* Used to denote details about a bank transaction, via which this invoice has to be paid.
*
* @return
* possible object is
* {@link UniversalBankTransactionType }
*
*/
public UniversalBankTransactionType getUniversalBankTransaction() {
return universalBankTransaction;
}
/**
* Sets the value of the universalBankTransaction property.
*
* @param value
* allowed object is
* {@link UniversalBankTransactionType }
*
*/
public void setUniversalBankTransaction(UniversalBankTransactionType value) {
this.universalBankTransaction = value;
}
/**
* Indicates that no payment takes place as a result of this invoice.
*
* @return
* possible object is
* {@link NoPaymentType }
*
*/
public NoPaymentType getNoPayment() {
return noPayment;
}
/**
* Sets the value of the noPayment property.
*
* @param value
* allowed object is
* {@link NoPaymentType }
*
*/
public void setNoPayment(NoPaymentType value) {
|
this.noPayment = value;
}
/**
* Indicates that a direct debit will take place as a result of this invoice.
*
* @return
* possible object is
* {@link DirectDebitType }
*
*/
public DirectDebitType getDirectDebit() {
return directDebit;
}
/**
* Sets the value of the directDebit property.
*
* @param value
* allowed object is
* {@link DirectDebitType }
*
*/
public void setDirectDebit(DirectDebitType value) {
this.directDebit = value;
}
/**
* Used to denote details about a SEPA direct debit, via which this invoice has to be paid.
*
* @return
* possible object is
* {@link SEPADirectDebitType }
*
*/
public SEPADirectDebitType getSEPADirectDebit() {
return sepaDirectDebit;
}
/**
* Sets the value of the sepaDirectDebit property.
*
* @param value
* allowed object is
* {@link SEPADirectDebitType }
*
*/
public void setSEPADirectDebit(SEPADirectDebitType value) {
this.sepaDirectDebit = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentMethodType.java
| 2
|
请完成以下Java代码
|
public class KeycloakReactiveTokenInstrospector implements ReactiveOpaqueTokenIntrospector {
private final ReactiveOpaqueTokenIntrospector delegate;
public KeycloakReactiveTokenInstrospector(ReactiveOpaqueTokenIntrospector delegate) {
this.delegate = delegate;
}
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
return delegate.introspect(token)
.map( this::mapPrincipal);
}
protected OAuth2AuthenticatedPrincipal mapPrincipal(OAuth2AuthenticatedPrincipal principal) {
return new DefaultOAuth2AuthenticatedPrincipal(
principal.getName(),
principal.getAttributes(),
extractAuthorities(principal));
}
protected Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
|
//
Map<String,List<String>> realm_access = principal.getAttribute("realm_access");
List<String> roles = realm_access.getOrDefault("roles", Collections.emptyList());
List<GrantedAuthority> rolesAuthorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
Set<GrantedAuthority> allAuthorities = new HashSet<>();
allAuthorities.addAll(principal.getAuthorities());
allAuthorities.addAll(rolesAuthorities);
return allAuthorities;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\oauth\shared\KeycloakReactiveTokenInstrospector.java
| 1
|
请完成以下Java代码
|
public boolean isValid()
{
return m_valid;
} // isValid
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize ()
{
p_width = 0;
p_height = 0;
if (m_barcode == null)
return true;
p_width = m_barcode.getWidth();
p_height = m_barcode.getHeight();
if (p_width * p_height == 0)
return true; // don't bother scaling and prevent div by 0
m_scaleFactor = 1f;
if (p_maxWidth != 0 && p_width > p_maxWidth)
m_scaleFactor = p_maxWidth / p_width;
if (p_maxHeight != 0 && p_height > p_maxHeight && p_maxHeight/p_height < m_scaleFactor)
m_scaleFactor = p_maxHeight / p_height;
p_width = (float) m_scaleFactor * p_width;
p_height = (float) m_scaleFactor * p_height;
return true;
} // calculateSize
public float getScaleFactor() {
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return m_scaleFactor;
}
/**
* @author teo_sarca - [ 1673590 ] report table - barcode overflows over next fields
* @return can this element overflow over the next fields
*/
public boolean isAllowOverflow() { //
return m_allowOverflow;
}
/**
* Paint Element
* @param g2D graphics
* @param pageNo page no
* @param pageStart page start
* @param ctx context
* @param isView view
|
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (!m_valid || m_barcode == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
try {
int w = m_barcode.getWidth();
int h = m_barcode.getHeight();
// draw barcode to buffer
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D temp = (Graphics2D) image.getGraphics();
m_barcode.draw(temp, 0, 0);
// scale barcode and paint
AffineTransform transform = new AffineTransform();
transform.translate(x,y);
transform.scale(m_scaleFactor, m_scaleFactor);
g2D.drawImage(image, transform, this);
} catch (OutputException e) {
}
} // paint
/**
* String Representation
* @return info
*/
public String toString ()
{
if (m_barcode == null)
return super.toString();
return super.toString() + " " + m_barcode.getData();
} // toString
} // BarcodeElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\BarcodeElement.java
| 1
|
请完成以下Java代码
|
public PointOfInteractionCapabilities1 getCpblties() {
return cpblties;
}
/**
* Sets the value of the cpblties property.
*
* @param value
* allowed object is
* {@link PointOfInteractionCapabilities1 }
*
*/
public void setCpblties(PointOfInteractionCapabilities1 value) {
this.cpblties = value;
}
/**
* Gets the value of the cmpnt 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 cmpnt property.
*
|
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCmpnt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PointOfInteractionComponent1 }
*
*
*/
public List<PointOfInteractionComponent1> getCmpnt() {
if (cmpnt == null) {
cmpnt = new ArrayList<PointOfInteractionComponent1>();
}
return this.cmpnt;
}
}
|
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\PointOfInteraction1.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/","/home","/about").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
|
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("user123").roles("USER")
.and()
.withUser("admin").password("admin123").roles("ADMIN");
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
|
repos\Spring-Boot-Advanced-Projects-main\Springboot-Security-Project\src\main\java\spring\security\config\SpringSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ParcelShippingService implements ShippingService {
public static final String EVENT_ORDER_READY_FOR_SHIPMENT = "OrderReadyForShipmentEvent";
private ShippingOrderRepository orderRepository;
private EventBus eventBus;
private Map<Integer, Parcel> shippedParcels = new HashMap<>();
@Override
public void shipOrder(int orderId) {
Optional<ShippableOrder> order = this.orderRepository.findShippableOrder(orderId);
order.ifPresent(completedOrder -> {
Parcel parcel = new Parcel(completedOrder.getOrderId(), completedOrder.getAddress(), completedOrder.getPackageItems());
if (parcel.isTaxable()) {
// Calculate additional taxes
}
// Ship parcel
this.shippedParcels.put(completedOrder.getOrderId(), parcel);
});
}
@Override
public void listenToOrderEvents() {
this.eventBus.subscribe(EVENT_ORDER_READY_FOR_SHIPMENT, new EventSubscriber() {
@Override
public <E extends ApplicationEvent> void onEvent(E event) {
shipOrder(Integer.parseInt(event.getPayloadValue("order_id")));
|
}
});
}
@Override
public Optional<Parcel> getParcelByOrderId(int orderId) {
return Optional.ofNullable(this.shippedParcels.get(orderId));
}
public void setOrderRepository(ShippingOrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Override
public EventBus getEventBus() {
return eventBus;
}
@Override
public void setEventBus(EventBus eventBus) {
this.eventBus = eventBus;
}
}
|
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-shippingcontext\src\main\java\com\baeldung\dddcontexts\shippingcontext\service\ParcelShippingService.java
| 2
|
请完成以下Java代码
|
public TopicPartition getTopicPartition() {
return this.topicPartition;
}
/**
* The id of the listener (if {@code @KafkaListener}) or the container bean name.
* @return the id.
*/
public String getListenerId() {
return this.listenerId;
}
/**
* Retrieve the consumer. Only populated if the listener is consumer-aware.
* Allows the listener to resume a paused consumer.
* @return the consumer.
* @since 2.0
*/
public Consumer<?, ?> getConsumer() {
return this.consumer;
}
/**
* Return true if the consumer was paused at the time the idle event was published.
|
* @return paused.
* @since 2.1.5
*/
public boolean isPaused() {
return this.paused;
}
@Override
public String toString() {
return "ListenerContainerPartitionIdleEvent [idleTime="
+ ((float) this.idleTime / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic #
+ ", container=" + getSource()
+ ", paused=" + this.paused
+ ", topicPartition=" + this.topicPartition + "]";
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ListenerContainerPartitionIdleEvent.java
| 1
|
请完成以下Java代码
|
protected final List<Consumer<T>> getCustomizers() {
return this.customizers;
}
protected final List<Consumer<T>> mergedCustomizers(Consumer<T> customizer) {
Assert.notNull(this.customizers, "'customizer' must not be null");
return merge(this.customizers, List.of(customizer));
}
protected final List<Consumer<T>> mergedCustomizers(Collection<Consumer<T>> customizers) {
Assert.notNull(customizers, "'customizers' must not be null");
Assert.noNullElements(customizers, "'customizers' must not contain null elements");
return merge(this.customizers, customizers);
}
private <E> List<E> merge(Collection<E> list, Collection<? extends E> additional) {
List<E> merged = new ArrayList<>(list);
|
merged.addAll(additional);
return List.copyOf(merged);
}
@Override
@SuppressWarnings("unchecked")
public final T build(@Nullable HttpClientSettings settings) {
T factory = createClientHttpRequestFactory((settings != null) ? settings : HttpClientSettings.defaults());
LambdaSafe.callbacks(Consumer.class, this.customizers, factory).invoke((consumer) -> consumer.accept(factory));
return factory;
}
protected abstract T createClientHttpRequestFactory(HttpClientSettings settings);
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\AbstractClientHttpRequestFactoryBuilder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.