instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.authenticationManager(auth)
.tokenStore(tokenStore())
;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.jdbc(dataSource)
.passwordEncoder(passwordEncoder)
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write")
.accessTokenValiditySeconds(3600) // 1 hour
.refreshTokenValiditySeconds(2592000) // 30 days
.and()
.withClient("svca-service")
.secret("password")
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("svcb-service")
.secret("password") | .authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
;
}
@Configuration
@Order(-20)
protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.withUser("dave").password("secret").roles("USER")
.and()
.withUser("anil").password("password").roles("ADMIN")
;
}
}
} | repos\spring-boot-cloud-master\auth-service\src\main\java\cn\zhangxd\auth\config\OAuthConfiguration.java | 2 |
请完成以下Java代码 | protected void initCommandContextCloseListener() {
this.commandContextCloseListener = new LoggingSessionCommandContextCloseListener(this, loggingListener, objectMapper);
}
public void addLoggingData(String type, ObjectNode data, String engineType) {
if (loggingData == null) {
loggingData = new ArrayList<>();
commandContextCloseListener.setEngineType(engineType);
commandContext.addCloseListener(commandContextCloseListener);
}
String transactionId = null;
if (loggingData.size() > 0) {
transactionId = loggingData.get(0).get(LoggingSessionUtil.TRANSACTION_ID).asString();
} else {
transactionId = data.get(LoggingSessionUtil.ID).asString();
}
data.put(LoggingSessionUtil.TRANSACTION_ID, transactionId);
data.put(LoggingSessionUtil.LOG_NUMBER, loggingData.size() + 1);
loggingData.add(data);
}
@Override | public void flush() {
}
@Override
public void close() {
}
public List<ObjectNode> getLoggingData() {
return loggingData;
}
public void setLoggingData(List<ObjectNode> loggingData) {
this.loggingData = loggingData;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSession.java | 1 |
请完成以下Java代码 | public InventoryQueryBuilder onlyResponsibleId(@NonNull final UserId responsibleId)
{
return onlyResponsibleIds(InSetPredicate.only(responsibleId));
}
public InventoryQueryBuilder onlyWarehouseIdOrAny(@Nullable final WarehouseId warehouseId)
{
return onlyWarehouseIds(InSetPredicate.onlyOrAny(warehouseId));
}
public InventoryQueryBuilder onlyDraftOrInProgress()
{
return onlyDocStatuses(InSetPredicate.only(DocStatus.Drafted, DocStatus.InProgress));
} | public <T> InventoryQueryBuilder excludeInventoryIdsOf(@Nullable Collection<T> collection, @NonNull final Function<T, InventoryId> inventoryIdFunction)
{
if (collection == null || collection.isEmpty()) {return this;}
final ImmutableSet<InventoryId> inventoryIds = collection.stream()
.filter(Objects::nonNull)
.map(inventoryIdFunction)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return excludeInventoryIds(inventoryIds);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\InventoryQuery.java | 1 |
请完成以下Java代码 | public void follow(User user) {
follow(user.getId());
}
public void unfollow(User user) {
unfollow(user.getId());
}
public void favorite(Article article) {
article.incrementFavoritesCount();
favoriteArticleIds.add(article.getId());
}
public void unfavorite(Article article) {
article.decrementFavoritesCount(); | favoriteArticleIds.remove(article.getId());
}
public boolean isFavoriteArticle(Article article) {
return favoriteArticleIds.contains(article.getId());
}
public boolean isFollowing(User user) {
return followingIds.contains(user.getId());
}
public boolean isFollower(User user) {
return user.isFollowing(this);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\User.java | 1 |
请完成以下Java代码 | public String getPropertyName() {
return this.propertyName;
}
/**
* Return the actual origin for the source if known.
* @return the actual source origin
* @since 3.2.8
*/
@Override
public @Nullable Origin getOrigin() {
return this.origin;
}
@Override
public @Nullable Origin getParent() {
return (this.origin != null) ? this.origin.getParent() : null;
}
@Override | public String toString() {
return (this.origin != null) ? this.origin.toString()
: "\"" + this.propertyName + "\" from property source \"" + this.propertySource.getName() + "\"";
}
/**
* Get an {@link Origin} for the given {@link PropertySource} and
* {@code propertyName}. Will either return an {@link OriginLookup} result or a
* {@link PropertySourceOrigin}.
* @param propertySource the origin property source
* @param name the property name
* @return the property origin
*/
public static Origin get(PropertySource<?> propertySource, String name) {
Origin origin = OriginLookup.getOrigin(propertySource, name);
return (origin instanceof PropertySourceOrigin) ? origin
: new PropertySourceOrigin(propertySource, name, origin);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\PropertySourceOrigin.java | 1 |
请完成以下Java代码 | public JobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
public JobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
} | public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java | 1 |
请完成以下Java代码 | public class GroupDetails implements Group, Serializable {
private static final long serialVersionUID = 1L;
protected final String id;
protected final String name;
protected final String type;
protected GroupDetails(String id, String name, String type) {
this.id = id;
this.name = name;
this.type = type;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
// Not supported
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
// Not supported
}
@Override
public String getType() {
return type;
} | @Override
public void setType(String string) {
// Not supported
}
public static GroupDetails create(Group group) {
return new GroupDetails(group.getId(), group.getName(), group.getType());
}
public static List<GroupDetails> create(List<Group> groups) {
List<GroupDetails> groupDetails = new ArrayList<>(groups.size());
for (Group group : groups) {
groupDetails.add(create(group));
}
return groupDetails;
}
} | repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\GroupDetails.java | 1 |
请完成以下Java代码 | public final class Cache implements TreeCache {
private final ConcurrentMap<String, Tree> map;
private final ConcurrentLinkedQueue<String> queue;
private final AtomicInteger size;
private final int capacity;
/**
* Creates a new cache with the specified capacity
* and default concurrency level (16).
*
* @param capacity
* Cache size. The actual size may exceed it temporarily.
*/
public Cache(int capacity) {
this(capacity, 16);
}
/**
* Creates a new cache with the specified capacity and concurrency level.
*
* @param capacity
* Cache size. The actual map size may exceed it temporarily.
* @param concurrencyLevel
* The estimated number of concurrently updating threads. The
* implementation performs internal sizing to try to accommodate
* this many threads.
*/
public Cache(int capacity, int concurrencyLevel) {
this.map = new ConcurrentHashMap<String, Tree>(16, 0.75f, concurrencyLevel);
this.queue = new ConcurrentLinkedQueue<String>();
this.size = new AtomicInteger();
this.capacity = capacity;
}
public int size() {
return size.get(); | }
public Tree get(String expression) {
return map.get(expression);
}
public void put(String expression, Tree tree) {
if (map.putIfAbsent(expression, tree) == null) {
queue.offer(expression);
if (size.incrementAndGet() > capacity) {
size.decrementAndGet();
map.remove(queue.poll());
}
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Cache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(kerberosAuthenticationProvider())
.authenticationProvider(kerberosServiceAuthenticationProvider())
.build();
}
@Bean
public KerberosAuthenticationProvider kerberosAuthenticationProvider() {
KerberosAuthenticationProvider provider = new KerberosAuthenticationProvider();
SunJaasKerberosClient client = new SunJaasKerberosClient();
client.setDebug(true);
provider.setKerberosClient(client);
provider.setUserDetailsService(dummyUserDetailsService());
return provider;
}
@Bean
public SpnegoEntryPoint spnegoEntryPoint() {
return new SpnegoEntryPoint("/login");
}
@Bean
public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(AuthenticationManager authenticationManager) {
SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter();
filter.setAuthenticationManager(authenticationManager);
return filter;
}
@Bean
public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() {
KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider();
provider.setTicketValidator(sunJaasKerberosTicketValidator());
provider.setUserDetailsService(dummyUserDetailsService()); | return provider;
}
@Bean
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
ticketValidator.setServicePrincipal("HTTP/demo.kerberos.bealdung.com@baeldung.com");
ticketValidator.setKeyTabLocation(new FileSystemResource("baeldung.keytab"));
ticketValidator.setDebug(true);
return ticketValidator;
}
@Bean
public DummyUserDetailsService dummyUserDetailsService() {
return new DummyUserDetailsService();
}
} | repos\tutorials-master\spring-security-modules\spring-security-oauth2-sso\spring-security-sso-kerberos\src\main\java\com\baeldung\intro\config\WebSecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult create(@RequestBody List<SmsHomeRecommendSubject> homeRecommendSubjectList) {
int count = recommendSubjectService.create(homeRecommendSubjectList);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改专题推荐排序")
@RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateSort(@PathVariable Long id, Integer sort) {
int count = recommendSubjectService.updateSort(id, sort);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("批量删除专题推荐")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = recommendSubjectService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("批量修改专题推荐状态") | @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) {
int count = recommendSubjectService.updateRecommendStatus(ids, recommendStatus);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("分页查询专题推荐")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsHomeRecommendSubject>> list(@RequestParam(value = "subjectName", required = false) String subjectName,
@RequestParam(value = "recommendStatus", required = false) Integer recommendStatus,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsHomeRecommendSubject> homeRecommendSubjectList = recommendSubjectService.list(subjectName, recommendStatus, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(homeRecommendSubjectList));
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeRecommendSubjectController.java | 2 |
请完成以下Java代码 | public class Content {
private String body;
private boolean approved;
private List<String> tags;
@JsonCreator
public Content(
@JsonProperty("body") String body,
@JsonProperty("approved") boolean approved,
@JsonProperty("tags") List<String> tags
) {
this.body = body;
this.approved = approved;
this.tags = tags;
if (this.tags == null) {
this.tags = new ArrayList<>();
}
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body; | }
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Content{" + "body='" + body + '\'' + ", approved=" + approved + ", tags=" + tags + '}';
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-full-example-bean\src\main\java\org\activiti\examples\Content.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handleEvent(@NonNull final ForecastCreatedEvent event)
{
final Forecast forecast = event.getForecast();
final CandidateBuilder candidateBuilder = Candidate.builderForEventDescriptor(event.getEventDescriptor())
//.status(EventUtil.getCandidateStatus(forecast.getDocStatus()))
.type(CandidateType.STOCK_UP)
.businessCase(CandidateBusinessCase.FORECAST);
for (final ForecastLine forecastLine : forecast.getForecastLines())
{
complementBuilderFromForecastLine(candidateBuilder, forecast, forecastLine);
final Candidate demandCandidate = candidateBuilder.build();
candidateChangeHandler.onCandidateNewOrChange(demandCandidate); | }
}
private void complementBuilderFromForecastLine(
@NonNull final CandidateBuilder candidateBuilder,
@NonNull final Forecast forecast,
@NonNull final ForecastLine forecastLine)
{
candidateBuilder
.materialDescriptor(forecastLine.getMaterialDescriptor())
.businessCaseDetail(DemandDetail.forForecastLineId(
forecastLine.getForecastLineId(),
forecast.getForecastId(),
forecastLine.getMaterialDescriptor().getQuantity()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\foreacast\ForecastCreatedHandler.java | 2 |
请完成以下Java代码 | public TypedValue execute(CommandContext commandContext) {
ensureNotNull("taskId", taskId);
ensureNotNull("variableName", variableName);
TaskEntity task = Context
.getCommandContext()
.getTaskManager()
.findTaskById(taskId);
ensureNotNull("task " + taskId + " doesn't exist", "task", task);
checkGetTaskVariableTyped(task, commandContext);
TypedValue value; | if (isLocal) {
value = task.getVariableLocalTyped(variableName, deserializeValue);
} else {
value = task.getVariableTyped(variableName, deserializeValue);
}
return value;
}
protected void checkGetTaskVariableTyped(TaskEntity task, CommandContext commandContext) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkReadTaskVariable(task);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetTaskVariableCmdTyped.java | 1 |
请完成以下Java代码 | public class JMHStreamReduceBenchMark {
private final List<User> userList = createUsers();
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
private List<User> createUsers() {
List<User> users = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
users.add(new User("John" + i, i));
}
return users;
} | @Benchmark
public Integer executeReduceOnParallelizedStream() {
return this.userList
.parallelStream()
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
@Benchmark
public Integer executeReduceOnSequentialStream() {
return this.userList
.stream()
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
} | repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\reduce\benchmarks\JMHStreamReduceBenchMark.java | 1 |
请完成以下Java代码 | public class AppHandler implements Handler {
private static final Logger LOGGER = Logger.getLogger(AppHandler.class.getSimpleName());
private GraphQL graphql;
public AppHandler() throws Exception {
GraphQLSchema schema = SchemaParser.newParser()
.resolvers(new Query(), new ProductResolver())
.scalars(ExtendedScalars.Json)
.file("schema.graphqls")
.build()
.makeExecutableSchema();
graphql = GraphQL.newGraphQL(schema).build();
}
@Override
public void handle(Context context) throws Exception {
context.parse(Map.class) | .then(payload -> {
ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY)
.toString(), null, this, Collections.emptyMap());
Map<String, Object> result = new LinkedHashMap<>();
if (executionResult.getErrors()
.isEmpty()) {
result.put(SchemaUtils.DATA, executionResult.getData());
} else {
result.put(SchemaUtils.ERRORS, executionResult.getErrors());
LOGGER.warning("Errors: " + executionResult.getErrors());
}
context.render(json(result));
});
}
} | repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlreturnmap\AppHandler.java | 1 |
请完成以下Java代码 | public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Candidate getPP_Order_Candidate()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class);
}
@Override
public void setPP_Order_Candidate(final org.eevolution.model.I_PP_Order_Candidate PP_Order_Candidate)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class, PP_Order_Candidate);
}
@Override
public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID)
{
if (PP_Order_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID);
}
@Override
public int getPP_Order_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID);
}
@Override
public void setPP_OrderLine_Candidate_ID (final int PP_OrderLine_Candidate_ID)
{
if (PP_OrderLine_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, PP_OrderLine_Candidate_ID);
}
@Override
public int getPP_OrderLine_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_OrderLine_Candidate_ID);
} | @Override
public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class);
}
@Override
public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine);
}
@Override
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID)
{
if (PP_Product_BOMLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID);
}
@Override
public int getPP_Product_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java | 1 |
请完成以下Java代码 | public class OrdersAggregator extends MapReduceAggregator<OrderHeaderAggregation, PurchaseCandidate>
{
public static final OrdersAggregator newInstance(final IOrdersCollector collector)
{
return new OrdersAggregator(collector);
}
private final IOrdersCollector collector;
private OrdersAggregator(final IOrdersCollector collector)
{
super();
this.collector = collector;
setItemAggregationKeyBuilder(new IAggregationKeyBuilder<PurchaseCandidate>()
{
@Override
public String buildKey(final PurchaseCandidate item)
{
return item.getHeaderAggregationKey().toString();
}
@Override
public boolean isSame(final PurchaseCandidate item1, final PurchaseCandidate item2)
{
throw new UnsupportedOperationException(); // shall not be called
}
@Override
public List<String> getDependsOnColumnNames()
{
throw new UnsupportedOperationException(); // shall not be called
}
});
} | @Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
protected OrderHeaderAggregation createGroup(final Object itemHashKey, final PurchaseCandidate candidate)
{
return new OrderHeaderAggregation();
}
@Override
protected void closeGroup(final OrderHeaderAggregation orderHeader)
{
I_C_Order order = orderHeader.build();
if (order != null)
{
collector.add(order);
}
}
@Override
protected void addItemToGroup(final OrderHeaderAggregation orderHeader, final PurchaseCandidate candidate)
{
orderHeader.add(candidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrdersAggregator.java | 1 |
请完成以下Java代码 | private void changeLane(final int boardId, final int cardId, final int newLaneId)
{
final int countUpdate = Services.get(IQueryBL.class)
.createQueryBuilder(I_WEBUI_Board_RecordAssignment.class)
.addEqualsFilter(I_WEBUI_Board_RecordAssignment.COLUMN_WEBUI_Board_ID, boardId)
.addEqualsFilter(I_WEBUI_Board_RecordAssignment.COLUMN_Record_ID, cardId)
.create()
.updateDirectly()
.addSetColumnValue(I_WEBUI_Board_RecordAssignment.COLUMNNAME_WEBUI_Board_Lane_ID, newLaneId)
.execute();
if (countUpdate <= 0)
{
throw new AdempiereException("Card it's not part this Board")
.setParameter("boardId", boardId)
.setParameter("cardId", cardId);
}
}
@EqualsAndHashCode
@ToString
private static final class LaneCardsSequence
{
private final int laneId;
private final List<Integer> cardIds;
public LaneCardsSequence(final int laneId, final List<Integer> cardIds)
{
this.laneId = laneId;
this.cardIds = new ArrayList<>(cardIds);
}
public LaneCardsSequence copy()
{
return new LaneCardsSequence(laneId, cardIds);
}
public int getLaneId()
{
return laneId;
}
private List<Integer> getCardIds()
{
return cardIds;
} | public void addCardIdAtPosition(final int cardId, final int position)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
if (position < 0)
{
cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
else if (position == Integer.MAX_VALUE || position > cardIds.size() - 1)
{
cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
else
{
cardIds.remove((Object)cardId);
cardIds.add(position, cardId);
}
}
public void removeCardId(final int cardId)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
cardIds.remove((Object)cardId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardDescriptorRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getGlobalAcquireLockPrefix() {
return globalAcquireLockPrefix;
}
public void setGlobalAcquireLockPrefix(String globalAcquireLockPrefix) {
this.globalAcquireLockPrefix = globalAcquireLockPrefix;
}
public Duration getAsyncJobsGlobalLockWaitTime() {
return asyncJobsGlobalLockWaitTime;
}
public void setAsyncJobsGlobalLockWaitTime(Duration asyncJobsGlobalLockWaitTime) {
this.asyncJobsGlobalLockWaitTime = asyncJobsGlobalLockWaitTime;
}
public Duration getAsyncJobsGlobalLockPollRate() {
return asyncJobsGlobalLockPollRate;
}
public void setAsyncJobsGlobalLockPollRate(Duration asyncJobsGlobalLockPollRate) {
this.asyncJobsGlobalLockPollRate = asyncJobsGlobalLockPollRate;
}
public Duration getAsyncJobsGlobalLockForceAcquireAfter() {
return asyncJobsGlobalLockForceAcquireAfter;
}
public void setAsyncJobsGlobalLockForceAcquireAfter(Duration asyncJobsGlobalLockForceAcquireAfter) {
this.asyncJobsGlobalLockForceAcquireAfter = asyncJobsGlobalLockForceAcquireAfter;
}
public Duration getTimerLockWaitTime() {
return timerLockWaitTime;
}
public void setTimerLockWaitTime(Duration timerLockWaitTime) {
this.timerLockWaitTime = timerLockWaitTime;
}
public Duration getTimerLockPollRate() {
return timerLockPollRate;
}
public void setTimerLockPollRate(Duration timerLockPollRate) {
this.timerLockPollRate = timerLockPollRate;
} | public Duration getTimerLockForceAcquireAfter() {
return timerLockForceAcquireAfter;
}
public void setTimerLockForceAcquireAfter(Duration timerLockForceAcquireAfter) {
this.timerLockForceAcquireAfter = timerLockForceAcquireAfter;
}
public Duration getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(Duration resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobExecutorConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
private Map<Long, User> userMap = new HashMap<>();
@GetMapping("/v1/users/{userId}")
public Mono<ResponseEntity<User>> getV1UserById(@PathVariable Long userId) {
return Mono.fromCallable(() -> {
User user = userMap.get(userId);
if (user == null) {
throw new UserNotFoundException("User not found with ID: " + userId);
}
return new ResponseEntity<>(user, HttpStatus.OK);
});
}
@GetMapping("/v2/users/{userId}")
public Mono<ResponseEntity<User>> getV2UserById(@PathVariable Long userId) {
return Mono.fromCallable(() -> { | User user = userMap.get(userId);
if (user == null) {
CustomErrorResponse customErrorResponse = CustomErrorResponse
.builder()
.traceId(UUID.randomUUID().toString())
.timestamp(OffsetDateTime.now().now())
.status(HttpStatus.NOT_FOUND)
.errors(List.of(ErrorDetails.API_USER_NOT_FOUND))
.build();
throw new CustomErrorException("User not found", customErrorResponse);
}
return new ResponseEntity<>(user, HttpStatus.OK);
});
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-exceptions\src\main\java\com\baeldung\spring\reactive\customexception\controller\UserController.java | 2 |
请完成以下Java代码 | public Optional<BPartnerId> getBPartnerId(@NonNull final OrderAndLineId orderLineId)
{
final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId);
return BPartnerId.optionalOfRepoId(orderLine.getC_BPartner_ID());
}
@Override
public void setTax(@NonNull final org.compiere.model.I_C_OrderLine orderLine)
{
final I_C_Order orderRecord = orderBL().getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
final TaxCategoryId taxCategoryId = getTaxCategoryId(orderLine);
final WarehouseId warehouseId = warehouseAdvisor.evaluateWarehouse(orderLine);
final CountryId countryFromId = warehouseBL.getCountryId(warehouseId);
final BPartnerLocationAndCaptureId bpLocationId = OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).getBPartnerLocationAndCaptureId();
final boolean isSOTrx = orderRecord.isSOTrx();
final Timestamp taxDate = orderLine.getDatePromised();
final BPartnerId effectiveBillPartnerId = orderBL().getEffectiveBillPartnerId(orderRecord);
// if we set the tax for a sales order, consider whether the customer is exempt from taxes
final Boolean isTaxExempt;
if (isSOTrx && effectiveBillPartnerId != null)
{
final I_C_BPartner billBPartnerRecord = bpartnerDAO.getById(effectiveBillPartnerId);
// Only set if TRUE - otherwise leave null (don't filter)
isTaxExempt = billBPartnerRecord.isTaxExempt() ? Boolean.TRUE : null;
}
else
{ | isTaxExempt = null;
}
final Tax tax = taxDAO.getBy(TaxQuery.builder()
.fromCountryId(countryFromId)
.orgId(OrgId.ofRepoId(orderLine.getAD_Org_ID()))
.bPartnerLocationId(bpLocationId)
.warehouseId(warehouseId)
.dateOfInterest(taxDate)
.taxCategoryId(taxCategoryId)
.soTrx(SOTrx.ofBoolean(isSOTrx))
.isTaxExempt(isTaxExempt)
.build());
if (tax == null)
{
TaxNotFoundException.builder()
.taxCategoryId(taxCategoryId)
.isSOTrx(isSOTrx)
.isTaxExempt(isTaxExempt)
.billDate(taxDate)
.billFromCountryId(countryFromId)
.billToC_Location_ID(bpLocationId.getLocationCaptureId())
.build()
.throwOrLogWarning(true, logger);
}
orderLine.setC_Tax_ID(tax.getTaxId().getRepoId());
orderLine.setC_TaxCategory_ID(tax.getTaxCategoryId().getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLineBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setParametersConsumer(Consumer<LogoutRequestParameters> parametersConsumer) {
Assert.notNull(parametersConsumer, "parametersConsumer cannot be null");
this.delegate
.setParametersConsumer((parameters) -> parametersConsumer.accept(new LogoutRequestParameters(parameters)));
}
/**
* Use this {@link Clock} for determining the issued {@link Instant}
* @param clock the {@link Clock} to use
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock must not be null");
this.delegate.setClock(clock);
}
/**
* Use this {@link Converter} to compute the RelayState
* @param relayStateResolver the {@link Converter} to use
* @since 6.1
*/
public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) {
Assert.notNull(relayStateResolver, "relayStateResolver cannot be null");
this.delegate.setRelayStateResolver(relayStateResolver);
}
public static final class LogoutRequestParameters {
private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final Authentication authentication;
private final LogoutRequest logoutRequest; | public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration,
Authentication authentication, LogoutRequest logoutRequest) {
this.request = request;
this.registration = registration;
this.authentication = authentication;
this.logoutRequest = logoutRequest;
}
LogoutRequestParameters(BaseOpenSamlLogoutRequestResolver.LogoutRequestParameters parameters) {
this(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthentication(),
parameters.getLogoutRequest());
}
public HttpServletRequest getRequest() {
return this.request;
}
public RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
public Authentication getAuthentication() {
return this.authentication;
}
public LogoutRequest getLogoutRequest() {
return this.logoutRequest;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolver.java | 2 |
请完成以下Java代码 | public class PartOfSpeechTagDictionary
{
/**
* 词性映射表
*/
public static Map<String, String> translator = new TreeMap<String, String>();
static
{
load(HanLP.Config.PartOfSpeechTagDictionary);
}
public static void load(String path)
{
IOUtil.LineIterator iterator = new IOUtil.LineIterator(path);
iterator.next(); // header
while (iterator.hasNext())
{
String[] args = iterator.next().split(","); | if (args.length < 3) continue;
translator.put(args[1], args[2]);
}
}
/**
* 翻译词性
*
* @param tag
* @return
*/
public static String translate(String tag)
{
String cn = translator.get(tag);
if (cn == null) return tag;
return cn;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\other\PartOfSpeechTagDictionary.java | 1 |
请完成以下Java代码 | public PMMContractBuilder addQtyPlanned(final Date date, final BigDecimal qtyPlannedToAdd)
{
assertNotProcessed();
if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0)
{
return this;
}
if (qtyPlannedToAdd.signum() < 0)
{
logger.warn("Skip adding negative QtyPlanned={} for {}", qtyPlannedToAdd, date);
return this;
}
Check.assumeNotNull(date, "date not null");
final Timestamp day = TimeUtil.trunc(date, TimeUtil.TRUNC_DAY);
DailyFlatrateDataEntry entry = _flatrateDataEntriesByDay.get(day);
if (entry == null)
{
entry = DailyFlatrateDataEntry.of(day);
_flatrateDataEntriesByDay.put(day, entry);
}
entry.addQtyPlanned(qtyPlannedToAdd);
return this;
}
private BigDecimal allocateQtyPlannedForPeriod(final I_C_Period period)
{
BigDecimal qtySum = null;
for (final DailyFlatrateDataEntry entry : _flatrateDataEntriesByDay.values())
{
final Date day = entry.getDay();
if (!periodBL.isInPeriod(period, day))
{
continue;
}
final BigDecimal qty = entry.allocateQtyPlanned();
if (qtySum == null)
{
qtySum = qty;
}
else
{
qtySum = qtySum.add(qty);
}
}
return qtySum;
}
private void assertDailyFlatrateDataEntriesAreFullyAllocated(final I_C_Flatrate_Term contract)
{
for (final DailyFlatrateDataEntry entry : _flatrateDataEntriesByDay.values())
{
if (!entry.isFullyAllocated())
{
throw new AdempiereException("Daily entry shall be fully allocated: " + entry
+ "\n Contract period: " + contract.getStartDate() + "->" + contract.getEndDate());
}
}
}
private static final class DailyFlatrateDataEntry
{
public static DailyFlatrateDataEntry of(final Date day)
{
return new DailyFlatrateDataEntry(day);
}
private final Date day;
private BigDecimal qtyPlanned = BigDecimal.ZERO;
private BigDecimal qtyPlannedAllocated = BigDecimal.ZERO;
private DailyFlatrateDataEntry(final Date day)
{
super();
Check.assumeNotNull(day, "day not null");
this.day = day;
} | @Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("day", day)
.add("qtyPlanned", qtyPlanned)
.add("qtyPlannedAllocated", qtyPlannedAllocated)
.toString();
}
public Date getDay()
{
return day;
}
public void addQtyPlanned(final BigDecimal qtyPlannedToAdd)
{
if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0)
{
return;
}
qtyPlanned = qtyPlanned.add(qtyPlannedToAdd);
}
public BigDecimal allocateQtyPlanned()
{
final BigDecimal qtyPlannedToAllocate = qtyPlanned.subtract(qtyPlannedAllocated);
qtyPlannedAllocated = qtyPlanned;
return qtyPlannedToAllocate;
}
public boolean isFullyAllocated()
{
return qtyPlannedAllocated.compareTo(qtyPlanned) == 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\PMMContractBuilder.java | 1 |
请完成以下Java代码 | public Optional<Account> getProductCategoryAccount(
final @NonNull AcctSchemaId acctSchemaId,
final @NonNull ProductCategoryId productCategoryId,
final @NonNull ProductAcctType acctType)
{
if (extension != null)
{
final Optional<Account> account = extension.getProductCategoryAccount(acctSchemaId, productCategoryId, acctType);
if (account.isPresent())
{
return account;
}
}
return productCategoryAccountsRepository.getAccounts(productCategoryId, acctSchemaId)
.map(accounts -> accounts.getAccount(acctType));
}
@NonNull
public Account getTaxAccount(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final TaxId taxId,
@NonNull final TaxAcctType acctType)
{
return getTaxAccounts(acctSchemaId, taxId)
.getAccount(acctType)
.orElseThrow(() -> new AdempiereException("Tax account not set: " + acctType + ", " + taxId + ", " + acctSchemaId));
}
@NonNull
public TaxAccounts getTaxAccounts(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final TaxId taxId)
{
return taxAccountsRepository.getAccounts(taxId, acctSchemaId);
}
@NonNull
public Account getProductAccount(
@NonNull final AcctSchemaId acctSchemaId,
@Nullable final ProductId productId,
@Nullable final TaxId taxId,
@NonNull final ProductAcctType acctType)
{
if (extension != null)
{
final Account account = extension.getProductAccount(acctSchemaId, productId, acctType).orElse(null);
if (account != null)
{
return account;
}
} | //
// Product Revenue: check/use the override defined on tax level
if (acctType == ProductAcctType.P_Revenue_Acct && taxId != null)
{
final Account productRevenueAcct = taxAccountsRepository.getAccounts(taxId, acctSchemaId)
.getT_Revenue_Acct()
.orElse(null);
if (productRevenueAcct != null)
{
return productRevenueAcct;
}
}
if (productId == null)
{
return productCategoryAccountsRepository
.getAccounts(productBL.getDefaultProductCategoryId(), acctSchemaId)
.map(accounts -> accounts.getAccount(acctType))
.orElseThrow(() -> newPostingException().setDetailMessage("No Default Account for account type: " + acctType));
}
else
{
return productAccountsRepository.getAccounts(productId, acctSchemaId).getAccount(acctType);
}
}
public Account getCostElementAccount(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final CostElementId costElementId,
@NonNull final CostElementAccountType acctType)
{
final AccountId accountId = costElementAccountsRepository
.getAccounts(costElementId, acctSchemaId)
.getAccountId(acctType);
return Account.of(accountId, acctType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\AccountProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final BookRepository bookRepository;
private final AuthorRepository authorRepository;
public BookstoreService(BookRepository bookRepository, AuthorRepository authorRepository) {
this.bookRepository = bookRepository;
this.authorRepository = authorRepository;
}
@Transactional
public void persistAuthorsAndBooks() {
Author at = new Author();
at.setName("Alicia Tom");
at.setGenre("Anthology");
at.setAge(38);
at.setEmail("alicia.tom@gmail.com");
Author jn = new Author();
jn.setName("Joana Nimar");
jn.setGenre("History");
jn.setAge(34);
jn.setEmail("joana.nimar@gmail.com");
Book atb1 = new Book();
atb1.setTitle("Anthology of a day");
atb1.setIsbn("AT-001");
Book atb2 = new Book();
atb2.setTitle("Anthology gaps");
atb2.setIsbn("AT-002");
Book jnb1 = new Book();
jnb1.setTitle("History of Prague");
jnb1.setIsbn("JN-001");
atb1.setAuthor(at);
atb2.setAuthor(at); | jnb1.setAuthor(jn);
authorRepository.save(at);
authorRepository.save(jn);
bookRepository.save(atb1);
bookRepository.save(atb2);
bookRepository.save(jnb1);
}
@Transactional(readOnly = true)
public void fetchBookWithAuthor() {
Book book = bookRepository.findByTitle("Anthology gaps");
Author author = book.getAuthor();
System.out.println(book);
System.out.println(author);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootReferenceNaturalId\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public boolean hasActivationRule() {
return StringUtils.isNotEmpty(activateCondition);
}
public boolean hasIgnoreRule() {
return StringUtils.isNotEmpty(ignoreCondition);
}
public boolean hasDefaultRule() {
return StringUtils.isNotEmpty(defaultCondition);
}
public boolean hasActivationCondition() {
return hasActivationRule() && (activateCondition.contains("#") || activateCondition.contains("$"));
}
public boolean hasIgnoreCondition() {
return hasIgnoreRule() && (ignoreCondition.contains("#") || ignoreCondition.contains("$"));
}
public boolean hasDefaultCondition() {
return hasDefaultRule() && (defaultCondition.contains("#") || defaultCondition.contains("$"));
}
public String getDefaultCondition() {
return defaultCondition;
}
public void setDefaultCondition(String defaultCondition) {
this.defaultCondition = defaultCondition;
}
public String getActivateCondition() {
return activateCondition;
}
public void setActivateCondition(String activateCondition) {
this.activateCondition = activateCondition;
} | public String getIgnoreCondition() {
return ignoreCondition;
}
public void setIgnoreCondition(String ignoreCondition) {
this.ignoreCondition = ignoreCondition;
}
@Override
public String toString() {
return "ReactivationRule{} " + super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReactivationRule that = (ReactivationRule) o;
return Objects.equals(activateCondition, that.activateCondition) && Objects.equals(ignoreCondition, that.ignoreCondition)
&& Objects.equals(defaultCondition, that.defaultCondition);
}
@Override
public int hashCode() {
return Objects.hash(activateCondition, ignoreCondition, defaultCondition);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ReactivationRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmptyCollectionType implements VariableType {
public static final String TYPE_NAME = "emptyCollection";
private static final String SET = "set";
private static final String LIST = "list";
private static final Class<?> EMPTY_LIST_CLASS = Collections.emptyList().getClass();
private static final Class<?> EMPTY_SET_CLASS = Collections.emptySet().getClass();
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public boolean isAbleToStore(Object value) {
if (value instanceof Collection) {
return EMPTY_LIST_CLASS.isInstance(value) || EMPTY_SET_CLASS.isInstance(value);
}
return false;
}
@Override | public void setValue(Object value, ValueFields valueFields) {
if (EMPTY_LIST_CLASS.isInstance(value)) {
valueFields.setTextValue("list");
} else {
valueFields.setTextValue("set");
}
}
@Override
public Object getValue(ValueFields valueFields) {
String value = valueFields.getTextValue();
if (LIST.equals(value)) {
return Collections.emptyList();
} else if (SET.equals(value)) {
return Collections.emptySet();
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EmptyCollectionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JwtMappingProperties {
private String authoritiesPrefix;
private String authoritiesClaimName;
private String principalClaimName;
private Map<String,String> scopes;
public String getAuthoritiesClaimName() {
return authoritiesClaimName;
}
public void setAuthoritiesClaimName(String authoritiesClaimName) {
this.authoritiesClaimName = authoritiesClaimName;
}
public String getAuthoritiesPrefix() {
return authoritiesPrefix;
}
public void setAuthoritiesPrefix(String authoritiesPrefix) {
this.authoritiesPrefix = authoritiesPrefix;
}
public String getPrincipalClaimName() {
return principalClaimName; | }
public void setPrincipalClaimName(String principalClaimName) {
this.principalClaimName = principalClaimName;
}
public Map<String,String> getScopes() {
return scopes;
}
public void setScopes(Map<String,String> scopes) {
this.scopes = scopes;
}
} | repos\tutorials-master\spring-security-modules\spring-security-oidc\src\main\java\com\baeldung\openid\oidc\jwtauthorities\config\JwtMappingProperties.java | 2 |
请完成以下Java代码 | public void deleteChildEntity(CommandContext commandContext, DelegatePlanItemInstance delegatePlanItemInstance, boolean cascade) {
if (ReferenceTypes.PLAN_ITEM_CHILD_PROCESS.equals(delegatePlanItemInstance.getReferenceType())) {
delegatePlanItemInstance.setState(PlanItemInstanceState.TERMINATED); // This is not the regular termination, but the state still needs to be correct
deleteProcessInstance(commandContext, delegatePlanItemInstance);
} else {
throw new FlowableException("Can only delete a child entity for a plan item with reference type " + ReferenceTypes.PLAN_ITEM_CHILD_PROCESS + " for " + delegatePlanItemInstance);
}
}
protected void handleOutParameters(DelegatePlanItemInstance planItemInstance,
CaseInstanceEntity caseInstance,
ProcessInstanceService processInstanceService) {
if (outParameters == null) {
return;
}
for (IOParameter outParameter : outParameters) {
String variableName = null;
if (StringUtils.isNotEmpty(outParameter.getTarget())) {
variableName = outParameter.getTarget();
} else if (StringUtils.isNotEmpty(outParameter.getTargetExpression())) {
Object variableNameValue = processInstanceService.resolveExpression(planItemInstance.getReferenceId(), outParameter.getTargetExpression());
if (variableNameValue != null) {
variableName = variableNameValue.toString();
} else {
LOGGER.warn("Out parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error",
outParameter.getTargetExpression());
}
} | Object variableValue = null;
if (StringUtils.isNotEmpty(outParameter.getSourceExpression())) {
variableValue = processInstanceService.resolveExpression(planItemInstance.getReferenceId(), outParameter.getSourceExpression());
} else if (StringUtils.isNotEmpty(outParameter.getSource())) {
variableValue = processInstanceService.getVariable(planItemInstance.getReferenceId(), outParameter.getSource());
}
planItemInstance.setVariable(variableName, variableValue);
}
}
protected String getParentDeploymentIfSameDeployment(CmmnEngineConfiguration cmmnEngineConfiguration, PlanItemInstanceEntity planItemInstanceEntity) {
if (!sameDeployment) {
// If not same deployment then return null
// Parent deployment should not be taken into consideration then
return null;
} else {
return CaseDefinitionUtil.getDefinitionDeploymentId(planItemInstanceEntity.getCaseDefinitionId(), cmmnEngineConfiguration);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\ProcessTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public String getProfilePictureUrl() {
return this.profilePictureUrl;
}
public User getUser() {
return this.user;
}
public void setId(Long id) {
this.id = id;
}
public void setBiography(String biography) {
this.biography = biography;
}
public void setWebsite(String website) {
this.website = website;
}
public void setProfilePictureUrl(String profilePictureUrl) {
this.profilePictureUrl = profilePictureUrl;
}
public void setUser(User user) {
this.user = user;
}
@Override | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Profile profile = (Profile) o;
return Objects.equals(id, profile.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "Profile(id=" + this.getId() + ", biography=" + this.getBiography() + ", website=" + this.getWebsite()
+ ", profilePictureUrl=" + this.getProfilePictureUrl() + ", user=" + this.getUser() + ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Profile.java | 1 |
请完成以下Java代码 | public class SPKIDataType {
@XmlElementRef(name = "SPKISexp", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class)
@XmlAnyElement(lax = true)
protected List<Object> spkiSexpAndAny;
/**
* Gets the value of the spkiSexpAndAny 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 spkiSexpAndAny property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSPKISexpAndAny().add(newItem);
* </pre>
*
*
* <p> | * Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link byte[]}{@code >}
* {@link Element }
* {@link Object }
*
*
*/
public List<Object> getSPKISexpAndAny() {
if (spkiSexpAndAny == null) {
spkiSexpAndAny = new ArrayList<Object>();
}
return this.spkiSexpAndAny;
}
} | 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\SPKIDataType.java | 1 |
请完成以下Java代码 | public void setAuthenticatedUserId(String authenticatedUserId) {
Authentication.setAuthenticatedUserId(authenticatedUserId);
}
@Override
public String getUserInfo(String userId, String key) {
return getIdmIdentityService().getUserInfo(userId, key);
}
@Override
public List<String> getUserInfoKeys(String userId) {
return getIdmIdentityService().getUserInfoKeys(userId);
}
@Override
public void setUserInfo(String userId, String key, String value) { | getIdmIdentityService().setUserInfo(userId, key, value);
}
@Override
public void deleteUserInfo(String userId, String key) {
getIdmIdentityService().deleteUserInfo(userId, key);
}
protected IdmIdentityService getIdmIdentityService() {
IdmIdentityService idmIdentityService = EngineServiceUtil.getIdmIdentityService(configuration);
if (idmIdentityService == null) {
throw new FlowableException("Trying to use idm identity service when it is not initialized");
}
return idmIdentityService;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\IdentityServiceImpl.java | 1 |
请完成以下Java代码 | public static boolean isExpression(String text) {
if (text == null) {
return false;
}
text = text.trim();
return text.startsWith("${") || text.startsWith("#{");
}
/**
* Splits a String by an expression.
*
* @param text the text to split
* @param regex the regex to split by
* @return the parts of the text or null if text was null
*/
public static String[] split(String text, String regex) {
if (text == null) {
return null;
}
else if (regex == null) {
return new String[] { text };
}
else {
String[] result = text.split(regex);
for (int i = 0; i < result.length; i++) {
result[i] = result[i].trim();
}
return result;
}
}
/**
* Joins a list of Strings to a single one.
*
* @param delimiter the delimiter between the joined parts
* @param parts the parts to join
* @return the joined String or null if parts was null
*/
public static String join(String delimiter, String... parts) {
if (parts == null) {
return null;
}
if (delimiter == null) {
delimiter = "";
} | StringBuilder stringBuilder = new StringBuilder();
for (int i=0; i < parts.length; i++) {
if (i > 0) {
stringBuilder.append(delimiter);
}
stringBuilder.append(parts[i]);
}
return stringBuilder.toString();
}
/**
* Returns either the passed in String, or if the String is <code>null</code>, an empty String ("").
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @param text the String to check, may be null
* @return the passed in String, or the empty String if it was <code>null</code>
*/
public static String defaultString(String text) {
return text == null ? "" : text;
}
/**
* Fetches the stack trace of an exception as a String.
*
* @param throwable to get the stack trace from
* @return the stack trace as String
*/
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw, true));
return sw.toString();
}
} | repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\StringUtil.java | 1 |
请完成以下Java代码 | private Entry<String, List<String>> getHeaderEntry(int n) {
Iterator<Entry<String, List<String>>> iterator = getHeaderFields().entrySet().iterator();
Entry<String, List<String>> entry = null;
for (int i = 0; i < n; i++) {
entry = (!iterator.hasNext()) ? null : iterator.next();
}
return entry;
}
@Override
public Map<String, List<String>> getHeaderFields() {
try {
connect();
}
catch (IOException ex) {
return Collections.emptyMap();
}
Map<String, List<String>> headerFields = this.headerFields;
if (headerFields == null) {
headerFields = new LinkedHashMap<>();
long contentLength = getContentLengthLong();
long lastModified = getLastModified();
if (contentLength > 0) {
headerFields.put("content-length", List.of(String.valueOf(contentLength)));
}
if (getLastModified() > 0) {
headerFields.put("last-modified",
List.of(RFC_1123_DATE_TIME.format(Instant.ofEpochMilli(lastModified))));
}
headerFields = Collections.unmodifiableMap(headerFields);
this.headerFields = headerFields;
}
return headerFields;
}
@Override
public int getContentLength() {
long contentLength = getContentLengthLong();
return (contentLength <= Integer.MAX_VALUE) ? (int) contentLength : -1;
}
@Override
public long getContentLengthLong() {
try {
connect();
return this.resources.getContentLength();
}
catch (IOException ex) {
return -1;
}
}
@Override
public String getContentType() {
return CONTENT_TYPE;
}
@Override
public long getLastModified() {
if (this.lastModified == -1) {
try {
this.lastModified = Files.getLastModifiedTime(this.resources.getLocation().path()).toMillis();
}
catch (IOException ex) {
this.lastModified = 0;
}
}
return this.lastModified;
}
@Override
public Permission getPermission() throws IOException {
if (this.permission == null) {
File file = this.resources.getLocation().path().toFile();
this.permission = new FilePermission(file.getCanonicalPath(), "read");
}
return this.permission;
}
@Override
public InputStream getInputStream() throws IOException { | connect();
return new ConnectionInputStream(this.resources.getInputStream());
}
@Override
public void connect() throws IOException {
if (this.connected) {
return;
}
this.resources.connect();
this.connected = true;
}
/**
* Connection {@link InputStream}.
*/
class ConnectionInputStream extends FilterInputStream {
private volatile boolean closing;
ConnectionInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
if (this.closing) {
return;
}
this.closing = true;
try {
super.close();
}
finally {
try {
NestedUrlConnection.this.cleanup.clean();
}
catch (UncheckedIOException ex) {
throw ex.getCause();
}
}
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnection.java | 1 |
请完成以下Java代码 | public ExecutionEntity getProcessInstance() {
if ((processInstance == null) && (processInstanceId != null)) {
this.processInstance = Context.getCommandContext().getExecutionEntityManager().findById(processInstanceId);
}
return processInstance;
}
public void setProcessInstance(ExecutionEntity processInstance) {
this.processInstance = processInstance;
this.processInstanceId = processInstance.getId();
}
public ProcessDefinitionEntity getProcessDef() {
if ((processDef == null) && (processDefId != null)) {
this.processDef = Context.getCommandContext().getProcessDefinitionEntityManager().findById(processDefId);
}
return processDef;
}
public void setProcessDef(ProcessDefinitionEntity processDef) {
this.processDef = processDef;
this.processDefId = processDef.getId();
}
@Override
public String getProcessDefinitionId() {
return this.processDefId;
}
public void setDetails(byte[] details) {
this.details = details;
}
public byte[] getDetails() {
return this.details;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) { | sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
if (details != null) {
sb.append(", details=").append(new String(details));
}
sb.append("]");
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityImpl.java | 1 |
请完成以下Java代码 | public class SetExternalTaskRetriesCmd extends ExternalTaskCmd {
protected int retries;
protected boolean writeUserOperationLog;
public SetExternalTaskRetriesCmd(String externalTaskId, int retries, boolean writeUserOperationLog) {
super(externalTaskId);
this.retries = retries;
this.writeUserOperationLog = writeUserOperationLog;
}
@Override
protected void validateInput() {
EnsureUtil.ensureGreaterThanOrEqual(BadUserRequestException.class, "The number of retries cannot be negative", "retries", retries, 0);
}
@Override
protected void execute(ExternalTaskEntity externalTask) {
externalTask.setRetriesAndManageIncidents(retries);
} | @Override
protected String getUserOperationLogOperationType() {
if (writeUserOperationLog) {
return UserOperationLogEntry.OPERATION_TYPE_SET_EXTERNAL_TASK_RETRIES;
}
return super.getUserOperationLogOperationType();
}
@Override
protected List<PropertyChange> getUserOperationLogPropertyChanges(ExternalTaskEntity externalTask) {
if (writeUserOperationLog) {
return Collections.singletonList(new PropertyChange("retries", externalTask.getRetries(), retries));
}
return super.getUserOperationLogPropertyChanges(externalTask);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetExternalTaskRetriesCmd.java | 1 |
请完成以下Java代码 | public CaseSentryPartQueryImpl satisfied() {
this.satisfied = true;
return this;
}
// order by ///////////////////////////////////////////
public CaseSentryPartQueryImpl orderByCaseSentryId() {
orderBy(CaseSentryPartQueryProperty.CASE_SENTRY_PART_ID);
return this;
}
public CaseSentryPartQueryImpl orderByCaseInstanceId() {
orderBy(CaseSentryPartQueryProperty.CASE_INSTANCE_ID);
return this;
}
public CaseSentryPartQueryImpl orderByCaseExecutionId() {
orderBy(CaseSentryPartQueryProperty.CASE_EXECUTION_ID);
return this;
}
public CaseSentryPartQueryImpl orderBySentryId() {
orderBy(CaseSentryPartQueryProperty.SENTRY_ID);
return this;
}
public CaseSentryPartQueryImpl orderBySource() {
orderBy(CaseSentryPartQueryProperty.SOURCE);
return this;
}
// results ////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getCaseSentryPartManager()
.findCaseSentryPartCountByQueryCriteria(this);
}
public List<CaseSentryPartEntity> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
List<CaseSentryPartEntity> result = commandContext
.getCaseSentryPartManager()
.findCaseSentryPartByQueryCriteria(this, page);
return result;
}
// getters /////////////////////////////////////////////
public String getId() {
return id;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() { | return caseExecutionId;
}
public String getSentryId() {
return sentryId;
}
public String getType() {
return type;
}
public String getSourceCaseExecutionId() {
return sourceCaseExecutionId;
}
public String getStandardEvent() {
return standardEvent;
}
public String getVariableEvent() {
return variableEvent;
}
public String getVariableName() {
return variableName;
}
public boolean isSatisfied() {
return satisfied;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartQueryImpl.java | 1 |
请完成以下Java代码 | public BalanceType5Choice getCdOrPrtry() {
return cdOrPrtry;
}
/**
* Sets the value of the cdOrPrtry property.
*
* @param value
* allowed object is
* {@link BalanceType5Choice }
*
*/
public void setCdOrPrtry(BalanceType5Choice value) {
this.cdOrPrtry = value;
}
/**
* Gets the value of the subTp property.
*
* @return
* possible object is | * {@link BalanceSubType1Choice }
*
*/
public BalanceSubType1Choice getSubTp() {
return subTp;
}
/**
* Sets the value of the subTp property.
*
* @param value
* allowed object is
* {@link BalanceSubType1Choice }
*
*/
public void setSubTp(BalanceSubType1Choice value) {
this.subTp = 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\BalanceType12.java | 1 |
请完成以下Java代码 | public RoleId getFirstRoleId()
{
getRecipients(false);
for (int i = 0; i < m_recipients.length; i++)
{
if (m_recipients[i].getAD_Role_ID() >= 0)
{
return RoleId.ofRepoId(m_recipients[i].getAD_Role_ID());
}
}
return null;
} // getForstAD_Role_ID
/**
* Get First User Role if exist
* @return AD_Role_ID or -1
*/
public RoleId getFirstUserRoleId()
{
getRecipients(false);
final UserId userId = UserId.ofRepoIdOrNull(getFirstAD_User_ID());
if (userId != null)
{
final RoleId firstRoleId = Services.get(IRoleDAO.class).retrieveFirstRoleIdForUserId(userId);
return firstRoleId;
}
return null;
} // getFirstUserAD_Role_ID
/**
* Get First User if exist
* @return AD_User_ID or -1
*/
public int getFirstAD_User_ID()
{
getRecipients(false);
for (int i = 0; i < m_recipients.length; i++)
{
if (m_recipients[i].getAD_User_ID() != -1)
return m_recipients[i].getAD_User_ID();
}
return -1;
} // getFirstAD_User_ID
/**
* @return unique list of recipient users
*/
public Set<UserId> getRecipientUsers() {
MAlertRecipient[] recipients = getRecipients(false);
TreeSet<UserId> users = new TreeSet<>();
for (int i = 0; i < recipients.length; i++)
{
MAlertRecipient recipient = recipients[i];
if (recipient.getAD_User_ID() >= 0) // System == 0
{
users.add(UserId.ofRepoId(recipient.getAD_User_ID()));
}
final RoleId roleId = RoleId.ofRepoIdOrNull(recipient.getAD_Role_ID());
if (roleId != null) // SystemAdministrator == 0 | {
final Set<UserId> allRoleUserIds = Services.get(IRoleDAO.class).retrieveUserIdsForRoleId(roleId);
users.addAll(allRoleUserIds);
}
}
return users;
}
/**
* String Representation
* @return info
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlert[");
sb.append(get_ID())
.append("-").append(getName())
.append(",Valid=").append(isValid());
if (m_rules != null)
sb.append(",Rules=").append(m_rules.length);
if (m_recipients != null)
sb.append(",Recipients=").append(m_recipients.length);
sb.append ("]");
return sb.toString ();
} // toString
} // MAlert | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlert.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderProcessingListeners {
private static final Logger logger = LoggerFactory.getLogger(OrderProcessingListeners.class);
private final InventoryService inventoryService;
private final OrderService orderService;
public OrderProcessingListeners(InventoryService inventoryService, OrderService orderService) {
this.inventoryService = inventoryService;
this.orderService = orderService;
}
@SqsListener(value = "${events.queues.order-processing-retry-queue}", id = "retry-order-processing-container", messageVisibilitySeconds = "1")
public void stockCheckRetry(OrderCreatedEvent orderCreatedEvent) {
logger.info("Message received: {}", orderCreatedEvent);
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING);
inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity());
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED);
logger.info("Message processed successfully: {}", orderCreatedEvent);
}
@SqsListener(value = "${events.queues.order-processing-async-queue}", acknowledgementMode = SqsListenerAcknowledgementMode.MANUAL, id = "async-order-processing-container", messageVisibilitySeconds = "3")
public void slowStockCheckAsynchronous(OrderCreatedEvent orderCreatedEvent, Acknowledgement acknowledgement) {
logger.info("Message received: {}", orderCreatedEvent);
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSING);
CompletableFuture.runAsync(() -> inventoryService.slowCheckInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity()))
.thenRun(() -> orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.PROCESSED))
.thenCompose(voidFuture -> acknowledgement.acknowledgeAsync())
.thenRun(() -> logger.info("Message for order {} acknowledged", orderCreatedEvent.id())); | logger.info("Releasing processing thread.");
}
@SqsListener(value = "${events.queues.order-processing-no-retries-queue}", acknowledgementMode = "${events.acknowledgment.order-processing-no-retries-queue}", id = "no-retries-order-processing-container", messageVisibilitySeconds = "3")
public void stockCheckNoRetries(OrderCreatedEvent orderCreatedEvent) {
logger.info("Message received: {}", orderCreatedEvent);
// Fire and forget scenario where we're not interested on the outcome, e.g. a sales event with limited inventory.
orderService.updateOrderStatus(orderCreatedEvent.id(), OrderStatus.RECEIVED);
inventoryService.checkInventory(orderCreatedEvent.productId(), orderCreatedEvent.quantity());
logger.info("Message processed: {}", orderCreatedEvent);
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\acknowledgement\listener\OrderProcessingListeners.java | 2 |
请完成以下Java代码 | public void setField(GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* Action Listener Interface
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
// m_text.addActionListener(listener);
} // addActionListener
/**
* Action Listener - start dialog
* @param e Event
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (!m_button.isEnabled())
return;
throw new AdempiereException("legacy feature removed");
}
/**
* Property Change Listener
* @param evt event
*/
@Override | public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
@Override
public boolean isAutoCommit()
{
return true;
}
} // VAssignment | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAssignment.java | 1 |
请完成以下Java代码 | public void mouseClicked(MouseEvent e)
{
if (!(e.getSource() instanceof VTable))
{
return;
}
//
m_vtable = (VTable)e.getSource();
final int rowIndexView = m_vtable.rowAtPoint(e.getPoint());
final int columnIndexView = m_vtable.columnAtPoint(e.getPoint());
final TableCellRenderer r = m_vtable.getCellRenderer(rowIndexView, columnIndexView);
if (!(r instanceof VCellRenderer))
return;
//
m_gridTable = null;
int displayType = -1;
if (m_vtable.getModel() instanceof GridTable)
{
final int columnIndexModel = m_vtable.getColumnModel().getColumn(columnIndexView).getModelIndex();
m_gridTable = (GridTable)m_vtable.getModel();
m_columnName = m_gridTable.getColumnName(columnIndexModel);
final GridField field = m_gridTable.getGridTab().getField(m_columnName);
displayType = field.getDisplayType();
}
if (e.getClickCount() >= 2)
{
// metas: Temp. Ausschalten des Zooms bei Doppelclick
// actionZoom();
// metas end
return;
}
final boolean showPopup = SwingUtilities.isRightMouseButton(e);
if (showPopup)
{
contextPopupMenu = getContextMenu(m_vtable.getCellEditor(rowIndexView, columnIndexView), rowIndexView, columnIndexView);
if (null == contextPopupMenu)
{
return;
}
contextPopupMenu.show(m_vtable.getComponentAt(e.getPoint()), e.getX(), e.getY());
return;
}
// Make sure context menu is not displayed
if (contextPopupMenu != null)
{
contextPopupMenu.setVisible(false);
contextPopupMenu = null;
}
if (DisplayType.isText(displayType))
{
editCellAt(e); | return;
}
}
private Component editCellAt(MouseEvent e)
{
if (m_vtable == null)
{
return null;
}
final Point p = e.getPoint();
final boolean canEdit = !m_vtable.isEditing() || m_vtable.getCellEditor().stopCellEditing();
if (canEdit && m_vtable.editCellAt(m_vtable.rowAtPoint(p), m_vtable.columnAtPoint(p)))
{
Component editor = m_vtable.getEditorComponent();
editor.dispatchEvent(e);
return editor;
}
return null;
}
private EditorContextPopupMenu getContextMenu(final TableCellEditor cellEditor, final int rowIndexView, final int columnIndexView)
{
if (m_vtable == null)
{
// VTable not set yet ?!
return null;
}
final Object value = m_vtable.getValueAt(rowIndexView, columnIndexView);
final Component component = cellEditor.getTableCellEditorComponent(m_vtable, value, true, rowIndexView, columnIndexView); // isSelected=true
if (component == null)
{
// It seems there is no editor for given cell (e.g. one reason could be the cell is not actually displayed)
return null;
}
if (!(component instanceof VEditor))
{
return null;
}
final VEditor editor = (VEditor)component;
final IContextMenuActionContext menuCtx = Services.get(IContextMenuProvider.class).createContext(editor, m_vtable, rowIndexView, columnIndexView);
final EditorContextPopupMenu contextMenu = new EditorContextPopupMenu(menuCtx);
return contextMenu;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VTableMouseListener.java | 1 |
请完成以下Java代码 | public class WebController {
private static final int DEFAULT_PORT = 8080;
public static final String SLOW_SERVICE_PRODUCTS_ENDPOINT_NAME = "/slow-service-products";
@Setter
private int serverPort = DEFAULT_PORT;
@Autowired
private ProductsFeignClient productsFeignClient;
@GetMapping("/products-blocking")
public List<Product> getProductsBlocking() {
log.info("Starting BLOCKING Controller!");
final URI uri = URI.create(getSlowServiceBaseUri());
List<Product> result = productsFeignClient.getProductsBlocking(uri);
result.forEach(product -> log.info(product.toString()));
log.info("Exiting BLOCKING Controller!");
return result;
} | @GetMapping(value = "/products-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Product> getProductsNonBlocking() {
log.info("Starting NON-BLOCKING Controller!");
Flux<Product> productFlux = WebClient.create()
.get()
.uri(getSlowServiceBaseUri() + SLOW_SERVICE_PRODUCTS_ENDPOINT_NAME)
.retrieve()
.bodyToFlux(Product.class);
productFlux.subscribe(product -> log.info(product.toString()));
log.info("Exiting NON-BLOCKING Controller!");
return productFlux;
}
private String getSlowServiceBaseUri() {
return "http://localhost:" + serverPort;
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\WebController.java | 1 |
请完成以下Java代码 | public DocumentId getId()
{
return id;
}
@Override
public AttachmentEntryType getType()
{
return AttachmentEntryType.Data;
}
@Override
public String getFilename()
{
final String contentType = getContentType();
final String fileExtension = MimeType.getExtensionByType(contentType);
final String name = archive.getName();
return FileUtil.changeFileExtension(name, fileExtension);
}
@Override
public byte[] getData()
{
return archiveBL.getBinaryData(archive);
}
@Override | public String getContentType()
{
return archiveBL.getContentType(archive);
}
@Override
public URI getUrl()
{
return null;
}
@Override
public Instant getCreated()
{
return archive.getCreated().toInstant();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentArchiveEntry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AccountConfigUtil {
private static final Log LOG = LogFactory.getLog(AccountConfigUtil.class);
/**
* 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例)
*/
private static Properties properties = new Properties();
private AccountConfigUtil() {
}
// 通过类装载器装载进来
static {
try {
// 从类路径下读取属性文件
properties.load(AccountConfigUtil.class.getClassLoader()
.getResourceAsStream("account_config.properties"));
} catch (IOException e) { | LOG.error(e);
}
}
/**
* 函数功能说明 :读取配置项 Administrator 2012-12-14 修改者名字 : 修改日期 : 修改内容 :
*
* @参数:
* @return void
* @throws
*/
public static String readConfig(String key) {
return (String) properties.get(key);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\utils\AccountConfigUtil.java | 2 |
请完成以下Java代码 | public class LogMDC {
public static final String LOG_MDC_PROCESSDEFINITION_ID = "mdcProcessDefinitionID";
public static final String LOG_MDC_EXECUTION_ID = "mdcExecutionId";
public static final String LOG_MDC_PROCESSINSTANCE_ID = "mdcProcessInstanceID";
public static final String LOG_MDC_BUSINESS_KEY = "mdcBusinessKey";
public static final String LOG_MDC_TASK_ID = "mdcTaskId";
static boolean enabled;
public static boolean isMDCEnabled() {
return enabled;
}
public static void setMDCEnabled(boolean b) {
enabled = b;
}
public static void putMDCExecution(ExecutionEntity e) {
if (e.getId() != null) {
MDC.put(LOG_MDC_EXECUTION_ID, e.getId()); | }
if (e.getProcessDefinitionId() != null) {
MDC.put(LOG_MDC_PROCESSDEFINITION_ID, e.getProcessDefinitionId());
}
if (e.getProcessInstanceId() != null) {
MDC.put(LOG_MDC_PROCESSINSTANCE_ID, e.getProcessInstanceId());
}
if (e.getProcessInstanceBusinessKey() != null) {
MDC.put(LOG_MDC_BUSINESS_KEY, e.getProcessInstanceBusinessKey());
}
}
public static void clear() {
MDC.clear();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\logging\LogMDC.java | 1 |
请完成以下Java代码 | public final boolean isCloseOnCompletion() throws SQLException
{
return getStatementImpl().isCloseOnCompletion();
}
@Override
public final String getSql()
{
return this.vo.getSql();
}
protected final String convertSqlAndSet(final String sql)
{
final String sqlConverted = DB.getDatabase().convertStatement(sql);
vo.setSql(sqlConverted);
MigrationScriptFileLoggerHolder.logMigrationScript(sql);
return sqlConverted;
}
@Override
public final void commit() throws SQLException
{
if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit())
{
this.ownedConnection.commit();
} | }
@Nullable
private static Trx getTrx(@NonNull final CStatementVO vo)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final String trxName = vo.getTrxName();
if (trxManager.isNull(trxName))
{
return (Trx)ITrx.TRX_None;
}
else
{
final ITrx trx = trxManager.get(trxName, false); // createNew=false
// NOTE: we assume trx if of type Trx because we need to invoke getConnection()
return (Trx)trx;
}
}
@Override
public String toString()
{
return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java | 1 |
请完成以下Java代码 | protected TaskEntityManager getTaskManager() {
return getSession(TaskEntityManager.class);
}
protected IdentityLinkEntityManager getIdentityLinkManager() {
return getSession(IdentityLinkEntityManager.class);
}
protected EventSubscriptionEntityManager getEventSubscriptionManager() {
return (getSession(EventSubscriptionEntityManager.class));
}
protected VariableInstanceEntityManager getVariableInstanceManager() {
return getSession(VariableInstanceEntityManager.class);
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceManager() {
return getSession(HistoricProcessInstanceEntityManager.class);
}
protected HistoricDetailEntityManager getHistoricDetailManager() {
return getSession(HistoricDetailEntityManager.class);
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
} | protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
protected AttachmentEntityManager getAttachmentManager() {
return getSession(AttachmentEntityManager.class);
}
protected HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
@Override
public void close() {
}
@Override
public void flush() {
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public @Nullable LibraryScope getScope() {
return this.scope;
}
/**
* Return the {@linkplain LibraryCoordinates coordinates} of the library.
* @return the coordinates
*/
public @Nullable LibraryCoordinates getCoordinates() {
return this.coordinates;
}
/**
* Return if the file cannot be used directly as a nested jar and needs to be
* unpacked.
* @return if unpack is required
*/
public boolean isUnpackRequired() {
return this.unpackRequired;
}
long getLastModified() {
Assert.state(this.file != null, "'file' must not be null");
return this.file.lastModified(); | }
/**
* Return if the library is local (part of the same build) to the application that is
* being packaged.
* @return if the library is local
*/
public boolean isLocal() {
return this.local;
}
/**
* Return if the library is included in the uber jar.
* @return if the library is included
*/
public boolean isIncluded() {
return this.included;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Library.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getREFERENCEDATE1() {
return referencedate1;
}
/**
* Sets the value of the referencedate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE1(String value) {
this.referencedate1 = value;
}
/**
* Gets the value of the referencedate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE2() {
return referencedate2; | }
/**
* Sets the value of the referencedate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE2(String value) {
this.referencedate2 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DREFE1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ImageClassificationController {
private final ImageClassificationService imageClassificationService;
@PostMapping(path = "/analyze")
public String predict(@RequestPart("image") MultipartFile image,
@RequestParam(defaultValue = "/home/djl-test/models") String modePath)
throws TranslateException,
MalformedModelException,
IOException {
return imageClassificationService.predict(image, modePath);
}
@PostMapping(path = "/training")
public String training(@RequestParam(defaultValue = "/home/djl-test/images-test")
String datasetRoot,
@RequestParam(defaultValue = "/home/djl-test/models") String modePath) throws TranslateException, IOException {
return imageClassificationService.training(datasetRoot, modePath);
}
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam(defaultValue = "/home/djl-test/images-test") String directoryPath) {
List<String> imgPathList = new ArrayList<>();
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
// Filter only regular files (excluding directories)
paths.filter(Files::isRegularFile)
.forEach(c-> imgPathList.add(c.toString()));
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
Random random = new Random();
String filePath = imgPathList.get(random.nextInt(imgPathList.size()));
Path file = Paths.get(filePath);
Resource resource = new FileSystemResource(file.toFile());
if (!resource.exists()) { | return ResponseEntity.notFound().build();
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFileName().toString());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
try {
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.body(resource);
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
}
} | repos\springboot-demo-master\djl\src\main\java\com\et\controller\ImageClassificationController.java | 2 |
请完成以下Java代码 | class ModelCacheSourceModel implements ICacheSourceModel
{
private final Object model;
ModelCacheSourceModel(@NonNull final Object model)
{
this.model = model;
}
@Override
public String getTableName()
{
return InterfaceWrapperHelper.getModelTableName(model);
}
@Override
public int getRecordId()
{
return InterfaceWrapperHelper.getId(model);
}
@Override | public TableRecordReference getRootRecordReferenceOrNull()
{
return null;
}
@Override
public Integer getValueAsInt(final String columnName, final Integer defaultValue)
{
final Object valueObj = InterfaceWrapperHelper.getValueOrNull(model, columnName);
return NumberUtils.asInteger(valueObj, defaultValue);
}
@Override
public boolean isValueChanged(final String columnName)
{
return InterfaceWrapperHelper.isValueChanged(model, columnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ModelCacheSourceModel.java | 1 |
请完成以下Java代码 | public static void processOutParameters(List<IOParameter> outParameters, VariableContainer sourceContainer, BiConsumer<String, Object> targetVariableConsumer,
BiConsumer<String, Object> targetTransientVariableConsumer, ExpressionManager expressionManager) {
processParameters(outParameters, sourceContainer, targetVariableConsumer, targetTransientVariableConsumer, expressionManager, "Out");
}
public static Map<String, Object> extractOutVariables(List<IOParameter> outParameters, VariableContainer sourceContainer, ExpressionManager expressionManager) {
if (outParameters == null || outParameters.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> payload = new HashMap<>();
processParameters(outParameters, sourceContainer, payload::put, payload::put, expressionManager, "Out");
return payload;
}
protected static void processParameters(List<IOParameter> parameters, VariableContainer sourceContainer, BiConsumer<String, Object> targetVariableConsumer,
BiConsumer<String, Object> targetTransientVariableConsumer, ExpressionManager expressionManager, String parameterType) {
if (parameters == null || parameters.isEmpty()) {
return;
}
for (IOParameter parameter : parameters) {
Object value;
if (StringUtils.isNotEmpty(parameter.getSourceExpression())) {
Expression expression = expressionManager.createExpression(parameter.getSourceExpression().trim());
value = expression.getValue(sourceContainer);
} else {
value = sourceContainer.getVariable(parameter.getSource());
} | if (value != null) {
value = JsonUtil.deepCopyIfJson(value);
}
String variableName = null;
if (StringUtils.isNotEmpty(parameter.getTargetExpression())) {
Expression expression = expressionManager.createExpression(parameter.getTargetExpression());
Object variableNameValue = expression.getValue(sourceContainer);
if (variableNameValue != null) {
variableName = variableNameValue.toString();
} else {
LOGGER.warn("{} parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error",
parameterType, parameter.getTargetExpression());
}
} else if (StringUtils.isNotEmpty(parameter.getTarget())){
variableName = parameter.getTarget();
}
if (parameter.isTransient()) {
targetTransientVariableConsumer.accept(variableName, value);
} else {
targetVariableConsumer.accept(variableName, value);
}
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\IOParameterUtil.java | 1 |
请完成以下Java代码 | private ImmutableMap<JsonExternalReferenceLookupItem, ExternalReferenceQuery> extractRepoQueries(
@NonNull final ImmutableSet<JsonExternalReferenceLookupItem> items,
@NonNull final OrgId orgId,
@NonNull final ExternalSystem externalSystem)
{
final ImmutableMap.Builder<JsonExternalReferenceLookupItem, ExternalReferenceQuery> item2Query = ImmutableMap.builder();
final ExternalReferenceQuery.ExternalReferenceQueryBuilder queryBuilder = ExternalReferenceQuery.builder()
.externalSystem(externalSystem);
for (final JsonExternalReferenceLookupItem item : items)
{
final IExternalReferenceType type = externalReferenceTypes.ofCode(item.getType())
.orElseThrow(() -> new InvalidIdentifierException("type", item));
queryBuilder
.orgId(orgId)
.externalReferenceType(type)
.externalReference(item.getId())
.metasfreshId(MetasfreshId.ofOrNull(item.getMetasfreshId()));
item2Query.put(item, queryBuilder.build());
}
return item2Query.build();
}
@NonNull
private JsonExternalReferenceLookupResponse createResponseFromRepoResult(
@NonNull final ImmutableMap<JsonExternalReferenceLookupItem, ExternalReferenceQuery> item2Query,
@NonNull final ExternalReferenceQueriesResult externalReferences)
{
final JsonExternalReferenceLookupResponse.JsonExternalReferenceLookupResponseBuilder result = JsonExternalReferenceLookupResponse.builder();
for (final Map.Entry<JsonExternalReferenceLookupItem, ExternalReferenceQuery> lookupItem2QueryEntry : item2Query.entrySet())
{
final JsonExternalReferenceLookupItem lookupItem = lookupItem2QueryEntry.getKey(); | final ExternalReference externalReference = externalReferences.get(lookupItem2QueryEntry.getValue()).orElse(null);
final JsonExternalReferenceItem responseItem;
if (externalReference == null)
{
responseItem = JsonExternalReferenceItem.of(lookupItem);
}
else
{
responseItem = JsonExternalReferenceItem.builder()
.lookupItem(lookupItem)
.metasfreshId(JsonMetasfreshId.of(externalReference.getRecordId()))
.externalReference(externalReference.getExternalReference())
.version(externalReference.getVersion())
.externalReferenceUrl(externalReference.getExternalReferenceUrl())
.systemName(JsonExternalSystemName.of(externalReference.getExternalSystem().getType().getValue()))
.externalReferenceId(JsonMetasfreshId.of(externalReference.getExternalReferenceId().getRepoId()))
.build();
}
result.item(responseItem);
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v2\ExternalReferenceRestControllerService.java | 1 |
请完成以下Java代码 | public void validateLine(final I_GL_DistributionLine line)
{
if (line.getLine() == 0)
{
final I_GL_Distribution glDistribution = line.getGL_Distribution();
final int lastLineNo = glDistributionDAO.retrieveLastLineNo(glDistribution);
final int lineNo = lastLineNo + 10;
line.setLine(lineNo);
}
// Reset not selected Overwrite
if (!line.isOverwriteAcct() && line.getAccount_ID() > 0)
{
line.setAccount_ID(0);
}
if (!line.isOverwriteActivity() && line.getC_Activity_ID() > 0)
{
line.setC_Activity_ID(-1);
}
if (!line.isOverwriteBPartner() && line.getC_BPartner_ID() > 0)
{
line.setC_BPartner_ID(-1);
}
if (!line.isOverwriteCampaign() && line.getC_Campaign_ID() > 0)
{
line.setC_Campaign(null);
}
if (!line.isOverwriteLocFrom() && line.getC_LocFrom_ID() > 0)
{
line.setC_LocFrom(null);
}
if (!line.isOverwriteLocTo() && line.getC_LocTo_ID() > 0)
{
line.setC_LocTo(null);
}
if (!line.isOverwriteOrg() && line.getOrg_ID() > 0)
{
line.setOrg_ID(-1);
}
if (!line.isOverwriteOrgTrx() && line.getAD_OrgTrx_ID() > 0)
{
line.setAD_OrgTrx_ID(-1);
}
if (!line.isOverwriteProduct() && line.getM_Product_ID() > 0)
{
line.setM_Product_ID(-1);
}
if (!line.isOverwriteProject() && line.getC_Project_ID() > 0)
{
line.setC_Project_ID(-1);
}
if (!line.isOverwriteSalesRegion() && line.getC_SalesRegion_ID() > 0)
{
line.setC_SalesRegion(null);
}
if (!line.isOverwriteUser1() && line.getUser1_ID() > 0)
{
line.setUser1(null);
}
if (!line.isOverwriteUser2() && line.getUser2_ID() > 0)
{
line.setUser2(null);
} | // Account Overwrite cannot be 0
if (line.isOverwriteAcct() && line.getAccount_ID() <= 0)
{
throw new FillMandatoryException(I_GL_DistributionLine.COLUMNNAME_Account_ID);
}
// Org Overwrite cannot be 0
if (line.isOverwriteOrg() && line.getOrg_ID() <= 0)
{
throw new FillMandatoryException(I_GL_DistributionLine.COLUMNNAME_Org_ID);
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void validateGLDistribution(final I_GL_DistributionLine line)
{
final I_GL_Distribution glDistribution = line.getGL_Distribution();
try
{
glDistributionBL.validate(glDistribution);
}
catch (final GLDistributionNotValidException e)
{
// NOTE: don't propagate the exception because we flagged the glDistribution as not valid, and we want to persist that.
logger.info("", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\GL_DistributionLine.java | 1 |
请完成以下Java代码 | public long findDeploymentCountByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) {
return dataManager.findDeploymentCountByQueryCriteria(deploymentQuery);
}
@Override
public List<DmnDeployment> findDeploymentsByQueryCriteria(DmnDeploymentQueryImpl deploymentQuery) {
return dataManager.findDeploymentsByQueryCriteria(deploymentQuery);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return dataManager.getDeploymentResourceNames(deploymentId);
}
@Override
public List<DmnDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDeploymentsByNativeQuery(parameterMap);
}
@Override | public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDeploymentCountByNativeQuery(parameterMap);
}
protected DmnResourceEntityManager getResourceEntityManager() {
return engineConfiguration.getResourceEntityManager();
}
protected HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() {
return engineConfiguration.getHistoricDecisionExecutionEntityManager();
}
protected DecisionEntityManager getDecisionTableEntityManager() {
return engineConfiguration.getDecisionEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DmnDeploymentEntityManagerImpl.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8097
servlet:
session:
timeout: 30
spring:
application:
name: roncoo-pay-app-reconciliation
logging:
config: classpath:logbac | k.xml
mybatis:
mapper-locations: classpath*:mybatis/mapper/**/*.xml | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
for (ProcessEnginePlugin plugin : plugins) {
plugin.postInit(processEngineConfiguration);
}
}
@Override
public void postProcessEngineBuild(ProcessEngine processEngine) {
for (ProcessEnginePlugin plugin : plugins) {
plugin.postProcessEngineBuild(processEngine);
}
}
/**
* Get all plugins.
*
* @return the configured plugins
*/
public List<ProcessEnginePlugin> getPlugins() { | return plugins;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + plugins;
}
private static List<ProcessEnginePlugin> toList(ProcessEnginePlugin plugin, ProcessEnginePlugin... additionalPlugins) {
final List<ProcessEnginePlugin> plugins = new ArrayList<ProcessEnginePlugin>();
plugins.add(plugin);
if (additionalPlugins != null && additionalPlugins.length > 0) {
plugins.addAll(Arrays.asList(additionalPlugins));
}
return plugins;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\CompositeProcessEnginePlugin.java | 1 |
请完成以下Java代码 | private ProcessPreconditionsResolution checkSingleLineSelectedWhichIsForeignCurrency(@NonNull final IProcessPreconditionsContext context)
{
final Set<TableRecordReference> bankStatemementLineRefs = context.getSelectedIncludedRecords();
if (bankStatemementLineRefs.size() != 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("a single line shall be selected");
}
final TableRecordReference bankStatemementLineRef = bankStatemementLineRefs.iterator().next();
final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(bankStatemementLineRef.getRecord_ID());
final I_C_BankStatementLine line = bankStatementBL.getLineById(bankStatementLineId);
final CurrencyId currencyId = CurrencyId.ofRepoId(line.getC_Currency_ID());
final CurrencyId baseCurrencyId = bankStatementBL.getBaseCurrencyId(line);
if (CurrencyId.equals(currencyId, baseCurrencyId))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("line is not in foreign currency");
}
return ProcessPreconditionsResolution.accept();
}
@Nullable
@Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_CurrencyRate.equals(parameter.getColumnName())) | {
return getSingleSelectedBankStatementLine().getCurrencyRate();
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected String doIt()
{
if (currencyRate == null || currencyRate.signum() == 0)
{
throw new FillMandatoryException("CurrencyRate");
}
bankStatementBL.changeCurrencyRate(getSingleSelectedBankStatementLineId(), currencyRate);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_ChangeCurrencyRate.java | 1 |
请完成以下Java代码 | private void addHeaderLine(final String labelText, final Component field)
{
if (labelText != null)
{
final Properties ctx = Env.getCtx();
final CLabel label = new CLabel(Services.get(IMsgBL.class).translate(ctx, labelText));
headerPanel.add(label, new GridBagConstraints(0, m_headerLine, 1, 1, 0.0,
0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 10, 0, 5), 0, 0));
}
headerPanel.add(field, new GridBagConstraints(1, m_headerLine, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 10), 1, 0));
//
m_headerLine++;
}
private int m_headerLine = 0;
private BoilerPlateContext attributes;
private boolean m_isPrinted = false;
private boolean m_isPressedOK = false;
private boolean m_isPrintOnOK = false;
/**
* Set Message
*/
public void setMessage(final String newMessage)
{
m_message = newMessage;
fMessage.setText(m_message);
fMessage.setCaretPosition(0);
} // setMessage
/**
* Get Message
*/
public String getMessage()
{
m_message = fMessage.getText();
return m_message;
} // getMessage
public void setAttributes(final BoilerPlateContext attributes)
{
this.attributes = attributes;
fMessage.setAttributes(attributes);
}
public BoilerPlateContext getAttributes()
{
return attributes;
}
/**
* Action Listener - Send email
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
try
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); | confirmPanel.getOKButton().setEnabled(false);
//
if (m_isPrintOnOK)
{
m_isPrinted = fMessage.print();
}
}
finally
{
confirmPanel.getOKButton().setEnabled(true);
setCursor(Cursor.getDefaultCursor());
}
// m_isPrinted = true;
m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
} // actionPerformed
public void setPrintOnOK(final boolean value)
{
m_isPrintOnOK = value;
}
public boolean isPressedOK()
{
return m_isPressedOK;
}
public boolean isPrinted()
{
return m_isPrinted;
}
public File getPDF()
{
return fMessage.getPDF(getTitle());
}
public RichTextEditor getRichTextEditor()
{
return fMessage;
}
} // Letter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\LetterDialog.java | 1 |
请完成以下Java代码 | public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getAuthorizationUserId() {
return authorizationUserId;
}
public String getProcDefId() {
return procDefId;
} | public String getEventSubscriptionName() {
return eventSubscriptionName;
}
public String getEventSubscriptionType() {
return eventSubscriptionType;
}
public ProcessDefinitionQueryImpl startableByUser(String userId) {
if (userId == null) {
throw new ActivitiIllegalArgumentException("userId is null");
}
this.authorizationUserId = userId;
return this;
}
public ProcessDefinitionQuery startableByGroups(List<String> groupIds) {
authorizationGroups = groupIds;
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | private int getPort(UriComponents uriComponents) {
int port = uriComponents.getPort();
if (port != -1) {
return port;
}
if ("https".equalsIgnoreCase(uriComponents.getScheme())) {
return 443;
}
return 80;
}
@Override
public @Nullable HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response) {
@Nullable SavedRequest saved = this.getRequest(request, response);
if (!this.matchesSavedRequest(request, saved)) {
this.logger.debug("saved request doesn't match");
return null;
}
this.removeRequest(request, response);
// we know that saved is non-null because matchesSavedRequest = true
return new SavedRequestAwareWrapper(Objects.requireNonNull(saved), request);
}
@Override
public void removeRequest(HttpServletRequest request, HttpServletResponse response) {
Cookie removeSavedRequestCookie = new Cookie(COOKIE_NAME, "");
removeSavedRequestCookie.setSecure(request.isSecure());
removeSavedRequestCookie.setHttpOnly(true);
removeSavedRequestCookie.setPath(getCookiePath(request));
removeSavedRequestCookie.setMaxAge(0);
response.addCookie(removeSavedRequestCookie);
}
private static String encodeCookie(String cookieValue) {
return Base64.getEncoder().encodeToString(cookieValue.getBytes());
}
private @Nullable String decodeCookie(String encodedCookieValue) {
try {
return new String(Base64.getDecoder().decode(encodedCookieValue.getBytes()));
}
catch (IllegalArgumentException ex) {
this.logger.debug("Failed decode cookie value " + encodedCookieValue);
return null;
}
}
private static String getCookiePath(HttpServletRequest request) {
String contextPath = request.getContextPath();
return (StringUtils.hasLength(contextPath)) ? contextPath : "/";
}
private boolean matchesSavedRequest(HttpServletRequest request, @Nullable SavedRequest savedRequest) {
if (savedRequest == null) {
return false;
} | String currentUrl = UrlUtils.buildFullRequestUrl(request);
return savedRequest.getRedirectUrl().equals(currentUrl);
}
/**
* Allows selective use of saved requests for a subset of requests. By default any
* request will be cached by the {@code saveRequest} method.
* <p>
* If set, only matching requests will be cached.
* @param requestMatcher a request matching strategy which defines which requests
* should be cached.
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher should not be null");
this.requestMatcher = requestMatcher;
}
/**
* Sets the {@link Consumer}, allowing customization of cookie.
* @param cookieCustomizer customize for cookie
* @since 6.4
*/
public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) {
Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null");
this.cookieCustomizer = cookieCustomizer;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\CookieRequestCache.java | 1 |
请完成以下Java代码 | public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFilterType() {
return filterType;
}
public void setFilterType(Integer filterType) {
this.filterType = filterType;
}
public Integer getSearchType() {
return searchType;
}
public void setSearchType(Integer searchType) {
this.searchType = searchType;
}
public Integer getRelatedStatus() {
return relatedStatus;
}
public void setRelatedStatus(Integer relatedStatus) {
this.relatedStatus = relatedStatus;
}
public Integer getHandAddStatus() {
return handAddStatus;
}
public void setHandAddStatus(Integer handAddStatus) {
this.handAddStatus = handAddStatus;
}
public Integer getType() {
return type;
} | public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId);
sb.append(", name=").append(name);
sb.append(", selectType=").append(selectType);
sb.append(", inputType=").append(inputType);
sb.append(", inputList=").append(inputList);
sb.append(", sort=").append(sort);
sb.append(", filterType=").append(filterType);
sb.append(", searchType=").append(searchType);
sb.append(", relatedStatus=").append(relatedStatus);
sb.append(", handAddStatus=").append(handAddStatus);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java | 1 |
请完成以下Java代码 | public static CRFModel loadTxt(String path)
{
return loadTxt(path, new CRFModel(new DoubleArrayTrie<FeatureFunction>()));
}
/**
* 加载CRF++模型<br>
* 如果存在缓存的话,优先读取缓存,否则读取txt,并且建立缓存
*
* @param path txt的路径,即使不存在.txt,只存在.bin,也应传入txt的路径,方法内部会自动加.bin后缀
* @return
*/
public static CRFModel load(String path)
{
CRFModel model = loadBin(path + BIN_EXT);
if (model != null) return model;
return loadTxt(path, new CRFModel(new DoubleArrayTrie<FeatureFunction>()));
}
/**
* 加载Bin形式的CRF++模型<br>
* 注意该Bin形式不是CRF++的二进制模型,而是HanLP由CRF++的文本模型转换过来的私有格式
*
* @param path
* @return
*/
public static CRFModel loadBin(String path)
{ | ByteArray byteArray = ByteArray.createByteArray(path);
if (byteArray == null) return null;
CRFModel model = new CRFModel();
if (model.load(byteArray)) return model;
return null;
}
/**
* 获取某个tag的ID
*
* @param tag
* @return
*/
public Integer getTagId(String tag)
{
return tag2id.get(tag);
}
public Map<String, Integer> getTag2id() {
return tag2id;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public boolean isOrActive() {
return orActive;
}
public boolean isUnassigned() {
return unassigned;
}
public boolean isNoDelegationState() {
return noDelegationState;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionKeyLike() {
return caseDefinitionKeyLike;
}
public String getCaseDefinitionKeyLikeIgnoreCase() {
return caseDefinitionKeyLikeIgnoreCase;
}
public Collection<String> getCaseDefinitionKeys() {
return caseDefinitionKeys;
}
public boolean isExcludeSubtasks() {
return excludeSubtasks;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
}
@Override
public List<Task> list() {
cachedCandidateGroups = null;
return super.list();
}
@Override
public List<Task> listPage(int firstResult, int maxResults) { | cachedCandidateGroups = null;
return super.listPage(firstResult, maxResults);
}
@Override
public long count() {
cachedCandidateGroups = null;
return super.count();
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups;
}
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java | 2 |
请完成以下Java代码 | private static List<DocumentPath> createSelectedIncludedDocumentPaths(final WindowId windowId, final String documentIdStr, final JSONSelectedIncludedTab selectedTab)
{
if (windowId == null || Check.isEmpty(documentIdStr, true) || selectedTab == null)
{
return ImmutableList.of();
}
final DocumentId documentId = DocumentId.of(documentIdStr);
final DetailId selectedTabId = DetailId.fromJson(selectedTab.getTabId());
return selectedTab.getRowIds()
.stream()
.map(DocumentId::of)
.map(rowId -> DocumentPath.includedDocumentPath(windowId, documentId, selectedTabId, rowId))
.collect(ImmutableList.toImmutableList());
}
public DocumentQueryOrderByList getViewOrderBys()
{
return JSONViewOrderBy.toDocumentQueryOrderByList(viewOrderBy);
} | @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@Data
public static final class JSONSelectedIncludedTab
{
@JsonProperty("tabId")
private final String tabId;
@JsonProperty("rowIds")
private final List<String> rowIds;
private JSONSelectedIncludedTab(@NonNull @JsonProperty("tabId") final String tabId, @JsonProperty("rowIds") final List<String> rowIds)
{
this.tabId = tabId;
this.rowIds = rowIds != null ? ImmutableList.copyOf(rowIds) : ImmutableList.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONCreateProcessInstanceRequest.java | 1 |
请完成以下Java代码 | public class MultipartConfigFactory {
private @Nullable String location;
private @Nullable DataSize maxFileSize;
private @Nullable DataSize maxRequestSize;
private @Nullable DataSize fileSizeThreshold;
/**
* Sets the directory location where files will be stored.
* @param location the location
*/
public void setLocation(@Nullable String location) {
this.location = location;
}
/**
* Sets the maximum {@link DataSize size} allowed for uploaded files.
* @param maxFileSize the maximum file size
*/
public void setMaxFileSize(@Nullable DataSize maxFileSize) {
this.maxFileSize = maxFileSize;
}
/**
* Sets the maximum {@link DataSize} allowed for multipart/form-data requests.
* @param maxRequestSize the maximum request size
*/
public void setMaxRequestSize(@Nullable DataSize maxRequestSize) {
this.maxRequestSize = maxRequestSize;
}
/**
* Sets the {@link DataSize size} threshold after which files will be written to disk.
* @param fileSizeThreshold the file size threshold
*/
public void setFileSizeThreshold(@Nullable DataSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
} | /**
* Create a new {@link MultipartConfigElement} instance.
* @return the multipart config element
*/
public MultipartConfigElement createMultipartConfig() {
long maxFileSizeBytes = convertToBytes(this.maxFileSize, -1);
long maxRequestSizeBytes = convertToBytes(this.maxRequestSize, -1);
long fileSizeThresholdBytes = convertToBytes(this.fileSizeThreshold, 0);
return new MultipartConfigElement(this.location, maxFileSizeBytes, maxRequestSizeBytes,
(int) fileSizeThresholdBytes);
}
/**
* Return the amount of bytes from the specified {@link DataSize size}. If the size is
* {@code null} or negative, returns {@code defaultValue}.
* @param size the data size to handle
* @param defaultValue the default value if the size is {@code null} or negative
* @return the amount of bytes to use
*/
private long convertToBytes(@Nullable DataSize size, int defaultValue) {
if (size != null && !size.isNegative()) {
return size.toBytes();
}
return defaultValue;
}
} | repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\MultipartConfigFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void insertAuthorWithBooks() {
Author jn = new Author();
jn.setName("Joana Nimar");
jn.setAge(34);
jn.setGenre("History");
Book jn01 = new Book();
jn01.setIsbn("001-JN");
jn01.setTitle("A History of Ancient Prague");
Book jn02 = new Book();
jn02.setIsbn("002-JN");
jn02.setTitle("A People's History");
Book jn03 = new Book();
jn03.setIsbn("003-JN");
jn03.setTitle("World History");
jn.addBook(jn01);
jn.addBook(jn02);
jn.addBook(jn03);
authorRepository.save(jn);
}
@Transactional
public void insertNewBook() {
Author author = authorRepository.fetchByName("Joana Nimar"); | Book book = new Book();
book.setIsbn("004-JN");
book.setTitle("History Details");
author.addBook(book); // use addBook() helper
authorRepository.save(author);
}
@Transactional
public void deleteLastBook() {
Author author = authorRepository.fetchByName("Joana Nimar");
List<Book> books = author.getBooks();
author.removeBook(books.get(books.size() - 1));
}
@Transactional
public void deleteFirstBook() {
Author author = authorRepository.fetchByName("Joana Nimar");
List<Book> books = author.getBooks();
author.removeBook(books.get(0));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOneToManyUnidirectional\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public void setLoginDate (final @Nullable java.sql.Timestamp LoginDate)
{
set_Value (COLUMNNAME_LoginDate, LoginDate);
}
@Override
public java.sql.Timestamp getLoginDate()
{
return get_ValueAsTimestamp(COLUMNNAME_LoginDate);
}
@Override
public void setLoginUsername (final @Nullable java.lang.String LoginUsername)
{
set_Value (COLUMNNAME_LoginUsername, LoginUsername);
}
@Override
public java.lang.String getLoginUsername()
{
return get_ValueAsString(COLUMNNAME_LoginUsername);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setRemote_Addr (final @Nullable java.lang.String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
@Override
public java.lang.String getRemote_Addr()
{
return get_ValueAsString(COLUMNNAME_Remote_Addr);
} | @Override
public void setRemote_Host (final @Nullable java.lang.String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
@Override
public java.lang.String getRemote_Host()
{
return get_ValueAsString(COLUMNNAME_Remote_Host);
}
@Override
public void setWebSession (final @Nullable java.lang.String WebSession)
{
set_ValueNoCheck (COLUMNNAME_WebSession, WebSession);
}
@Override
public java.lang.String getWebSession()
{
return get_ValueAsString(COLUMNNAME_WebSession);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Session.java | 1 |
请完成以下Java代码 | public String getCategory() {
throw new UnsupportedOperationException();
}
@Override
public CamundaFormDefinitionEntity getPreviousDefinition() {
throw new UnsupportedOperationException();
}
@Override
public void setCategory(String category) {
throw new UnsupportedOperationException();
}
@Override
public String getDiagramResourceName() {
throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms");
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms");
}
@Override
public Integer getHistoryTimeToLive() {
throw new UnsupportedOperationException("history time to live not supported for Camunda Forms");
}
@Override
public void setHistoryTimeToLive(Integer historyTimeToLive) { | throw new UnsupportedOperationException("history time to live not supported for Camunda Forms");
}
@Override
public Object getPersistentState() {
// properties of this entity are immutable
return CamundaFormDefinitionEntity.class;
}
@Override
public void updateModifiableFieldsFromEntity(CamundaFormDefinitionEntity updatingDefinition) {
throw new UnsupportedOperationException("properties of Camunda Form Definitions are immutable");
}
@Override
public String getName() {
throw new UnsupportedOperationException("name property not supported for Camunda Forms");
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException("name property not supported for Camunda Forms");
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CamundaFormDefinitionEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QueryStringController {
@GetMapping("/api/byGetQueryString")
public String byGetQueryString(HttpServletRequest request) {
return request.getQueryString();
}
@GetMapping("/api/byGetParameter")
public String byGetParameter(HttpServletRequest request) {
String username = request.getParameter("username");
return "username:" + username;
}
@GetMapping("/api/byGetParameterValues")
public String byGetParameterValues(HttpServletRequest request) {
String[] roles = request.getParameterValues("roles");
return "roles:" + Arrays.toString(roles);
}
@GetMapping("/api/byGetParameterMap")
public UserDto byGetParameterMap(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
String[] usernames = parameterMap.get("username");
String[] roles = parameterMap.get("roles");
UserDto userDto = new UserDto();
userDto.setUsername(usernames[0]);
userDto.setRoles(Arrays.asList(roles));
return userDto;
} | @GetMapping("/api/byParameterName")
public UserDto byParameterName(String username, String[] roles) {
UserDto userDto = new UserDto();
userDto.setUsername(username);
userDto.setRoles(Arrays.asList(roles));
return userDto;
}
@GetMapping("/api/byAnnoRequestParam")
public UserDto byAnnoRequestParam(@RequestParam("username") String var1, @RequestParam("roles") List<String> var2) {
UserDto userDto = new UserDto();
userDto.setUsername(var1);
userDto.setRoles(var2);
return userDto;
}
@GetMapping("/api/byPojo")
public UserDto byPojo(UserDto userDto) {
return userDto;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-6\src\main\java\com\baeldung\requestparam\QueryStringController.java | 2 |
请完成以下Java代码 | private void throwExceptionIfEmptyResult(
final List<PurchaseItem> remotePurchaseItems,
final Collection<PurchaseCandidate> purchaseCandidatesWithVendorId,
final BPartnerId vendorId)
{
if (remotePurchaseItems.isEmpty())
{
final I_C_BPartner vendor = Services.get(IBPartnerDAO.class).getById(vendorId);
throw new AdempiereException(
MSG_NO_REMOTE_PURCHASE_ORDER_WAS_PLACED,
vendor.getValue(), vendor.getName())
.appendParametersToMessage()
.setParameter("purchaseCandidatesWithVendorId", purchaseCandidatesWithVendorId);
}
}
private void throwExceptionIfErrorItemsExist(
final List<PurchaseItem> remotePurchaseItems,
final Collection<PurchaseCandidate> purchaseCandidatesWithVendorId,
final BPartnerId vendorId)
{
final List<PurchaseErrorItem> purchaseErrorItems = remotePurchaseItems.stream()
.filter(item -> item instanceof PurchaseErrorItem)
.map(item -> (PurchaseErrorItem)item)
.collect(ImmutableList.toImmutableList());
if (purchaseErrorItems.isEmpty())
{
return; // nothing to do
}
final I_C_BPartner vendor = Services.get(IBPartnerDAO.class).getById(vendorId);
throw new AdempiereException( | MSG_ERROR_WHILE_PLACING_REMOTE_PURCHASE_ORDER,
vendor.getValue(), vendor.getName())
.appendParametersToMessage()
.setParameter("purchaseCandidatesWithVendorId", purchaseCandidatesWithVendorId)
.setParameter("purchaseErrorItems", purchaseErrorItems);
}
private void logAndRethrow(
final Throwable throwable,
final BPartnerId vendorId,
final Collection<PurchaseCandidate> purchaseCandidates)
{
final ILoggable loggable = Loggables.get();
final String message = StringUtils.formatMessage(
"Caught {} while working with vendorId={}; message={}, purchaseCandidates={}",
throwable.getClass(), vendorId, throwable.getMessage(), purchaseCandidates);
logger.error(message, throwable);
loggable.addLog(message);
for (final PurchaseCandidate purchaseCandidate : purchaseCandidates)
{
purchaseCandidate.createErrorItem()
.throwable(throwable)
.buildAndAdd();
}
purchaseCandidateRepo.saveAll(purchaseCandidates);
exceptions.add(throwable);
throw new AdempiereException(message, throwable);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\PurchaseCandidateToOrderWorkflow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SysThirdAccount bindThirdAppAccountByUserId(SysThirdAccount sysThirdAccount) {
String thirdUserUuid = sysThirdAccount.getThirdUserUuid();
String thirdType = sysThirdAccount.getThirdType();
//获取当前登录用户
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//当前第三方用户已被其他用户所绑定
SysThirdAccount oneByThirdUserId = this.getOneByUuidAndThirdType(thirdUserUuid, thirdType,CommonConstant.TENANT_ID_DEFAULT_VALUE, null);
if(null != oneByThirdUserId){
//如果不为空,并且第三方表和当前登录的用户一致,直接返回
if(oConvertUtils.isNotEmpty(oneByThirdUserId.getSysUserId()) && oneByThirdUserId.getSysUserId().equals(sysUser.getId())){
return oneByThirdUserId;
}else if(oConvertUtils.isNotEmpty(oneByThirdUserId.getSysUserId())){
//如果第三方表的用户id不为空,那就说明已经绑定过了
throw new JeecgBootException("该敲敲云账号已被其它第三方账号绑定,请解绑或绑定其它敲敲云账号");
}else{
//更新第三方表信息用户id
oneByThirdUserId.setSysUserId(sysUser.getId());
oneByThirdUserId.setThirdType(thirdType);
sysThirdAccountMapper.updateById(oneByThirdUserId);
return oneByThirdUserId;
}
}else{
throw new JeecgBootException("账号绑定失败,请稍后重试");
}
} | @Override
public SysThirdAccount getOneByUuidAndThirdType(String unionid, String thirdType,Integer tenantId,String thirdUserId) {
LambdaQueryWrapper<SysThirdAccount> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysThirdAccount::getThirdType, thirdType);
// 代码逻辑说明: 如果第三方用户id为空那么就不走第三方用户查询逻辑,因为扫码登录third_user_id是唯一的,没有重复的情况---
if(oConvertUtils.isNotEmpty(thirdUserId)){
queryWrapper.and((wrapper) ->wrapper.eq(SysThirdAccount::getThirdUserUuid,unionid).or().eq(SysThirdAccount::getThirdUserId,thirdUserId));
}else{
queryWrapper.eq(SysThirdAccount::getThirdUserUuid, unionid);
}
queryWrapper.eq(SysThirdAccount::getTenantId, tenantId);
return super.getOne(queryWrapper);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysThirdAccountServiceImpl.java | 2 |
请完成以下Java代码 | public List<IdentityLink> execute(CommandContext commandContext) {
TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
List<IdentityLink> identityLinks = (List) task.getIdentityLinks();
// assignee is not part of identity links in the db.
// so if there is one, we add it here.
// @Tom: we discussed this long on skype and you agreed ;-)
// an assignee *is* an identityLink, and so must it be reflected in the
// API
//
// Note: we cant move this code to the TaskEntity (which would be
// cleaner),
// since the task.delete cascaded to all associated identityLinks
// and of course this leads to exception while trying to delete a
// non-existing identityLink
if (task.getAssignee() != null) {
IdentityLinkEntity identityLink = commandContext.getIdentityLinkEntityManager().create();
identityLink.setUserId(task.getAssignee()); | identityLink.setType(IdentityLinkType.ASSIGNEE);
identityLink.setTaskId(task.getId());
identityLinks.add(identityLink);
}
if (task.getOwner() != null) {
IdentityLinkEntity identityLink = commandContext.getIdentityLinkEntityManager().create();
identityLink.setUserId(task.getOwner());
identityLink.setTaskId(task.getId());
identityLink.setType(IdentityLinkType.OWNER);
identityLinks.add(identityLink);
}
return (List) task.getIdentityLinks();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetIdentityLinksForTaskCmd.java | 1 |
请完成以下Java代码 | public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Reference for this record
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
/** Set Zusammenfassung.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Zusammenfassung.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary () | {
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void createInvoicePaySchedules(final I_C_Invoice invoice)
{
InvoicePayScheduleCreateCommand.builder()
.invoicePayScheduleRepository(invoicePayScheduleRepository)
.orderPayScheduleService(orderPayScheduleService)
.paymentTermService(paymentTermService)
.invoiceRecord(invoice)
.build()
.execute();
}
public void validateInvoiceBeforeCommit(@NonNull final InvoiceId invoiceId)
{
trxManager.accumulateAndProcessBeforeCommit(
"InvoicePayScheduleService.validateInvoiceBeforeCommit",
Collections.singleton(invoiceId),
invoiceIds -> validateInvoicesNow(ImmutableSet.copyOf(invoiceIds))
);
} | private void validateInvoicesNow(final Set<InvoiceId> invoiceIds)
{
if (invoiceIds.isEmpty()) {return;}
final ImmutableMap<InvoiceId, I_C_Invoice> invoicesById = Maps.uniqueIndex(
invoiceBL.getByIds(invoiceIds),
invoice -> InvoiceId.ofRepoId(invoice.getC_Invoice_ID())
);
invoicePayScheduleRepository.updateByIds(invoicesById.keySet(), invoicePaySchedule -> {
final I_C_Invoice invoice = invoicesById.get(invoicePaySchedule.getInvoiceId());
final Money grandTotal = invoiceBL.extractGrandTotal(invoice).toMoney();
boolean isValid = invoicePaySchedule.validate(grandTotal);
invoice.setIsPayScheduleValid(isValid);
invoiceBL.save(invoice);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\service\InvoicePayScheduleService.java | 2 |
请完成以下Java代码 | public String getRoleName(final RoleId adRoleId)
{
if (adRoleId == null)
{
return "?";
}
final Role role = getById(adRoleId);
return role.getName();
}
@Override
// @Cached(cacheName = I_AD_User_Roles.Table_Name + "#by#AD_Role_ID", expireMinutes = 0) // not sure if caching is needed...
public Set<UserId> retrieveUserIdsForRoleId(final RoleId adRoleId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMN_AD_Role_ID, adRoleId)
.addOnlyActiveRecordsFilter()
.create()
.listDistinct(I_AD_User_Roles.COLUMNNAME_AD_User_ID, Integer.class)
.stream()
.map(UserId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public RoleId retrieveFirstRoleIdForUserId(final UserId userId)
{
final Integer firstRoleId = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMN_AD_User_ID, userId)
.addOnlyActiveRecordsFilter()
.create()
.first(I_AD_User_Roles.COLUMNNAME_AD_Role_ID, Integer.class);
return firstRoleId == null ? null : RoleId.ofRepoIdOrNull(firstRoleId);
}
@Override
public void createUserRoleAssignmentIfMissing(final UserId adUserId, final RoleId adRoleId)
{
if (hasUserRoleAssignment(adUserId, adRoleId))
{
return;
}
final I_AD_User_Roles userRole = InterfaceWrapperHelper.newInstance(I_AD_User_Roles.class);
userRole.setAD_User_ID(adUserId.getRepoId()); | userRole.setAD_Role_ID(adRoleId.getRepoId());
InterfaceWrapperHelper.save(userRole);
Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
}
private boolean hasUserRoleAssignment(final UserId adUserId, final RoleId adRoleId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMNNAME_AD_User_ID, adUserId)
.addEqualsFilter(I_AD_User_Roles.COLUMN_AD_Role_ID, adRoleId)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
public void deleteUserRolesByUserId(final UserId userId)
{
Services.get(IQueryBL.class).createQueryBuilder(I_AD_User_Roles.class)
.addEqualsFilter(I_AD_User_Roles.COLUMNNAME_AD_User_ID, userId)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\RoleDAO.java | 1 |
请完成以下Java代码 | public void applyRequestMetadata(final RequestInfo requestInfo, final Executor appExecutor,
final MetadataApplier applier) {
if (isPrivacyGuaranteed(requestInfo.getSecurityLevel())) {
this.callCredentials.applyRequestMetadata(requestInfo, appExecutor, applier);
} else {
applier.fail(STATUS_LACKING_PRIVACY);
}
}
@Override
public void thisUsesUnstableApi() {} // API evolution in progress
@Override
public String toString() {
return "RequirePrivacyCallCredentials [callCredentials=" + this.callCredentials + "]";
}
}
/**
* Wraps the given call credentials in a new layer, that will only include the credentials if the connection
* guarantees privacy. If the connection doesn't do that, the call will continue without the credentials.
*
* <p>
* <b>Note:</b> This method uses experimental grpc-java-API features.
* </p>
*
* @param callCredentials The call credentials to wrap.
* @return The newly created call credentials.
*/
public static CallCredentials includeWhenPrivate(final CallCredentials callCredentials) {
return new IncludeWhenPrivateCallCredentials(callCredentials);
}
/**
* A call credentials implementation with increased security requirements. It ensures that the credentials and
* requests aren't send via an insecure connection. This wrapper does not have any other influence on the security
* of the underlying {@link CallCredentials} implementation. | */
private static final class IncludeWhenPrivateCallCredentials extends CallCredentials {
private final CallCredentials callCredentials;
IncludeWhenPrivateCallCredentials(final CallCredentials callCredentials) {
this.callCredentials = callCredentials;
}
@Override
public void applyRequestMetadata(final RequestInfo requestInfo, final Executor appExecutor,
final MetadataApplier applier) {
if (isPrivacyGuaranteed(requestInfo.getSecurityLevel())) {
this.callCredentials.applyRequestMetadata(requestInfo, appExecutor, applier);
}
}
@Override
public void thisUsesUnstableApi() {} // API evolution in progress
@Override
public String toString() {
return "IncludeWhenPrivateCallCredentials [callCredentials=" + this.callCredentials + "]";
}
}
private CallCredentialsHelper() {}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\security\CallCredentialsHelper.java | 1 |
请完成以下Java代码 | public boolean isSameFile(Path path, Path path2) throws IOException {
return path.equals(path2);
}
@Override
public boolean isHidden(Path path) throws IOException {
return false;
}
@Override
public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
nestedPath.assertExists();
return new NestedFileStore(nestedPath.getFileSystem());
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override | public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java | 1 |
请完成以下Java代码 | public void updateById(
@NonNull final PPOrderWeightingRunId runId,
@NonNull final Consumer<PPOrderWeightingRun> consumer)
{
final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver();
loaderAndSaver.updateById(runId, consumer);
}
public void deleteChecks(final PPOrderWeightingRunId runId)
{
queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class)
.addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, runId)
.create()
.delete();
}
public PPOrderWeightingRunCheckId addRunCheck(
@NonNull final PPOrderWeightingRunId weightingRunId, | @NonNull final SeqNo lineNo,
@NonNull final Quantity weight,
@NonNull final OrgId orgId)
{
final I_PP_Order_Weighting_RunCheck record = InterfaceWrapperHelper.newInstance(I_PP_Order_Weighting_RunCheck.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setPP_Order_Weighting_Run_ID(weightingRunId.getRepoId());
record.setLine(lineNo.toInt());
record.setWeight(weight.toBigDecimal());
record.setC_UOM_ID(weight.getUomId().getRepoId());
InterfaceWrapperHelper.save(record);
return PPOrderWeightingRunCheckId.ofRepoId(weightingRunId, record.getPP_Order_Weighting_RunCheck_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunRepository.java | 1 |
请完成以下Java代码 | protected void instantiate(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) {
if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, null, (PvmTransition) targetElement, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, (PvmActivity) targetElement, null, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected void instantiateConcurrent(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) {
if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, null, (PvmTransition) targetElement, variables,
variablesLocal, skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, (PvmActivity) targetElement, null, variables, | variablesLocal, skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected abstract ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition);
protected abstract CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition);
protected abstract String getTargetElementId();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractInstantiationCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SumUpPendingTransactionContinuousUpdater implements SumUpTransactionStatusChangedListener
{
private static final String SYSCONFIG_PollIntervalInSeconds = "de.metas.payment.sumup.pendingTransactionsUpdate.pollIntervalInSeconds";
private static final Duration DEFAULT_PollInterval = Duration.ofSeconds(2);
private static final int DEFAULT_NoPendingTransactionsDelayMultiplier = 5;
@NonNull private static final Logger logger = LogManager.getLogger(SumUpPendingTransactionContinuousUpdater.class);
@NonNull private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
@NonNull private final SumUpService sumUpService;
@NonNull private final AtomicBoolean pendingTransactionsDetected = new AtomicBoolean(false);
@PostConstruct
public void postConstruct()
{
final Thread thread = new Thread(this::runNow);
thread.setDaemon(true);
thread.setName("SumUp-pending-transaction-updater");
thread.start();
logger.info("Started {}", thread);
}
private void runNow()
{
while (true)
{
final Duration delay = getPollInterval();
for (int i = 1; i <= DEFAULT_NoPendingTransactionsDelayMultiplier; i++)
{
if (!sleep(delay))
{
logger.info("Got interrupt request. Exiting.");
return;
}
if (pendingTransactionsDetected.get())
{
logger.debug("Pending transactions detected.");
break;
}
}
bulkUpdatePendingTransactionsNoFail();
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean sleep(final Duration duration)
{
try | {
logger.debug("Sleeping {}", duration);
Thread.sleep(duration.toMillis());
return true;
}
catch (InterruptedException e)
{
return false;
}
}
private void bulkUpdatePendingTransactionsNoFail()
{
try
{
final BulkUpdateByQueryResult result = sumUpService.bulkUpdatePendingTransactions(false);
if (!result.isZero())
{
logger.debug("Pending transactions updated: {}", result);
}
// Set the pending transactions flag as long as we get some updates
pendingTransactionsDetected.set(!result.isZero());
}
catch (final Exception ex)
{
logger.warn("Failed to process. Ignored.", ex);
}
}
private Duration getPollInterval()
{
final int valueInt = sysConfigBL.getPositiveIntValue(SYSCONFIG_PollIntervalInSeconds, 0);
return valueInt > 0 ? Duration.ofSeconds(valueInt) : DEFAULT_PollInterval;
}
@Override
public void onStatusChanged(@NonNull final SumUpTransactionStatusChangedEvent event)
{
if (event.getStatusNew().isPending())
{
pendingTransactionsDetected.set(true);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\server\SumUpPendingTransactionContinuousUpdater.java | 2 |
请完成以下Java代码 | public Byte getCommentStatus() {
return commentStatus;
}
public void setCommentStatus(Byte commentStatus) {
this.commentStatus = commentStatus;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", commentId=").append(commentId);
sb.append(", newsId=").append(newsId);
sb.append(", commentator=").append(commentator);
sb.append(", commentBody=").append(commentBody);
sb.append(", commentStatus=").append(commentStatus);
sb.append(", isDeleted=").append(isDeleted);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsComment.java | 1 |
请完成以下Java代码 | private void forwardSomeResponseHttpHeaders(@NonNull final HttpServletResponse servletResponse, @Nullable final HttpHeaders httpHeaders)
{
if (httpHeaders == null || httpHeaders.isEmpty())
{
return;
}
httpHeaders.keySet()
.stream()
.filter(key -> !key.equals(HttpHeaders.CONNECTION))
.filter(key -> !key.equals(HttpHeaders.CONTENT_LENGTH))
.filter(key -> !key.equals(HttpHeaders.CONTENT_TYPE))
.filter(key -> !key.equals(HttpHeaders.TRANSFER_ENCODING)) // if we forwarded this without knowing what we do, we would annoy a possible nginx reverse proxy
.forEach(key -> {
final List<String> values = httpHeaders.get(key);
if (values != null)
{
values.forEach(value -> servletResponse.addHeader(key, value));
}
});
}
@NonNull
private ApiResponse wrapBodyIfNeeded(
@Nullable final ApiAuditConfig apiAuditConfig,
@Nullable final ApiRequestAudit apiRequestAudit,
@NonNull final ApiResponse apiResponse)
{
if (apiAuditConfig != null && apiRequestAudit != null && apiAuditConfig.isWrapApiResponse() && apiResponse.isJson())
{
return apiResponse.toBuilder()
.contentType(MediaType.APPLICATION_JSON)
.charset(StandardCharsets.UTF_8)
.body(JsonApiResponse.builder()
.requestId(JsonMetasfreshId.of(apiRequestAudit.getIdNotNull().getRepoId()))
.endpointResponse(apiResponse.getBody())
.build())
.build();
}
else
{
final HttpHeaders httpHeaders = apiResponse.getHttpHeaders() != null ? new HttpHeaders(apiResponse.getHttpHeaders()) : new HttpHeaders();
if (apiRequestAudit != null) | {
httpHeaders.add(API_RESPONSE_HEADER_REQUEST_AUDIT_ID, String.valueOf(apiRequestAudit.getIdNotNull().getRepoId()));
}
return apiResponse.toBuilder().httpHeaders(httpHeaders).build();
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isResetServletResponse(@NonNull final HttpServletResponse response)
{
if (!response.isCommitted())
{
response.reset();
return true;
}
Loggables.addLog("HttpServletResponse has already been committed -> cannot be altered! response status = {}", response.getStatus());
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ResponseHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void save(@NonNull final ServiceRepairProjectTask task)
{
final I_C_Project_Repair_Task record = getRecordById(task.getId());
updateRecord(record, task);
saveRecord(record);
}
public ImmutableSet<ServiceRepairProjectTaskId> retainIdsOfType(
@NonNull final ImmutableSet<ServiceRepairProjectTaskId> taskIds,
@NonNull final ServiceRepairProjectTaskType type)
{
if (taskIds.isEmpty())
{
return ImmutableSet.of();
}
final List<Integer> eligibleRepoIds = queryBL.createQueryBuilder(I_C_Project_Repair_Task.class)
.addInArrayFilter(I_C_Project_Repair_Task.COLUMNNAME_C_Project_Repair_Task_ID, taskIds)
.addEqualsFilter(I_C_Project_Repair_Task.COLUMNNAME_Type, type.getCode())
.create()
.listIds();
return taskIds.stream()
.filter(taskId -> eligibleRepoIds.contains(taskId.getRepoId()))
.collect(ImmutableSet.toImmutableSet()); | }
public Optional<ServiceRepairProjectTask> getTaskByRepairOrderId(
@NonNull final ProjectId projectId,
@NonNull final PPOrderId repairOrderId)
{
return getTaskIdByRepairOrderId(projectId, repairOrderId).map(this::getById);
}
public Optional<ServiceRepairProjectTaskId> getTaskIdByRepairOrderId(
@NonNull final ProjectId projectId,
@NonNull final PPOrderId repairOrderId)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_Task.class)
.addEqualsFilter(I_C_Project_Repair_Task.COLUMNNAME_Type, ServiceRepairProjectTaskType.REPAIR_ORDER.getCode())
.addEqualsFilter(I_C_Project_Repair_Task.COLUMNNAME_C_Project_ID, projectId)
.addEqualsFilter(I_C_Project_Repair_Task.COLUMNNAME_Repair_Order_ID, repairOrderId)
.create()
.firstOnlyOptional(I_C_Project_Repair_Task.class)
.map(ServiceRepairProjectTaskRepository::extractTaskId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\ServiceRepairProjectTaskRepository.java | 2 |
请完成以下Java代码 | protected boolean afterSave(boolean newRecord, boolean success)
{
if (isActive())
{
setDataToLevel();
listChildRecords();
}
return true;
}
private String setDataToLevel()
{
String info = "-";
if (isClientLevelOnly())
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(getTableName())
.append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?");
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), getAD_Client_ID(), get_TrxName());
info = getTableName() + " set to Shared #" + no;
log.info(info);
}
else if (isOrgLevelOnly())
{
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ")
.append(getTableName())
.append(" WHERE AD_Org_ID=0 AND AD_Client_ID=?");
int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID());
info = getTableName() + " Shared records #" + no;
log.info(info);
}
return info;
} // setDataToLevel
private String listChildRecords()
{
final StringBuilder info = new StringBuilder();
String sql = "SELECT AD_Table_ID, TableName "
+ "FROM AD_Table t "
+ "WHERE AccessLevel='3' AND IsView='N'"
+ " AND EXISTS (SELECT * FROM AD_Column c "
+ "WHERE t.AD_Table_ID=c.AD_Table_ID"
+ " AND c.IsParent='Y'" | + " AND c.ColumnName IN (SELECT ColumnName FROM AD_Column cc "
+ "WHERE cc.IsKey='Y' AND cc.AD_Table_ID=?))";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, getAD_Table_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
String TableName = rs.getString(2);
if (info.length() != 0)
{
info.append(", ");
}
info.append(TableName);
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
}
return info.toString();
}
@Override
protected boolean beforeSave(boolean newRecord)
{
if (getAD_Org_ID() != 0)
{
setAD_Org_ID(0);
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClientShare.java | 1 |
请完成以下Java代码 | public ProfilePayload follow(@InputArgument("username") String username) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
return userRepository
.findByUsername(username)
.map(
target -> {
FollowRelation followRelation = new FollowRelation(user.getId(), target.getId());
userRepository.saveRelation(followRelation);
Profile profile = buildProfile(username, user);
return ProfilePayload.newBuilder().profile(profile).build();
})
.orElseThrow(ResourceNotFoundException::new);
}
@DgsData(parentType = MUTATION.TYPE_NAME, field = MUTATION.UnfollowUser)
public ProfilePayload unfollow(@InputArgument("username") String username) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
User target =
userRepository.findByUsername(username).orElseThrow(ResourceNotFoundException::new);
return userRepository
.findRelation(user.getId(), target.getId())
.map(
relation -> { | userRepository.removeRelation(relation);
Profile profile = buildProfile(username, user);
return ProfilePayload.newBuilder().profile(profile).build();
})
.orElseThrow(ResourceNotFoundException::new);
}
private Profile buildProfile(@InputArgument("username") String username, User current) {
ProfileData profileData = profileQueryService.findByUsername(username, current).get();
return Profile.newBuilder()
.username(profileData.getUsername())
.bio(profileData.getBio())
.image(profileData.getImage())
.following(profileData.isFollowing())
.build();
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\RelationMutation.java | 1 |
请完成以下Java代码 | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code. | */
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass_Type.java | 1 |
请完成以下Java代码 | public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Role Menu.
@param U_RoleMenu_ID Role Menu */
public void setU_RoleMenu_ID (int U_RoleMenu_ID)
{
if (U_RoleMenu_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, Integer.valueOf(U_RoleMenu_ID));
}
/** Get Role Menu.
@return Role Menu */
public int getU_RoleMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_RoleMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_U_WebMenu getU_WebMenu() throws RuntimeException
{
return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name)
.getPO(getU_WebMenu_ID(), get_TrxName()); } | /** Set Web Menu.
@param U_WebMenu_ID Web Menu */
public void setU_WebMenu_ID (int U_WebMenu_ID)
{
if (U_WebMenu_ID < 1)
set_Value (COLUMNNAME_U_WebMenu_ID, null);
else
set_Value (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID));
}
/** Get Web Menu.
@return Web Menu */
public int getU_WebMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_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_U_RoleMenu.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
public List<Bar> getBars() {
return bars;
}
public Long getId() {
return id;
}
public String getName() {
return name; | }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public void setBars(List<Bar> bars) {
this.bars = bars;
}
public void setId(final Long id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=")
.append(name)
.append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Foo.java | 1 |
请完成以下Java代码 | private Optional<ProductExclude> getBannedManufacturerFromSaleToCustomer(@NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
final ProductRepository productRepo = SpringContextHolder.instance.getBean(ProductRepository.class);
final Product product = productRepo.getById(productId);
final BPartnerId manufacturerId = product.getManufacturerId();
return queryBL
.createQueryBuilderOutOfTrx(I_M_BannedManufacturer.class)
.addOnlyContextClient()
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_BannedManufacturer.COLUMNNAME_C_BPartner_ID, partnerId.getRepoId())
.addEqualsFilter(I_M_BannedManufacturer.COLUMNNAME_Manufacturer_ID, manufacturerId == null ? -1 : manufacturerId.getRepoId())
.create()
.firstOnlyOptional(I_M_BannedManufacturer.class)
.map(bannedManufacturer -> ProductExclude.builder()
.bpartnerId(partnerId)
.productId(productId)
.reason(bannedManufacturer.getExclusionFromSaleReason())
.build());
}
@Override
public @NonNull List<I_C_BPartner_Product> retrieveByEAN13ProductCode(@NonNull final EAN13ProductCode ean13ProductCode, @NonNull final BPartnerId bpartnerId)
{
return queryBL.createQueryBuilder(I_C_BPartner_Product.class) | .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_EAN13_ProductCode, ean13ProductCode.getAsString())
.create()
.listImmutable(I_C_BPartner_Product.class);
}
@Override
public @NonNull List<I_C_BPartner_Product> retrieveByGTIN(@NonNull GTIN gtin, @NonNull final BPartnerId bpartnerId)
{
return queryBL.createQueryBuilder(I_C_BPartner_Product.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addFilter(
queryBL.createCompositeQueryFilter(I_C_BPartner_Product.class)
.setJoinOr()
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_GTIN, gtin.getAsString())
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_EAN_CU, gtin.getAsString())
// NOTE: don't check the EAN13_ProductCode
)
.create()
.listImmutable(I_C_BPartner_Product.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner_product\impl\BPartnerProductDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OLCandProductFromPIIPvalidator implements IOLCandValidator
{
private final static transient Logger logger = LogManager.getLogger(OLCandProductFromPIIPvalidator.class);
private final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class);
@Override
public int getSeqNo()
{
return 10;
}
@Override
public void validate(@NonNull final I_C_OLCand olCand)
{
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand);
final I_M_HU_PI_Item_Product huPIItemProduct = OLCandPIIPUtil.extractHUPIItemProductOrNull(olCand);
if (huPIItemProduct == null)
{
return;
}
final boolean virtualHU = HUPIItemProductId.ofRepoId(huPIItemProduct.getM_HU_PI_Item_Product_ID()).isVirtualHU();
if (virtualHU)
{ | return;
}
if (productId == null)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Supplement missing C_OLCand.M_Product_ID = {} from M_HU_PI_Item_Product_ID={}", huPIItemProduct.getM_Product_ID(), huPIItemProduct.getM_HU_PI_Item_Product_ID());
olCand.setM_Product_ID(huPIItemProduct.getM_Product_ID());
}
else if (productId.getRepoId() != huPIItemProduct.getM_Product_ID())
{
throw new AdempiereException("Effective C_OLCand.M_Product_ID is inconsistent with effective C_OLCand.M_HU_PI_Item_Product.M_Product_ID")
.appendParametersToMessage()
.setParameter("C_OLCand.M_Product_ID (eff)", productId.getRepoId())
.setParameter("C_OLCand.M_HU_PI_Item_Product.M_Product_ID (eff)", huPIItemProduct.getM_Product_ID());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandProductFromPIIPvalidator.java | 2 |
请完成以下Java代码 | public String getCode()
{
return code;
}
public static final Join forCodeOrAND(final String code)
{
final Join join = codeToJoin.get(code);
return join != null ? join : AND;
}
}
//@formatter:off
void setJoin(Join join);
Join getJoin();
//@formatter:on
//@formatter:off
IUserQueryField getSearchField();
void setSearchField(final IUserQueryField searchField);
//@formatter:on
//@formatter:off
void setOperator(Operator operator);
Operator getOperator();
//@formatter:on
//@formatter:off
Object getValue();
void setValue(Object value);
//@formatter:on
//@formatter:off | Object getValueTo();
void setValueTo(Object valueTo);
//@formatter:on
/** @return true if restriction is empty (i.e. has nothing set) */
boolean isEmpty();
boolean isMandatory();
void setMandatory(boolean mandatory);
boolean isInternalParameter();
void setInternalParameter(boolean internalParameter);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\IUserQueryRestriction.java | 1 |
请完成以下Java代码 | public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public org.compiere.model.I_C_Activity getParent_Activity() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class);
}
@Override
public void setParent_Activity(org.compiere.model.I_C_Activity Parent_Activity)
{
set_ValueFromPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class, Parent_Activity);
}
/** Set Hauptkostenstelle.
@param Parent_Activity_ID Hauptkostenstelle */
@Override
public void setParent_Activity_ID (int Parent_Activity_ID)
{
if (Parent_Activity_ID < 1)
set_Value (COLUMNNAME_Parent_Activity_ID, null);
else
set_Value (COLUMNNAME_Parent_Activity_ID, Integer.valueOf(Parent_Activity_ID));
}
/** Get Hauptkostenstelle.
@return Hauptkostenstelle */ | @Override
public int getParent_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Parent_Activity_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Activity.java | 1 |
请完成以下Java代码 | public static boolean setAttribute(String word, Nature... natures)
{
if (natures == null) return false;
CoreDictionary.Attribute attribute = new CoreDictionary.Attribute(natures, new int[natures.length]);
Arrays.fill(attribute.frequency, 1);
return setAttribute(word, attribute);
}
/**
* 设置某个单词的属性
* @param word
* @param natures
* @return
*/
public static boolean setAttribute(String word, String... natures)
{
if (natures == null) return false;
Nature[] natureArray = new Nature[natures.length];
for (int i = 0; i < natureArray.length; i++)
{
natureArray[i] = Nature.create(natures[i]);
}
return setAttribute(word, natureArray);
}
/**
* 设置某个单词的属性
* @param word
* @param natureWithFrequency
* @return | */
public static boolean setAttribute(String word, String natureWithFrequency)
{
CoreDictionary.Attribute attribute = CoreDictionary.Attribute.create(natureWithFrequency);
return setAttribute(word, attribute);
}
/**
* 将字符串词性转为Enum词性
* @param name 词性名称
* @param customNatureCollector 一个收集集合
* @return 转换结果
*/
public static Nature convertStringToNature(String name, LinkedHashSet<Nature> customNatureCollector)
{
Nature nature = Nature.fromString(name);
if (nature == null)
{
nature = Nature.create(name);
if (customNatureCollector != null) customNatureCollector.add(nature);
}
return nature;
}
/**
* 将字符串词性转为Enum词性
* @param name 词性名称
* @return 转换结果
*/
public static Nature convertStringToNature(String name)
{
return convertStringToNature(name, null);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\LexiconUtility.java | 1 |
请完成以下Java代码 | private static void updateHeaderNow(final Set<OrderId> orderIds)
{
// shall not happen
if (orderIds.isEmpty())
{
return;
}
// Update Order Header: TotalLines
{
final ArrayList<Object> sqlParams = new ArrayList<>();
final String sql = "UPDATE C_Order o"
+ " SET TotalLines="
+ "(SELECT COALESCE(SUM(ol.LineNetAmt),0) FROM C_OrderLine ol WHERE ol.C_Order_ID=o.C_Order_ID) "
+ "WHERE " + DB.buildSqlList("C_Order_ID", orderIds, sqlParams);
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), ITrx.TRXNAME_ThreadInherited);
if (no != 1)
{ | new AdempiereException("Updating TotalLines failed for C_Order_IDs=" + orderIds);
}
}
// Update Order Header: GrandTotal
{
final ArrayList<Object> sqlParams = new ArrayList<>();
final String sql = "UPDATE C_Order o "
+ " SET GrandTotal=TotalLines+"
// SUM up C_OrderTax.TaxAmt only for those lines which does not have Tax Included
+ "(SELECT COALESCE(SUM(TaxAmt),0) FROM C_OrderTax ot WHERE o.C_Order_ID=ot.C_Order_ID AND ot.IsActive='Y' AND ot.IsTaxIncluded='N') "
+ "WHERE " + DB.buildSqlList("C_Order_ID", orderIds, sqlParams);
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), ITrx.TRXNAME_ThreadInherited);
if (no != 1)
{
new AdempiereException("Updating GrandTotal failed for C_Order_IDs=" + orderIds);
}
}
}
} // MOrderLine | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MOrderLine.java | 1 |
请完成以下Java代码 | private final void assertConfigurable()
{
// nothing
}
public LUTUAssignBuilder setContext(final IContextAware context)
{
assertConfigurable();
_context = context;
return this;
}
private IContextAware getContext()
{
return _context;
}
public LUTUAssignBuilder setLU_PI(final I_M_HU_PI luPI)
{
assertConfigurable();
_luPI = luPI;
return this;
}
private I_M_HU_PI getLU_PI()
{
Check.assumeNotNull(_luPI, "_luPI not null");
return _luPI;
}
public LUTUAssignBuilder setTUsToAssign(final Collection<I_M_HU> tusToAssign)
{
assertConfigurable();
_tusToAssign = new ArrayList<>(tusToAssign);
return this;
}
private List<I_M_HU> getTUsToAssign()
{
Check.assumeNotEmpty(_tusToAssign, "_tusToAssign not empty");
return _tusToAssign;
}
public final LUTUAssignBuilder setHUPlanningReceiptOwnerPM(final boolean isHUPlanningReceiptOwnerPM)
{
assertConfigurable();
_isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM;
return this;
}
private final boolean isHUPlanningReceiptOwnerPM()
{
return _isHUPlanningReceiptOwnerPM;
}
public LUTUAssignBuilder setDocumentLine(final IHUDocumentLine documentLine)
{
assertConfigurable();
_documentLine = documentLine;
return this;
}
private IHUDocumentLine getDocumentLine()
{
return _documentLine; // null is ok
} | public LUTUAssignBuilder setC_BPartner(final I_C_BPartner bpartner)
{
assertConfigurable();
this._bpartnerId = bpartner != null ? BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()) : null;
return this;
}
private final BPartnerId getBPartnerId()
{
return _bpartnerId;
}
public LUTUAssignBuilder setC_BPartner_Location_ID(final int bpartnerLocationId)
{
assertConfigurable();
_bpLocationId = bpartnerLocationId;
return this;
}
private final int getC_BPartner_Location_ID()
{
return _bpLocationId;
}
public LUTUAssignBuilder setM_Locator(final I_M_Locator locator)
{
assertConfigurable();
_locatorId = LocatorId.ofRecordOrNull(locator);
return this;
}
private LocatorId getLocatorId()
{
Check.assumeNotNull(_locatorId, "_locatorId not null");
return _locatorId;
}
public LUTUAssignBuilder setHUStatus(final String huStatus)
{
assertConfigurable();
_huStatus = huStatus;
return this;
}
private String getHUStatus()
{
Check.assumeNotEmpty(_huStatus, "_huStatus not empty");
return _huStatus;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUAssignBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EDIMProductLookupUPCVType {
@XmlElement(name = "UPC", required = true)
protected String upc;
@XmlElement(name = "GLN", required = true)
protected String gln;
/**
* Gets the value of the upc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUPC() {
return upc;
}
/**
* Sets the value of the upc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUPC(String value) {
this.upc = value;
}
/** | * Gets the value of the gln property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIMProductLookupUPCVType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class InventoryLineHUId implements RepoIdAware
{
int repoId;
private InventoryLineHUId(int repoId)
{
this.repoId = assumeGreaterThanZero(repoId, "M_InventoryLine_HU_ID");
}
public static InventoryLineHUId ofRepoId(int repoId)
{
return new InventoryLineHUId(repoId);
}
@Nullable
public static InventoryLineHUId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
@JsonCreator
@Nullable
public static InventoryLineHUId ofNullableObject(@Nullable final Object obj)
{
return RepoIdAwares.ofObjectOrNull(obj, InventoryLineHUId.class, InventoryLineHUId::ofRepoIdOrNull);
} | @NonNull
public static InventoryLineHUId ofObject(@NonNull final Object obj)
{
return RepoIdAwares.ofObject(obj, InventoryLineHUId.class, InventoryLineHUId::ofRepoId);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final InventoryLineHUId id1, final InventoryLineHUId id2) { return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHUId.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.