instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
PmsProduct record = new PmsProduct();
record.setPublishStatus(publishStatus);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andIdIn(ids);
return productMapper.updateByExampleSelective(record, example);
}
@Override
public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
PmsProduct record = new PmsProduct();
record.setRecommandStatus(recommendStatus);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andIdIn(ids);
return productMapper.updateByExampleSelective(record, example);
}
@Override
public int updateNewStatus(List<Long> ids, Integer newStatus) {
PmsProduct record = new PmsProduct();
record.setNewStatus(newStatus);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andIdIn(ids);
return productMapper.updateByExampleSelective(record, example);
}
@Override
public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
PmsProduct record = new PmsProduct();
record.setDeleteStatus(deleteStatus);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andIdIn(ids);
return productMapper.updateByExampleSelective(record, example);
}
@Override
public List<PmsProduct> list(String keyword) {
PmsProductExample productExample = new PmsProductExample();
PmsProductExample.Criteria criteria = productExample.createCriteria();
criteria.andDeleteStatusEqualTo(0);
if(!StrUtil.isEmpty(keyword)){
criteria.andNameLike("%" + keyword + "%");
productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%");
|
}
return productMapper.selectByExample(productExample);
}
/**
* 建立和插入关系表操作
*
* @param dao 可以操作的dao
* @param dataList 要插入的数据
* @param productId 建立关系的id
*/
private void relateAndInsertList(Object dao, List dataList, Long productId) {
try {
if (CollectionUtils.isEmpty(dataList)) return;
for (Object item : dataList) {
Method setId = item.getClass().getMethod("setId", Long.class);
setId.invoke(item, (Long) null);
Method setProductId = item.getClass().getMethod("setProductId", Long.class);
setProductId.invoke(item, productId);
}
Method insertList = dao.getClass().getMethod("insertList", List.class);
insertList.invoke(dao, dataList);
} catch (Exception e) {
LOGGER.warn("创建商品出错:{}", e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductServiceImpl.java
| 2
|
请完成以下Java代码
|
public static String toCodeOrNull(@Nullable final DeliveryRule type)
{
return type != null ? type.getCode() : null;
}
public boolean isCompleteOrder()
{
return COMPLETE_ORDER.equals(this);
}
public boolean isCompleteOrderOrLine()
{
return COMPLETE_ORDER.equals(this) || COMPLETE_LINE.equals(this);
}
public boolean isBasedOnDelivery()
{
|
return AVAILABILITY.equals(this) || COMPLETE_ORDER.equals(this) || COMPLETE_LINE.equals(this);
}
public boolean isAvailability()
{
return AVAILABILITY.equals(this);
}
public boolean isForce()
{
return FORCE.equals(this);
}
public boolean isManual()
{
return MANUAL.equals(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\order\DeliveryRule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getDefaultDestination() {
return this.defaultDestination;
}
public void setDefaultDestination(@Nullable String defaultDestination) {
this.defaultDestination = defaultDestination;
}
public @Nullable Duration getDeliveryDelay() {
return this.deliveryDelay;
}
public void setDeliveryDelay(@Nullable Duration deliveryDelay) {
this.deliveryDelay = deliveryDelay;
}
public @Nullable DeliveryMode getDeliveryMode() {
return this.deliveryMode;
}
public void setDeliveryMode(@Nullable DeliveryMode deliveryMode) {
this.deliveryMode = deliveryMode;
}
public @Nullable Integer getPriority() {
return this.priority;
}
public void setPriority(@Nullable Integer priority) {
this.priority = priority;
}
public @Nullable Duration getTimeToLive() {
return this.timeToLive;
}
public void setTimeToLive(@Nullable Duration timeToLive) {
this.timeToLive = timeToLive;
}
public boolean determineQosEnabled() {
if (this.qosEnabled != null) {
return this.qosEnabled;
}
return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null);
}
public @Nullable Boolean getQosEnabled() {
return this.qosEnabled;
}
public void setQosEnabled(@Nullable Boolean qosEnabled) {
this.qosEnabled = qosEnabled;
}
public @Nullable Duration getReceiveTimeout() {
return this.receiveTimeout;
}
public void setReceiveTimeout(@Nullable Duration receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Acknowledge mode used when creating sessions.
*/
private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO;
/**
* Whether to use transacted sessions.
*/
private boolean transacted;
public AcknowledgeMode getAcknowledgeMode() {
return this.acknowledgeMode;
}
|
public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) {
this.acknowledgeMode = acknowledgeMode;
}
public boolean isTransacted() {
return this.transacted;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
}
}
public enum DeliveryMode {
/**
* Does not require that the message be logged to stable storage. This is the
* lowest-overhead delivery mode but can lead to lost of message if the broker
* goes down.
*/
NON_PERSISTENT(1),
/*
* Instructs the JMS provider to log the message to stable storage as part of the
* client's send operation.
*/
PERSISTENT(2);
private final int value;
DeliveryMode(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java
| 2
|
请完成以下Java代码
|
public ModificationRestService getModificationRestService() {
return super.getModificationRestService(null);
}
@Path(BatchRestService.PATH)
public BatchRestService getBatchRestService() {
return super.getBatchRestService(null);
}
@Path(TenantRestService.PATH)
public TenantRestService getTenantRestService() {
return super.getTenantRestService(null);
}
@Path(SignalRestService.PATH)
public SignalRestService getSignalRestService() {
return super.getSignalRestService(null);
}
@Path(ConditionRestService.PATH)
public ConditionRestService getConditionRestService() {
return super.getConditionRestService(null);
}
@Path(OptimizeRestService.PATH)
public OptimizeRestService getOptimizeRestService() {
return super.getOptimizeRestService(null);
}
@Path(VersionRestService.PATH)
public VersionRestService getVersionRestService() {
return super.getVersionRestService(null);
}
@Path(SchemaLogRestService.PATH)
public SchemaLogRestService getSchemaLogRestService() {
return super.getSchemaLogRestService(null);
|
}
@Path(EventSubscriptionRestService.PATH)
public EventSubscriptionRestService getEventSubscriptionRestService() {
return super.getEventSubscriptionRestService(null);
}
@Path(TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService() {
return super.getTelemetryRestService(null);
}
@Override
protected URI getRelativeEngineUri(String engineName) {
// the default engine
return URI.create("/");
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public Object execute(CommandContext commandContext) {
ensureNotNull("taskId", taskId);
ensureNotNull("variableName", variableName);
TaskEntity task = Context
.getCommandContext()
.getTaskManager()
.findTaskById(taskId);
ensureNotNull("task " + taskId + " doesn't exist", "task", task);
checkGetTaskVariable(task, commandContext);
Object value;
|
if (isLocal) {
value = task.getVariableLocal(variableName);
} else {
value = task.getVariable(variableName);
}
return value;
}
protected void checkGetTaskVariable(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\GetTaskVariableCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
@GetMapping("/session/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
public String sessionInvalid() {
return "session已失效,请重新认证";
}
@GetMapping("/signout/success")
public String signout() {
return "退出成功,请重新登录";
}
@GetMapping("/auth/admin")
@PreAuthorize("hasAuthority('admin')")
public String authenticationTest() {
return "您拥有admin权限,可以查看";
}
}
|
repos\SpringAll-master\61.Spring-security-Permission\src\main\java\cc\mrbird\web\controller\BrowserSecurityController.java
| 2
|
请完成以下Java代码
|
public final UriComponentsBuilder getUriBuilder() {
return uriBuilder;
}
public final HttpServletResponse getResponse() {
return response;
}
public final int getPage() {
return page;
}
public final int getTotalPages() {
return totalPages;
}
|
public final int getPageSize() {
return pageSize;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
@SuppressWarnings("unchecked")
public final Class<T> getClazz() {
return (Class<T>) getSource();
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\hateoas\event\PaginatedResultsRetrievedEvent.java
| 1
|
请完成以下Java代码
|
private LookupValuesList getPickingSlotValues(final LookupDataSourceContext context)
{
final WEBUI_M_HU_Pick_ParametersFiller filler = WEBUI_M_HU_Pick_ParametersFiller
.pickingSlotFillerBuilder()
.shipmentScheduleId(shipmentScheduleId)
.build();
return filler.getPickingSlotValues(context);
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
|
return;
}
invalidateView();
}
private WEBUI_M_HU_Pick_ParametersFiller createNewDefaultParametersFiller()
{
final HURow row = WEBUI_PP_Order_ProcessHelper.getHURowsFromIncludedRows(getView()).get(0);
return WEBUI_M_HU_Pick_ParametersFiller.defaultFillerBuilder()
.huId(row.getHuId())
.salesOrderLineId(getSalesOrderLineId())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Pick_ReceivedHUs.java
| 1
|
请完成以下Java代码
|
public void setTaxID (java.lang.String TaxID)
{
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID);
}
/** Get Steuer-ID.
@return Tax Identification
*/
@Override
public java.lang.String getTaxID ()
{
return (java.lang.String)get_Value(COLUMNNAME_TaxID);
}
/** Set Titel.
@param Title
Name this entity is referred to as
|
*/
@Override
public void setTitle (java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java
| 1
|
请完成以下Java代码
|
public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin)
{
set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin);
}
/** Get Erreichbar von.
@return Erreichbar von */
@Override
public java.sql.Timestamp getPhonecallTimeMin ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin);
}
/** Set Kundenbetreuer.
@param SalesRep_ID Kundenbetreuer */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
|
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Kundenbetreuer.
@return Kundenbetreuer */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_Phonecall_Schedule.java
| 1
|
请完成以下Java代码
|
public class FatherAndSonRelation {
@Id
private long id;
@StartNode
private King from;
@EndNode
private King to;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
|
}
public King getFrom() {
return from;
}
public void setFrom(King from) {
this.from = from;
}
public King getTo() {
return to;
}
public void setTo(King to) {
this.to = to;
}
}
|
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\relation\FatherAndSonRelation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUsernameLC() {
return getUsername().toLowerCase();
}
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
public boolean isValidUsername3(String username) {
return userRoleRepository.isValidUsername(username);
}
@PreAuthorize("#username == authentication.principal.username")
public String getMyRoles(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("#username == authentication.principal.username")
public String getMyRoles2(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
@PreFilter("filterObject != authentication.principal.username")
public String joinUsernames(List<String> usernames) {
|
return usernames.stream().collect(Collectors.joining(";"));
}
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
}
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() {
return userRoleRepository.getAllUsernames();
}
@IsViewer
public String getUsername4() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PreAuthorize("#username == authentication.principal.username")
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser securedLoadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java
| 2
|
请完成以下Java代码
|
private CompletableFuture<R> execute( ApiInvoker<R> invoker) {
try {
callResult = new CompletableFuture<>();
log.info("[I38] Calling API...");
final Call call = invoker.apply(api,this);
log.info("[I41] API Succesfully invoked: method={}, url={}",
call.request().method(),
call.request().url());
return callResult;
}
catch(ApiException aex) {
callResult.completeExceptionally(aex);
return callResult;
}
}
@Override
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
log.error("[E53] onFailure",e);
callResult.completeExceptionally(e);
}
|
@Override
public void onSuccess(R result, int statusCode, Map<String, List<String>> responseHeaders) {
log.error("[E61] onSuccess: statusCode={}",statusCode);
callResult.complete(result);
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
log.info("[E61] onUploadProgress: bytesWritten={}, contentLength={}, done={}",bytesWritten,contentLength,done);
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
log.info("[E75] onDownloadProgress: bytesRead={}, contentLength={}, done={}",bytesRead,contentLength,done);
}
}
|
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\AsyncHelper.java
| 1
|
请完成以下Java代码
|
public void setAD_Issue_ID (int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID));
}
/** Get System-Problem.
@return Automatically created or manually entered System Issue
*/
@Override
public int getAD_Issue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_ValueNoCheck (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Fehler.
@param IsError
Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
|
@Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());// 设置解密规则
// 开启全局缓存
myShiroRealm.setCachingEnabled(true);
// 开启认证缓存
myShiroRealm.setAuthenticationCachingEnabled(true);
// 设置认证缓存管理的名字
myShiroRealm.setAuthenticationCacheName("authenticationCache");
// 开启授权缓存管理
myShiroRealm.setAuthorizationCachingEnabled(true);
// 设置授权缓存管理的名字
myShiroRealm.setAuthorizationCacheName("authorizationCache");
// 开启Redis缓存
myShiroRealm.setCacheManager(new RedisCacheManager());
return myShiroRealm;
}
// SecurityManager是Shiro架构的核心,通过它来链接Realm和用户(文档中称之为Subject.)
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}
/**
* 开启shiro aop注解支持.
|
* 使用代理方式;所以需要开启代码支持;
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver
createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
mappings.setProperty("UnauthorizedException","403");
r.setExceptionMappings(mappings); // None by default
r.setDefaultErrorView("error"); // No default
r.setExceptionAttribute("ex"); // Default is "exception"
//r.setWarnLogCategory("example.MvcLogger"); // No default
return r;
}
}
|
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\config\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public ITranslatableString getExplanation()
{
return explanation != null ? explanation : TranslatableStrings.empty();
}
public String getExplanationAsString()
{
return explanation != null ? explanation.getDefaultValue() : null;
}
@Nullable
public T orElse(@Nullable final T other)
{
return value != null ? value : other;
}
public T orElseGet(@NonNull final Supplier<? extends T> other)
{
return value != null ? value : other.get();
}
public T orElseThrow()
{
return orElseThrow(AdempiereException::new);
}
public T orElseThrow(@NonNull final AdMessageKey adMessageKey)
{
return orElseThrow(message -> new AdempiereException(adMessageKey).setParameter("detail", message));
}
public T orElseThrow(@NonNull final Function<ITranslatableString, RuntimeException> exceptionFactory)
{
if (value != null)
{
return value;
}
else
{
throw exceptionFactory.apply(explanation);
}
}
public T get()
{
return orElseThrow();
}
public boolean isPresent()
{
return value != null;
}
public <U> ExplainedOptional<U> map(@NonNull final Function<? super T, ? extends U> mapper)
{
if (!isPresent())
{
return emptyBecause(explanation);
}
else
{
final U newValue = mapper.apply(value);
if (newValue == null)
{
return emptyBecause(explanation);
}
else
|
{
return of(newValue);
}
}
}
public ExplainedOptional<T> ifPresent(@NonNull final Consumer<T> consumer)
{
if (isPresent())
{
consumer.accept(value);
}
return this;
}
@SuppressWarnings("UnusedReturnValue")
public ExplainedOptional<T> ifAbsent(@NonNull final Consumer<ITranslatableString> consumer)
{
if (!isPresent())
{
consumer.accept(explanation);
}
return this;
}
/**
* @see #resolve(Function, Function)
*/
public <R> Optional<R> mapIfAbsent(@NonNull final Function<ITranslatableString, R> mapper)
{
return isPresent()
? Optional.empty()
: Optional.ofNullable(mapper.apply(getExplanation()));
}
/**
* @see #mapIfAbsent(Function)
*/
public <R> R resolve(
@NonNull final Function<T, R> mapPresent,
@NonNull final Function<ITranslatableString, R> mapAbsent)
{
return isPresent()
? mapPresent.apply(value)
: mapAbsent.apply(explanation);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ExplainedOptional.java
| 1
|
请完成以下Java代码
|
private Quantity addQtyShipped(
final DDOrderLineToAllocate ddOrderLineToAllocate,
final I_M_HU hu,
final Quantity qtyToAllocate,
final boolean force)
{
final ProductId productId = ddOrderLineToAllocate.getProductId();
//
// Get how much we can allocate (maximum)
final Quantity qtyToAllocateMax;
if (force)
{
qtyToAllocateMax = qtyToAllocate;
}
else
{
qtyToAllocateMax = ddOrderLineToAllocate.getQtyToShipRemaining();
}
final Quantity qtyToAllocateConv = uomConversionBL.convertQuantityTo(qtyToAllocate, productId, qtyToAllocateMax.getUomId());
final Quantity qtyToAllocateRemaining = qtyToAllocateMax.subtract(qtyToAllocateConv);
final Quantity qtyShipped;
if (qtyToAllocateRemaining.signum() < 0)
{
qtyShipped = qtyToAllocateMax; // allocate the maximum allowed qty if it's lower than the remaining qty
}
else
{
qtyShipped = qtyToAllocateConv; // allocate the full remaining qty because it's within the maximum boundaries
}
if (qtyShipped.isZero())
{
return qtyShipped;
}
final Quantity qtyShippedConv = uomConversionBL.convertQuantityTo(qtyShipped, productId, qtyToAllocateMax.getUomId());
|
ddOrderLineToAllocate.addPickFromHU(DDOrderLineToAllocate.PickFromHU.builder()
.hu(hu)
.qty(qtyShippedConv)
.build());
return qtyShippedConv;
}
private ImmutableList<DDOrderLineToAllocate> getLinesToAllocateByProductId(@NonNull final ProductId productId)
{
return ddOrderLines.stream()
.filter(ddOrderLineToAllocate -> ProductId.equals(ddOrderLineToAllocate.getProductId(), productId))
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\generate_from_hu\SchedulesFromHUsGenerator.java
| 1
|
请完成以下Java代码
|
public void setAD_Org_Mapping(final org.compiere.model.I_AD_Org_Mapping AD_Org_Mapping)
{
set_ValueFromPO(COLUMNNAME_AD_Org_Mapping_ID, org.compiere.model.I_AD_Org_Mapping.class, AD_Org_Mapping);
}
@Override
public void setAD_Org_Mapping_ID (final int AD_Org_Mapping_ID)
{
if (AD_Org_Mapping_ID < 1)
set_Value (COLUMNNAME_AD_Org_Mapping_ID, null);
else
set_Value (COLUMNNAME_AD_Org_Mapping_ID, AD_Org_Mapping_ID);
}
@Override
public int getAD_Org_Mapping_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID);
}
@Override
public void setAD_OrgTo_ID (final int AD_OrgTo_ID)
{
if (AD_OrgTo_ID < 1)
set_Value (COLUMNNAME_AD_OrgTo_ID, null);
else
set_Value (COLUMNNAME_AD_OrgTo_ID, AD_OrgTo_ID);
}
@Override
public int getAD_OrgTo_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_OrgTo_ID);
}
@Override
public void setC_BPartner_From_ID (final int C_BPartner_From_ID)
{
if (C_BPartner_From_ID < 1)
set_Value (COLUMNNAME_C_BPartner_From_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_From_ID, C_BPartner_From_ID);
}
@Override
public int getC_BPartner_From_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_From_ID);
}
@Override
|
public void setC_BPartner_To_ID (final int C_BPartner_To_ID)
{
if (C_BPartner_To_ID < 1)
set_Value (COLUMNNAME_C_BPartner_To_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_To_ID, C_BPartner_To_ID);
}
@Override
public int getC_BPartner_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_To_ID);
}
@Override
public void setDate_OrgChange (final java.sql.Timestamp Date_OrgChange)
{
set_Value (COLUMNNAME_Date_OrgChange, Date_OrgChange);
}
@Override
public java.sql.Timestamp getDate_OrgChange()
{
return get_ValueAsTimestamp(COLUMNNAME_Date_OrgChange);
}
@Override
public void setIsCloseInvoiceCandidate (final boolean IsCloseInvoiceCandidate)
{
set_Value (COLUMNNAME_IsCloseInvoiceCandidate, IsCloseInvoiceCandidate);
}
@Override
public boolean isCloseInvoiceCandidate()
{
return get_ValueAsBoolean(COLUMNNAME_IsCloseInvoiceCandidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgChange_History.java
| 1
|
请完成以下Java代码
|
public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText)
{
this.parent = parent;
this.infoColumn = infoColumn;
}
@Override
public I_AD_InfoColumn getAD_InfoColumn()
{
return infoColumn;
}
@Override
public int getParameterCount()
{
return 2;
}
@Override
public String getLabel(int index)
{
if (index == 0)
return Msg.translate(Env.getCtx(), "NearCity");
else if (index == 1)
|
return Msg.translate(Env.getCtx(), "RadiusKM");
else
return null;
}
@Override
public Object getParameterToComponent(int index)
{
return null;
}
@Override
public Object getParameterValue(int index, boolean returnValueTo)
{
return null;
}
public IInfoSimple getParent()
{
return parent;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPRadiusAbstract.java
| 1
|
请完成以下Java代码
|
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String fromHeader = Objects.requireNonNull(config.getFromHeader(), "fromHeader must be set");
String toHeader = Objects.requireNonNull(config.getToHeader(), "toHeader must be set");
if (!exchange.getRequest().getHeaders().containsHeader(fromHeader)) {
return chain.filter(exchange);
}
List<String> headerValues = exchange.getRequest().getHeaders().get(fromHeader);
if (headerValues == null) {
return chain.filter(exchange);
}
ServerHttpRequest request = exchange.getRequest()
.mutate()
.headers(i -> i.addAll(toHeader, headerValues))
.build();
return chain.filter(exchange.mutate().request(request).build());
}
@Override
public String toString() {
// @formatter:off
String fromHeader = config.getFromHeader();
String toHeader = config.getToHeader();
return filterToStringCreator(MapRequestHeaderGatewayFilterFactory.this)
.append(FROM_HEADER_KEY, fromHeader != null ? fromHeader : "")
.append(TO_HEADER_KEY, toHeader != null ? toHeader : "")
.toString();
// @formatter:on
}
};
}
public static class Config {
private @Nullable String fromHeader;
private @Nullable String toHeader;
public @Nullable String getFromHeader() {
return this.fromHeader;
|
}
public Config setFromHeader(String fromHeader) {
this.fromHeader = fromHeader;
return this;
}
public @Nullable String getToHeader() {
return this.toHeader;
}
public Config setToHeader(String toHeader) {
this.toHeader = toHeader;
return this;
}
@Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("fromHeader", fromHeader)
.append("toHeader", toHeader)
.toString();
// @formatter:on
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\MapRequestHeaderGatewayFilterFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Class<? extends Annotation> getAnnotationType() {
return UseGroups.class;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
if (isAnnotationPresent(importMetadata)) {
AnnotationAttributes inGroupsAttributes = getAnnotationAttributes(importMetadata);
setGroups(inGroupsAttributes.containsKey("value")
? inGroupsAttributes.getStringArray("value") : null);
setGroups(inGroupsAttributes.containsKey("groups")
? inGroupsAttributes.getStringArray("groups") : null);
}
}
protected void setGroups(String[] groups) {
this.groups = Optional.ofNullable(groups)
.filter(it -> it.length > 0)
.orElse(this.groups);
}
|
protected Optional<String[]> getGroups() {
return Optional.ofNullable(this.groups)
.filter(it -> it.length > 0);
}
@Bean
ClientCacheConfigurer clientCacheGroupsConfigurer() {
return (beaName, clientCacheFactoryBean) -> configureGroups(clientCacheFactoryBean);
}
@Bean
PeerCacheConfigurer peerCacheGroupsConfigurer() {
return (beaName, peerCacheFactoryBean) -> configureGroups(peerCacheFactoryBean);
}
private void configureGroups(CacheFactoryBean cacheFactoryBean) {
getGroups().ifPresent(groups -> cacheFactoryBean.getProperties()
.setProperty(GEMFIRE_GROUPS_PROPERTY, StringUtils.arrayToCommaDelimitedString(groups)));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\GroupsConfiguration.java
| 2
|
请完成以下Java代码
|
private ImmutableList<DocLine_CostRevaluation> loadDocLines()
{
return costRevaluationRepository.streamAllLineRecordsByCostRevaluationId(costRevaluation.getCostRevaluationId())
.filter(I_M_CostRevaluationLine::isActive)
.sorted(Comparator.comparing(I_M_CostRevaluationLine::getM_CostRevaluationLine_ID))
.map(lineRecord -> new DocLine_CostRevaluation(lineRecord, this))
.collect(ImmutableList.toImmutableList());
}
@Override
protected BigDecimal getBalance() {return BigDecimal.ZERO;}
@Override
protected List<Fact> createFacts(final AcctSchema as)
{
if (!AcctSchemaId.equals(as.getId(), costRevaluation.getAcctSchemaId()))
{
return ImmutableList.of();
}
setC_Currency_ID(as.getCurrencyId());
final Fact fact = new Fact(this, as, PostingType.Actual);
getDocLines().forEach(line -> createFactsForLine(fact, line));
return ImmutableList.of(fact);
}
private void createFactsForLine(@NonNull final Fact fact, @NonNull final DocLine_CostRevaluation docLine)
{
final AcctSchema acctSchema = fact.getAcctSchema();
final CostAmount costs = docLine.getCreateCosts(acctSchema);
//
// Revenue
// -------------------
// Product Asset DR
// Revenue CR
if (costs.signum() >= 0)
{
fact.createLine()
.setDocLine(docLine)
|
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs, null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Revenue_Acct, acctSchema))
.setAmtSource(null, costs)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
//
// Expense
// ------------------------------------
// Product Asset CR
// Expense DR
else // deltaAmountToBook.signum() < 0
{
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(null, costs.negate())
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs.negate(), null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_CostRevaluation.java
| 1
|
请完成以下Java代码
|
public int getC_AcctSchema_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_CostElement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_AcctSchema getC_AcctSchema() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class);
}
@Override
public void setC_AcctSchema(org.compiere.model.I_C_AcctSchema C_AcctSchema)
{
set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema);
}
/** Set Buchführungs-Schema.
@param C_AcctSchema_ID
Stammdaten für Buchhaltung
*/
@Override
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_Value (COLUMNNAME_C_AcctSchema_ID, null);
else
set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Buchführungs-Schema.
@return Stammdaten für Buchhaltung
*/
@Override
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
@Override
public org.compiere.model.I_M_CostElement getM_CostElement() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class);
}
@Override
public void setM_CostElement(org.compiere.model.I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
}
/** Set Kostenart.
@param M_CostElement_ID
Produkt-Kostenart
*/
@Override
public void setM_CostElement_ID (int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID));
}
/** Get Kostenart.
@return Produkt-Kostenart
*/
@Override
public int getM_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_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_C_AcctSchema_CostElement.java
| 1
|
请完成以下Java代码
|
private void setFavoriteCount(List<ArticleData> articles) {
List<ArticleFavoriteCount> favoritesCounts =
articleFavoritesReadService.articlesFavoriteCount(
articles.stream().map(ArticleData::getId).collect(toList()));
Map<String, Integer> countMap = new HashMap<>();
favoritesCounts.forEach(
item -> {
countMap.put(item.getId(), item.getCount());
});
articles.forEach(
articleData -> articleData.setFavoritesCount(countMap.get(articleData.getId())));
}
private void setIsFavorite(List<ArticleData> articles, User currentUser) {
Set<String> favoritedArticles =
articleFavoritesReadService.userFavorites(
articles.stream().map(articleData -> articleData.getId()).collect(toList()),
currentUser);
articles.forEach(
articleData -> {
|
if (favoritedArticles.contains(articleData.getId())) {
articleData.setFavorited(true);
}
});
}
private void fillExtraInfo(String id, User user, ArticleData articleData) {
articleData.setFavorited(articleFavoritesReadService.isUserFavorite(user.getId(), id));
articleData.setFavoritesCount(articleFavoritesReadService.articleFavoriteCount(id));
articleData
.getProfileData()
.setFollowing(
userRelationshipQueryService.isUserFollowing(
user.getId(), articleData.getProfileData().getId()));
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\ArticleQueryService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RuntimeService runtimeServiceBean(ProcessEngine processEngine) {
return processEngine.getRuntimeService();
}
@Bean
@ConditionalOnMissingBean
public RepositoryService repositoryServiceBean(ProcessEngine processEngine) {
return processEngine.getRepositoryService();
}
@Bean
@ConditionalOnMissingBean
public TaskService taskServiceBean(ProcessEngine processEngine) {
return processEngine.getTaskService();
}
@Bean
@ConditionalOnMissingBean
public HistoryService historyServiceBean(ProcessEngine processEngine) {
return processEngine.getHistoryService();
}
@Bean
@ConditionalOnMissingBean
public ManagementService managementServiceBean(ProcessEngine processEngine) {
return processEngine.getManagementService();
}
@Bean
@ConditionalOnMissingBean
public DynamicBpmnService dynamicBpmnServiceBean(ProcessEngine processEngine) {
return processEngine.getDynamicBpmnService();
|
}
@Bean
@ConditionalOnMissingBean
public ProcessMigrationService processInstanceMigrationService(ProcessEngine processEngine) {
return processEngine.getProcessMigrationService();
}
@Bean
@ConditionalOnMissingBean
public FormService formServiceBean(ProcessEngine processEngine) {
return processEngine.getFormService();
}
@Bean
@ConditionalOnMissingBean
public IdentityService identityServiceBean(ProcessEngine processEngine) {
return processEngine.getIdentityService();
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ProcessEngineServicesAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setInvalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy) {
this.invalidSessionStrategy = invalidSessionStrategy;
}
/**
* The handler which will be invoked if the <tt>AuthenticatedSessionStrategy</tt>
* raises a <tt>SessionAuthenticationException</tt>, indicating that the user is not
* allowed to be authenticated for this session (typically because they already have
* too many sessions open).
*
*/
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
|
* null.
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\SessionManagementFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private BigDecimal extractQtyDelivered(@Nullable final SinglePack singlePack)
{
if (singlePack == null)
{
return ZERO;
}
final BigDecimal qtyDelivered = singlePack.getPackItem().getQtyCUsPerLU();
if (qtyDelivered == null)
{
return ZERO;
}
return qtyDelivered;
}
private DiscrepencyCode extractDiscrepancyCode(
@Nullable final String isSubsequentDeliveryPlanned,
@NonNull final BigDecimal diff)
{
final DiscrepencyCode discrepancyCode;
if (diff.signum() > 0)
|
{
discrepancyCode = DiscrepencyCode.OVSH; // = Over-shipped
return discrepancyCode;
}
if (Boolean.parseBoolean(isSubsequentDeliveryPlanned))
{
discrepancyCode = DiscrepencyCode.BFOL; // = Shipment partial - back order to follow
}
else
{
discrepancyCode = DiscrepencyCode.BCOM; // = shipment partial - considered complete, no backorder;
}
return discrepancyCode;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\stepcom\StepComXMLDesadvBean.java
| 2
|
请完成以下Java代码
|
public int getC_OrgAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_OrgAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
|
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrgAssignment.java
| 1
|
请完成以下Java代码
|
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (Objects.equals(PARAM_QtyCUsPerTU, parameter.getColumnName()))
{
return retrieveQtyToPick().toBigDecimal();
}
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
protected void validatePickingToHU()
{
final PickingSlotRow pickingSlotRow = getSingleSelectedRow();
final I_M_HU hu = handlingUnitsBL.getById(pickingSlotRow.getHuId());
if (!handlingUnitsBL.isVirtual(hu))
{
return;
}
final ImmutableSet<ProductId> productIds = handlingUnitsBL.getStorageFactory().streamHUProductStorages(ImmutableList.of(hu))
.map(IProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
final I_M_ShipmentSchedule selectedShipmentSchedule = getCurrentShipmentSchedule();
if (productIds.size() != 1 || !productIds.contains(ProductId.ofRepoId(selectedShipmentSchedule.getM_Product_ID())))
{
throw new AdempiereException("VHUs cannot have multiple product storages!")
.appendParametersToMessage()
.setParameter("HuId", hu.getM_HU_ID());
}
}
@NonNull
protected Optional<ProcessPreconditionsResolution> checkValidSelection()
{
if (getParentViewRowIdsSelection() == null)
{
return Optional.of(ProcessPreconditionsResolution.rejectBecauseNoSelection());
}
if (getSelectedRowIds().isMoreThanOneDocumentId()
|| getParentViewRowIdsSelection().getRowIds().isMoreThanOneDocumentId() )
{
return Optional.of(ProcessPreconditionsResolution.rejectBecauseNotSingleSelection());
}
final PickingSlotRow pickingSlotRow = getSingleSelectedRow();
if (!pickingSlotRow.isPickedHURow())
{
return Optional.of(ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU)));
}
if (pickingSlotRow.isProcessed())
{
|
return Optional.of(ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_NO_UNPROCESSED_RECORDS)));
}
if (getPickingConfig().isForbidAggCUsForDifferentOrders() && isAggregatingCUsToDifferentOrders())
{
return Optional.of(ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_AGGREGATING_CUS_TO_DIFF_ORDER_IS_FORBIDDEN)));
}
return Optional.empty();
}
@NonNull
protected HuId getPackToHuId()
{
final PickingSlotRow selectedRow = getSingleSelectedRow();
if (!getPickingConfig().isForbidAggCUsForDifferentOrders())
{
return selectedRow.getHuId();
}
final OrderId orderId = getCurrentlyPickingOrderId();
if (orderId == null)
{
throw new AdempiereException(MSG_WEBUI_PICKING_AGGREGATING_CUS_TO_DIFF_ORDER_IS_FORBIDDEN);
}
if (!selectedRow.isLU())
{
return selectedRow.getHuId();
}
return selectedRow.findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId))
.map(PickingSlotRow::getHuId)
.orElseThrow(() -> new AdempiereException(MSG_WEBUI_PICKING_AGGREGATING_CUS_TO_DIFF_ORDER_IS_FORBIDDEN));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToExistingHU.java
| 1
|
请完成以下Java代码
|
public void planContinueProcessInCompensation(ExecutionEntity execution) {
planOperation(new ContinueProcessOperation(commandContext, execution, false, true, null), execution);
}
@Override
public void planContinueMultiInstanceOperation(ExecutionEntity execution, ExecutionEntity multiInstanceRootExecution, int loopCounter) {
planOperation(new ContinueMultiInstanceOperation(commandContext, execution, multiInstanceRootExecution, loopCounter), execution);
}
@Override
public void planTakeOutgoingSequenceFlowsOperation(ExecutionEntity execution, boolean evaluateConditions) {
planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, false), execution);
}
@Override
public void planTakeOutgoingSequenceFlowsSynchronousOperation(ExecutionEntity execution, boolean evaluateConditions) {
planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, true), execution);
}
@Override
public void planEndExecutionOperation(ExecutionEntity execution) {
planOperation(new EndExecutionOperation(commandContext, execution), execution);
}
@Override
public void planEndExecutionOperationSynchronous(ExecutionEntity execution) {
planOperation(new EndExecutionOperation(commandContext, execution, true), execution);
}
@Override
public void planTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution), execution);
|
}
@Override
public void planAsyncTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution, true), execution);
}
@Override
public void planEvaluateConditionalEventsOperation(ExecutionEntity execution) {
planOperation(new EvaluateConditionalEventsOperation(commandContext, execution), execution);
}
@Override
public void planEvaluateVariableListenerEventsOperation(String processDefinitionId, String processInstanceId) {
planOperation(new EvaluateVariableListenerEventDefinitionsOperation(commandContext, processDefinitionId, processInstanceId));
}
@Override
public void planDestroyScopeOperation(ExecutionEntity execution) {
planOperation(new DestroyScopeOperation(commandContext, execution), execution);
}
@Override
public void planExecuteInactiveBehaviorsOperation(Collection<ExecutionEntity> executions) {
planOperation(new ExecuteInactiveBehaviorsOperation(commandContext, executions));
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\agenda\DefaultFlowableEngineAgenda.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractAssetEntity<T extends Asset> extends BaseVersionedEntity<T> {
@Column(name = ASSET_TENANT_ID_PROPERTY)
private UUID tenantId;
@Column(name = ASSET_CUSTOMER_ID_PROPERTY)
private UUID customerId;
@Column(name = ASSET_NAME_PROPERTY)
private String name;
@Column(name = ASSET_TYPE_PROPERTY)
private String type;
@Column(name = ASSET_LABEL_PROPERTY)
private String label;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.ASSET_ADDITIONAL_INFO_PROPERTY)
private JsonNode additionalInfo;
@Column(name = ModelConstants.ASSET_ASSET_PROFILE_ID_PROPERTY, columnDefinition = "uuid")
private UUID assetProfileId;
@Column(name = EXTERNAL_ID_PROPERTY)
private UUID externalId;
public AbstractAssetEntity() {
super();
}
public AbstractAssetEntity(T asset) {
super(asset);
if (asset.getTenantId() != null) {
this.tenantId = asset.getTenantId().getId();
}
if (asset.getCustomerId() != null) {
this.customerId = asset.getCustomerId().getId();
}
if (asset.getAssetProfileId() != null) {
this.assetProfileId = asset.getAssetProfileId().getId();
}
this.name = asset.getName();
this.type = asset.getType();
this.label = asset.getLabel();
this.additionalInfo = asset.getAdditionalInfo();
if (asset.getExternalId() != null) {
this.externalId = asset.getExternalId().getId();
}
|
}
public AbstractAssetEntity(AssetEntity assetEntity) {
super(assetEntity);
this.tenantId = assetEntity.getTenantId();
this.customerId = assetEntity.getCustomerId();
this.assetProfileId = assetEntity.getAssetProfileId();
this.type = assetEntity.getType();
this.name = assetEntity.getName();
this.label = assetEntity.getLabel();
this.additionalInfo = assetEntity.getAdditionalInfo();
this.externalId = assetEntity.getExternalId();
}
protected Asset toAsset() {
Asset asset = new Asset(new AssetId(id));
asset.setCreatedTime(createdTime);
asset.setVersion(version);
if (tenantId != null) {
asset.setTenantId(TenantId.fromUUID(tenantId));
}
if (customerId != null) {
asset.setCustomerId(new CustomerId(customerId));
}
if (assetProfileId != null) {
asset.setAssetProfileId(new AssetProfileId(assetProfileId));
}
asset.setName(name);
asset.setType(type);
asset.setLabel(label);
asset.setAdditionalInfo(additionalInfo);
if (externalId != null) {
asset.setExternalId(new AssetId(externalId));
}
return asset;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractAssetEntity.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold max.
@param ThresholdMax
Maximum gross amount for withholding calculation (0=no limit)
*/
public void setThresholdMax (BigDecimal ThresholdMax)
{
set_Value (COLUMNNAME_ThresholdMax, ThresholdMax);
}
/** Get Threshold max.
@return Maximum gross amount for withholding calculation (0=no limit)
*/
|
public BigDecimal getThresholdMax ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold min.
@param Thresholdmin
Minimum gross amount for withholding calculation
*/
public void setThresholdmin (BigDecimal Thresholdmin)
{
set_Value (COLUMNNAME_Thresholdmin, Thresholdmin);
}
/** Get Threshold min.
@return Minimum gross amount for withholding calculation
*/
public BigDecimal getThresholdmin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Withholding.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnableSafeXml() {
return enableSafeXml;
}
public void setEnableSafeXml(boolean enableSafeXml) {
this.enableSafeXml = enableSafeXml;
}
public boolean isEventRegistryStartCaseInstanceAsync() {
return eventRegistryStartCaseInstanceAsync;
}
public void setEventRegistryStartCaseInstanceAsync(boolean eventRegistryStartCaseInstanceAsync) {
this.eventRegistryStartCaseInstanceAsync = eventRegistryStartCaseInstanceAsync;
}
public boolean isEventRegistryUniqueCaseInstanceCheckWithLock() {
return eventRegistryUniqueCaseInstanceCheckWithLock;
}
public void setEventRegistryUniqueCaseInstanceCheckWithLock(boolean eventRegistryUniqueCaseInstanceCheckWithLock) {
|
this.eventRegistryUniqueCaseInstanceCheckWithLock = eventRegistryUniqueCaseInstanceCheckWithLock;
}
public Duration getEventRegistryUniqueCaseInstanceStartLockTime() {
return eventRegistryUniqueCaseInstanceStartLockTime;
}
public void setEventRegistryUniqueCaseInstanceStartLockTime(Duration eventRegistryUniqueCaseInstanceStartLockTime) {
this.eventRegistryUniqueCaseInstanceStartLockTime = eventRegistryUniqueCaseInstanceStartLockTime;
}
public FlowableServlet getServlet() {
return servlet;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\FlowableCmmnProperties.java
| 2
|
请完成以下Java代码
|
public static LocalDate fromObjectToLocalDate(final Object valueObj)
{
return fromObjectTo(valueObj,
LocalDate.class,
de.metas.util.converter.DateTimeConverters::fromJsonToLocalDate,
TimeUtil::asLocalDate);
}
private static LocalTime fromObjectToLocalTime(final Object valueObj)
{
return fromObjectTo(valueObj,
LocalTime.class,
de.metas.util.converter.DateTimeConverters::fromJsonToLocalTime,
TimeUtil::asLocalTime);
}
public static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj)
{
return fromObjectTo(valueObj,
ZonedDateTime.class,
de.metas.util.converter.DateTimeConverters::fromJsonToZonedDateTime,
TimeUtil::asZonedDateTime);
}
public static Instant fromObjectToInstant(final Object valueObj)
{
return fromObjectTo(valueObj,
Instant.class,
de.metas.util.converter.DateTimeConverters::fromJsonToInstant,
TimeUtil::asInstant);
}
@Nullable
private static <T> T fromObjectTo(
final Object valueObj,
@NonNull final Class<T> type,
@NonNull final Function<String, T> fromJsonConverer,
@NonNull final Function<Object, T> fromObjectConverter)
{
if (valueObj == null
|| JSONNullValue.isNull(valueObj))
{
return null;
}
else if (type.isInstance(valueObj))
{
return type.cast(valueObj);
|
}
else if (valueObj instanceof CharSequence)
{
final String json = valueObj.toString().trim();
if (json.isEmpty())
{
return null;
}
if (isPossibleJdbcTimestamp(json))
{
try
{
final Timestamp timestamp = fromPossibleJdbcTimestamp(json);
return fromObjectConverter.apply(timestamp);
}
catch (final Exception e)
{
logger.warn("Error while converting possible JDBC Timestamp `{}` to java.sql.Timestamp", json, e);
return fromJsonConverer.apply(json);
}
}
else
{
return fromJsonConverer.apply(json);
}
}
else if (valueObj instanceof StringLookupValue)
{
final String key = ((StringLookupValue)valueObj).getIdAsString();
if (Check.isEmpty(key))
{
return null;
}
else
{
return fromJsonConverer.apply(key);
}
}
else
{
return fromObjectConverter.apply(valueObj);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\DateTimeConverters.java
| 1
|
请完成以下Java代码
|
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
return acceptIfSingleSelectedRow()
.and(this::acceptIfLockedByCurrentUser);
}
private ProcessPreconditionsResolution acceptIfSingleSelectedRow()
{
final DocumentIdsSelection rowIds = getSelectedRowIds();
if (!rowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select a single row");
}
else
{
return ProcessPreconditionsResolution.accept();
}
}
private ProcessPreconditionsResolution acceptIfLockedByCurrentUser()
{
final PackageableRow row = getSingleSelectedRow();
if (!row.isLockedBy(getLoggedUserId()))
|
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not locked by current user");
}
else
{
return ProcessPreconditionsResolution.accept();
}
}
@Override
protected String doIt()
{
final PackageableRow row = getSingleSelectedRow();
locksRepo.unlock(ShipmentScheduleUnLockRequest.builder()
.shipmentScheduleIds(row.getShipmentScheduleIds())
.lockType(ShipmentScheduleLockType.PICKING)
.lockedBy(getLoggedUserId())
.build());
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_UnlockFromLoggedUser.java
| 1
|
请完成以下Java代码
|
public class ListValueProvider implements ParameterValueProvider {
protected List<ParameterValueProvider> providerList;
public ListValueProvider(List<ParameterValueProvider> providerList) {
this.providerList = providerList;
}
public Object getValue(VariableScope variableScope) {
List<Object> valueList = new ArrayList<Object>();
for (ParameterValueProvider provider : providerList) {
valueList.add(provider.getValue(variableScope));
}
return valueList;
}
public List<ParameterValueProvider> getProviderList() {
|
return providerList;
}
public void setProviderList(List<ParameterValueProvider> providerList) {
this.providerList = providerList;
}
/**
* @return this method currently always returns false, but that might change in the future.
*/
@Override
public boolean isDynamic() {
// This implementation is currently not needed and therefore returns a defensive default value
return true;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\mapping\value\ListValueProvider.java
| 1
|
请完成以下Java代码
|
public Integer getHttpStatusCode() {
return getCause() == null ? httpStatusCode : ((RestException) getCause()).getHttpStatusCode();
}
public void setHttpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
/**
* @return the exception type from the Engine's REST API.
*/
public String getType() {
return getCause() == null ? type : ((RestException) getCause()).getType();
}
public void setType(String type) {
|
this.type = type;
}
/**
* @return the exception error code from the Engine's REST API.
*/
public Integer getCode() {
return getCause() == null ? code : ((RestException) getCause()).getCode();
}
public void setCode(Integer code) {
this.code = code;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\exception\RestException.java
| 1
|
请完成以下Java代码
|
default Class<?> getValueClass() { return getDescriptor().getValueClass(); }
/** @return field's current value */
@Nullable
Object getValue();
@Nullable
Object getValueAsJsonObject(JSONOptions jsonOpts);
boolean getValueAsBoolean();
int getValueAsInt(final int defaultValueWhenNull);
DocumentZoomIntoInfo getZoomIntoInfo();
@Nullable
<T> T getValueAs(@NonNull final Class<T> returnType);
default Optional<BigDecimal> getValueAsBigDecimal() { return Optional.ofNullable(getValueAs(BigDecimal.class));}
default <T extends RepoIdAware> Optional<T> getValueAsId(Class<T> idType) { return Optional.ofNullable(getValueAs(idType));}
/** @return initial value / last saved value */
@Nullable
|
Object getInitialValue();
/** @return old value (i.e. the value as it was when the document was checked out from repository/documents collection) */
@Nullable
Object getOldValue();
//@formatter:on
/**
* @return field's valid state; never return null
*/
DocumentValidStatus getValidStatus();
/**
* @return optional WindowId to be used when zooming into
*/
Optional<WindowId> getZoomIntoWindowId();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\IDocumentFieldView.java
| 1
|
请完成以下Java代码
|
public class C_Fiscal_Representation
{
private final FiscalRepresentationBL fiscalRepresentationBL = SpringContextHolder.instance.getBean(FiscalRepresentationBL.class);
@Init
public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_ValidFrom
})
public void addFiscalRepresentationValidFromTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidFrom() != null && fiscalRep.getValidTo() != null && !fiscalRepresentationBL.isValidFromDate(fiscalRep))
{
fiscalRepresentationBL.updateValidFrom(fiscalRep);
}
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_ValidTo
})
public void addFiscalRepresentationValidTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidToDate(fiscalRep))
{
fiscalRepresentationBL.updateValidTo(fiscalRep);
}
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Location_ID
})
public void addFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRepresentationBL.updateCountryId(fiscalRep);
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidFrom })
|
public void updateFiscalRepresentationValidFrom(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidFromDate(fiscalRep))
{
fiscalRepresentationBL.updateValidFrom(fiscalRep);
}
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Location_ID })
public void updateFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRepresentationBL.updateCountryId(fiscalRep);
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidTo })
public void updateFiscalRepresentationValidTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidToDate(fiscalRep))
{
fiscalRepresentationBL.updateValidTo(fiscalRep);
}
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Representative_ID })
public void updateFiscalRepresentationPartner(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setC_BPartner_Location_ID(-1);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\interceptors\C_Fiscal_Representation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria){
return databaseMapper.toDto(databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public DatabaseDto findById(String id) {
Database database = databaseRepository.findById(id).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",id);
return databaseMapper.toDto(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Database resources) {
resources.setId(IdUtil.simpleUUID());
databaseRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Database resources) {
Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",resources.getId());
database.copy(resources);
databaseRepository.save(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
databaseRepository.deleteById(id);
|
}
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
@Override
public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DatabaseDto databaseDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("数据库名称", databaseDto.getName());
map.put("数据库连接地址", databaseDto.getJdbcUrl());
map.put("用户名", databaseDto.getUserName());
map.put("创建日期", databaseDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DatabaseServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set End Date.
@param EndDate
Last effective date (inclusive)
*/
public void setEndDate (Timestamp EndDate)
{
set_Value (COLUMNNAME_EndDate, EndDate);
}
/** Get End Date.
@return Last effective date (inclusive)
*/
public Timestamp getEndDate ()
{
return (Timestamp)get_Value(COLUMNNAME_EndDate);
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
|
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign.java
| 1
|
请完成以下Java代码
|
public PointOfInteraction1 getPOI() {
return poi;
}
/**
* Sets the value of the poi property.
*
* @param value
* allowed object is
* {@link PointOfInteraction1 }
*
*/
public void setPOI(PointOfInteraction1 value) {
this.poi = value;
}
/**
* Gets the value of the aggtdNtry property.
*
* @return
* possible object is
* {@link CardAggregated1 }
|
*
*/
public CardAggregated1 getAggtdNtry() {
return aggtdNtry;
}
/**
* Sets the value of the aggtdNtry property.
*
* @param value
* allowed object is
* {@link CardAggregated1 }
*
*/
public void setAggtdNtry(CardAggregated1 value) {
this.aggtdNtry = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardEntry1.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<PageResult<MenuDto>> queryMenu(MenuQueryCriteria criteria) throws Exception {
List<MenuDto> menuDtoList = menuService.queryAll(criteria, true);
return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()),HttpStatus.OK);
}
@ApiOperation("查询菜单:根据ID获取同级与上级数据")
@PostMapping("/superior")
@PreAuthorize("@el.check('menu:list')")
public ResponseEntity<List<MenuDto>> getMenuSuperior(@RequestBody List<Long> ids) {
Set<MenuDto> menuDtos = new LinkedHashSet<>();
if(CollectionUtil.isNotEmpty(ids)){
for (Long id : ids) {
MenuDto menuDto = menuService.findById(id);
List<MenuDto> menuDtoList = menuService.getSuperior(menuDto, new ArrayList<>());
for (MenuDto menu : menuDtoList) {
if(menu.getId().equals(menuDto.getPid())) {
menu.setSubCount(menu.getSubCount() - 1);
}
}
menuDtos.addAll(menuDtoList);
}
// 编辑菜单时不显示自己以及自己下级的数据,避免出现PID数据环形问题
menuDtos = menuDtos.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toSet());
return new ResponseEntity<>(menuService.buildTree(new ArrayList<>(menuDtos)),HttpStatus.OK);
}
return new ResponseEntity<>(menuService.getMenus(null),HttpStatus.OK);
}
@Log("新增菜单")
@ApiOperation("新增菜单")
@PostMapping
@PreAuthorize("@el.check('menu:add')")
public ResponseEntity<Object> createMenu(@Validated @RequestBody Menu resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
menuService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改菜单")
@ApiOperation("修改菜单")
|
@PutMapping
@PreAuthorize("@el.check('menu:edit')")
public ResponseEntity<Object> updateMenu(@Validated(Menu.Update.class) @RequestBody Menu resources){
menuService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除菜单")
@ApiOperation("删除菜单")
@DeleteMapping
@PreAuthorize("@el.check('menu:del')")
public ResponseEntity<Object> deleteMenu(@RequestBody Set<Long> ids){
Set<Menu> menuSet = new HashSet<>();
for (Long id : ids) {
List<MenuDto> menuList = menuService.getMenus(id);
menuSet.add(menuService.findOne(id));
menuSet = menuService.getChildMenus(menuMapper.toEntity(menuList), menuSet);
}
menuService.delete(menuSet);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\MenuController.java
| 1
|
请完成以下Java代码
|
public String getUsageHelp() {
return "command";
}
@Override
public @Nullable String getHelp() {
return null;
}
@Override
public Collection<OptionHelp> getOptionsHelp() {
List<OptionHelp> help = new ArrayList<>();
for (Command command : this.commandRunner) {
if (isHelpShown(command)) {
help.add(new OptionHelp() {
@Override
public Set<String> getOptions() {
return Collections.singleton(command.getName());
}
@Override
public String getUsageHelp() {
return command.getDescription();
}
});
}
}
return help;
}
private boolean isHelpShown(Command command) {
return !(command instanceof HelpCommand) && !(command instanceof HintCommand);
}
@Override
public ExitStatus run(String... args) throws Exception {
if (args.length == 0) {
throw new NoHelpCommandArgumentsException();
}
String commandName = args[0];
for (Command command : this.commandRunner) {
if (command.getName().equals(commandName)) {
Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription());
Log.info("");
if (command.getUsageHelp() != null) {
Log.info("usage: " + this.commandRunner.getName() + command.getName() + " "
+ command.getUsageHelp());
|
Log.info("");
}
if (command.getHelp() != null) {
Log.info(command.getHelp());
}
Collection<HelpExample> examples = command.getExamples();
if (examples != null) {
Log.info((examples.size() != 1) ? "examples:" : "example:");
Log.info("");
for (HelpExample example : examples) {
Log.info(" " + example.getDescription() + ":");
Log.info(" $ " + example.getExample());
Log.info("");
}
Log.info("");
}
return ExitStatus.OK;
}
}
throw new NoSuchCommandException(commandName);
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\core\HelpCommand.java
| 1
|
请完成以下Java代码
|
public class TenantManager extends AbstractManager {
public ListQueryParameterObject configureQuery(ListQueryParameterObject query) {
TenantCheck tenantCheck = query.getTenantCheck();
configureTenantCheck(tenantCheck);
return query;
}
public void configureTenantCheck(TenantCheck tenantCheck) {
if (isTenantCheckEnabled()) {
Authentication currentAuthentication = getCurrentAuthentication();
tenantCheck.setTenantCheckEnabled(true);
tenantCheck.setAuthTenantIds(currentAuthentication.getTenantIds());
} else {
tenantCheck.setTenantCheckEnabled(false);
tenantCheck.setAuthTenantIds(null);
}
}
public ListQueryParameterObject configureQuery(Object parameters) {
ListQueryParameterObject queryObject = new ListQueryParameterObject();
queryObject.setParameter(parameters);
return configureQuery(queryObject);
|
}
public boolean isAuthenticatedTenant(String tenantId) {
if (tenantId != null && isTenantCheckEnabled()) {
Authentication currentAuthentication = getCurrentAuthentication();
List<String> authenticatedTenantIds = currentAuthentication.getTenantIds();
if (authenticatedTenantIds != null) {
return authenticatedTenantIds.contains(tenantId);
} else {
return false;
}
} else {
return true;
}
}
public boolean isTenantCheckEnabled() {
return Context.getProcessEngineConfiguration().isTenantCheckEnabled()
&& Context.getCommandContext().isTenantCheckEnabled()
&& getCurrentAuthentication() != null
&& !getAuthorizationManager().isCamundaAdmin(getCurrentAuthentication());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TenantManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getInvoiceDocType()
{
if (Check.isBlank(remadvLineItemExtension.getBusinessProcessID()))
{
throw new RuntimeCamelException("getInvoiceDocType: Missing BusinessProcessID on line: " + remadvLineItemExtension);
}
final Optional<String> invoiceDocBaseType = RemittanceAdviceInvoiceType.getByEdiCode(remadvLineItemExtension.getBusinessProcessID())
.map(RemittanceAdviceInvoiceType::getMetasDocBaseType);
return invoiceDocBaseType
.orElseThrow(() -> new RuntimeCamelException("getInvoiceDocType: Unclear InvoiceDocType for BusinessProcessID " + remadvLineItemExtension.getBusinessProcessID() + "on line: " + remadvLineItemExtension));
}
private boolean isSalesInvoice()
{
return getInvoiceDocType().equals(SALES_INVOICE.getMetasDocBaseType());
}
@NonNull
private Optional<String> getDateInvoiced()
{
final XMLGregorianCalendar dateInvoice = remadvLineItemExtension.getDocumentDate();
if (dateInvoice == null)
{
return Optional.empty();
}
final Instant instantDateInvoice = dateInvoice.toGregorianCalendar()
.toZonedDateTime()
.withZoneSameLocal(ZoneId.of(DOCUMENT_ZONE_ID))
.toInstant();
return Optional.of(instantDateInvoice.toString());
}
@NonNull
private Optional<BigDecimal> asBigDecimalAbs(@Nullable final MonetaryAmountType monetaryAmountType)
{
return asBigDecimal(monetaryAmountType);
}
@NonNull
private Optional<BigDecimal> asBigDecimal(@Nullable final MonetaryAmountType monetaryAmountType)
{
if (monetaryAmountType == null)
{
return Optional.empty();
}
return Optional.of(monetaryAmountType.getAmount());
}
@VisibleForTesting
Optional<BigDecimal> getServiceFeeVATRate(@NonNull final REMADVListLineItemExtensionType.MonetaryAmounts monetaryAmounts)
{
|
if (CollectionUtils.isEmpty(monetaryAmounts.getAdjustment()))
{
logger.log(Level.INFO, "No adjustments found on line! Line:" + remadvLineItemExtension);
return Optional.empty();
}
final List<String> targetAdjustmentCodes = Arrays.asList(ADJUSTMENT_CODE_67, ADJUSTMENT_CODE_90);
final ImmutableSet<BigDecimal> vatTaxRateSet = monetaryAmounts.getAdjustment()
.stream()
.filter(adjustmentType -> targetAdjustmentCodes.contains(adjustmentType.getReasonCode()))
.map(AdjustmentType::getTax)
.filter(Objects::nonNull)
.map(TaxType::getVAT)
.filter(Objects::nonNull)
.map(VATType::getItem)
.flatMap(List::stream)
.map(ItemType::getTaxRate)
.collect(ImmutableSet.toImmutableSet());
if (vatTaxRateSet.size() > 1)
{
throw new RuntimeException("Multiple vatTax rates found on the line! TaxRates: " + vatTaxRateSet);
}
else if (vatTaxRateSet.isEmpty())
{
logger.log(Level.INFO, "No vat tax rates found on line! Line:" + remadvLineItemExtension);
return Optional.empty();
}
else
{
return vatTaxRateSet.stream().findFirst();
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\remadvimport\ecosio\JsonRemittanceAdviceLineProducer.java
| 2
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
|
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java
| 1
|
请完成以下Java代码
|
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 boolean hasPermission(SecurityUser user, Operation operation, UserId userId, User userEntity) {
if (Authority.SYS_ADMIN.equals(userEntity.getAuthority())) {
return false;
}
if (!user.getTenantId().equals(userEntity.getTenantId())) {
return false;
}
return true;
}
};
private static final PermissionChecker widgetsPermissionChecker = new PermissionChecker() {
@Override
public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) {
if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) {
return operation == Operation.READ;
}
if (!user.getTenantId().equals(entity.getTenantId())) {
return false;
}
return true;
}
};
private static final PermissionChecker tbResourcePermissionChecker = new PermissionChecker() {
@Override
public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) {
if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) {
return operation == Operation.READ;
}
if (!user.getTenantId().equals(entity.getTenantId())) {
return false;
}
return true;
}
};
private static final PermissionChecker queuePermissionChecker = new PermissionChecker() {
|
@Override
public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) {
if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) {
return operation == Operation.READ;
}
if (!user.getTenantId().equals(entity.getTenantId())) {
return false;
}
return true;
}
};
private static final PermissionChecker<AiModelId, AiModel> aiModelPermissionChecker = new PermissionChecker<>() {
@Override
public boolean hasPermission(SecurityUser user, Operation operation) {
return true;
}
@Override
public boolean hasPermission(SecurityUser user, Operation operation, AiModelId entityId, AiModel entity) {
return user.getTenantId().equals(entity.getTenantId());
}
};
private static final PermissionChecker<ApiKeyId, ApiKeyInfo> apiKeysPermissionChecker = new PermissionChecker<>() {
@Override
public boolean hasPermission(SecurityUser user, Operation operation) {
return true;
}
@Override
public boolean hasPermission(SecurityUser user, Operation operation, ApiKeyId entityId, ApiKeyInfo entity) {
return user.getTenantId().equals(entity.getTenantId());
}
};
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\permission\TenantAdminPermissions.java
| 2
|
请完成以下Java代码
|
public void validateModel(DomDocument document) {
Schema schema = getSchema(document);
if (schema == null) {
return;
}
Validator validator = schema.newValidator();
try {
synchronized(document) {
validator.validate(document.getDomSource());
}
} catch (IOException e) {
throw new ModelValidationException("Error during DOM document validation", e);
} catch (SAXException e) {
throw new ModelValidationException("DOM document is not valid", e);
}
}
protected Schema getSchema(DomDocument document) {
DomElement rootElement = document.getRootElement();
String namespaceURI = rootElement.getNamespaceURI();
return schemas.get(namespaceURI);
|
}
protected void addSchema(String namespaceURI, Schema schema) {
schemas.put(namespaceURI, schema);
}
protected Schema createSchema(String location, ClassLoader classLoader) {
URL cmmnSchema = ReflectUtil.getResource(location, classLoader);
try {
return schemaFactory.newSchema(cmmnSchema);
} catch (SAXException e) {
throw new ModelValidationException("Unable to parse schema:" + cmmnSchema);
}
}
protected abstract ModelInstance createModelInstance(DomDocument document);
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\parser\AbstractModelParser.java
| 1
|
请完成以下Java代码
|
public void setPromotionCounter (int PromotionCounter)
{
set_ValueNoCheck (COLUMNNAME_PromotionCounter, Integer.valueOf(PromotionCounter));
}
/** Get Usage Counter.
@return Usage counter
*/
public int getPromotionCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionCounter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usage Limit.
@param PromotionUsageLimit
Maximum usage limit
*/
public void setPromotionUsageLimit (int PromotionUsageLimit)
{
set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
|
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java
| 1
|
请完成以下Java代码
|
private NotificationItem toNotificationItem(final Event event)
{
//
// Build summary text
final String summaryTrl = msgBL.getMsg(getCtx(), MSG_Notification_Summary_Default, new Object[] { Adempiere.getName() });
final UserNotification notification = UserNotificationUtils.toUserNotification(event);
//
// Build detail message
final StringBuilder detailBuf = new StringBuilder();
{
// Add plain detail if any
final String detailPlain = notification.getDetailPlain();
if (!Check.isEmpty(detailPlain, true))
{
detailBuf.append(detailPlain.trim());
}
// Translate, parse and add detail (AD_Message).
final String detailADMessage = notification.getDetailADMessage();
if (!Check.isEmpty(detailADMessage, true))
|
{
final String detailTrl = msgBL.getMsg(getCtx(), detailADMessage);
final String detailTrlParsed = EventHtmlMessageFormat.newInstance()
.setArguments(notification.getDetailADMessageParams())
.format(detailTrl);
if (!Check.isEmpty(detailTrlParsed, true))
{
if (detailBuf.length() > 0)
{
detailBuf.append("<br>");
}
detailBuf.append(detailTrlParsed);
}
}
}
return NotificationItem.builder()
.setSummary(summaryTrl)
.setDetail(detailBuf.toString())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierFrame.java
| 1
|
请完成以下Java代码
|
private PaymentReservation updateReservationFromPaypalOrder(@NonNull final PayPalOrder paypalOrder)
{
final PaymentReservationId reservationId = paypalOrder.getPaymentReservationId();
final PaymentReservation reservation = paymentReservationRepo.getById(reservationId);
updateReservationFromPayPalOrderNoSave(reservation, paypalOrder);
paymentReservationRepo.save(reservation);
return reservation;
}
public void authorizePayPalOrder(final PaymentReservation reservation)
{
reservation.getStatus().assertApprovedByPayer();
PayPalOrder paypalOrder = paypalOrderService.getByReservationId(reservation.getId());
final Order apiOrder = paypalClient.authorizeOrder(
paypalOrder.getExternalId(),
createPayPalClientExecutionContext(reservation, paypalOrder));
paypalOrder = paypalOrderService.save(paypalOrder.getId(), apiOrder);
if (!paypalOrder.isAuthorized())
{
throw new AdempiereException("Not authorized: " + paypalOrder);
}
reservation.changeStatusTo(paypalOrder.getStatus().toPaymentReservationStatus());
paymentReservationRepo.save(reservation);
completeSalesOrder(reservation.getSalesOrderId());
}
private void completeSalesOrder(@NonNull final OrderId salesOrderId)
{
final IOrderDAO ordersRepo = Services.get(IOrderDAO.class);
final I_C_Order order = ordersRepo.getById(salesOrderId);
|
final DocStatus orderDocStatus = DocStatus.ofCode(order.getDocStatus());
if (orderDocStatus.isWaitingForPayment())
{
Services.get(IDocumentBL.class).processEx(order, IDocument.ACTION_WaitComplete);
ordersRepo.save(order);
}
}
public void processCapture(
@NonNull final PaymentReservation reservation,
@NonNull final PaymentReservationCapture capture)
{
reservation.getStatus().assertCompleted();
PayPalOrder paypalOrder = paypalOrderService.getByReservationId(capture.getReservationId());
final Boolean finalCapture = null;
final Capture apiCapture = paypalClient.captureOrder(
paypalOrder.getAuthorizationId(),
moneyService.toAmount(capture.getAmount()),
finalCapture,
createPayPalClientExecutionContext(capture, paypalOrder));
paypalOrder = updatePayPalOrderFromAPI(paypalOrder.getExternalId());
updateReservationFromPayPalOrderNoSave(reservation, paypalOrder);
}
private static void updateReservationFromPayPalOrderNoSave(
@NonNull final PaymentReservation reservation,
@NonNull final PayPalOrder payPalOrder)
{
reservation.changeStatusTo(payPalOrder.getStatus().toPaymentReservationStatus());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPal.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getReductionAmount() {
return reductionAmount;
}
/**
* Sets the value of the reductionAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setReductionAmount(BigDecimal value) {
this.reductionAmount = value;
}
/**
* Used to denote details about the reduction rate.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getReductionRate() {
return reductionRate;
|
}
/**
* Sets the value of the reductionRate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setReductionRate(BigDecimal value) {
this.reductionRate = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemReductionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HttpClientSslConfigurer extends AbstractSslConfigurer<HttpClient, HttpClient> {
private final ServerProperties serverProperties;
public HttpClientSslConfigurer(HttpClientProperties.Ssl sslProperties, ServerProperties serverProperties,
SslBundles bundles) {
super(sslProperties, bundles);
this.serverProperties = serverProperties;
}
public HttpClient configureSsl(HttpClient client) {
final HttpClientProperties.Ssl ssl = getSslProperties();
if (getBundle() != null || (ssl.getKeyStore() != null && ssl.getKeyStore().length() > 0)
|| getTrustedX509CertificatesForTrustManager().length > 0 || ssl.isUseInsecureTrustManager()) {
client = client.secure(sslContextSpec -> {
// configure ssl
configureSslContext(ssl, sslContextSpec);
});
}
return client;
}
protected void configureSslContext(HttpClientProperties.Ssl ssl, SslProvider.SslContextSpec sslContextSpec) {
SslProvider.ProtocolSslContextSpec clientSslContext = (serverProperties.getHttp2().isEnabled())
? Http2SslContextSpec.forClient() : Http11SslContextSpec.forClient();
clientSslContext.configure(sslContextBuilder -> {
X509Certificate[] trustedX509Certificates = getTrustedX509CertificatesForTrustManager();
SslBundle bundle = getBundle();
if (trustedX509Certificates.length > 0) {
|
setTrustManager(sslContextBuilder, trustedX509Certificates);
}
else if (ssl.isUseInsecureTrustManager()) {
setTrustManager(sslContextBuilder, InsecureTrustManagerFactory.INSTANCE);
}
else if (bundle != null) {
setTrustManager(sslContextBuilder, bundle.getManagers().getTrustManagerFactory());
}
try {
if (bundle != null) {
sslContextBuilder.keyManager(bundle.getManagers().getKeyManagerFactory());
}
else {
sslContextBuilder.keyManager(getKeyManagerFactory());
}
}
catch (Exception e) {
logger.error(e);
}
});
sslContextSpec.sslContext(clientSslContext)
.handshakeTimeout(ssl.getHandshakeTimeout())
.closeNotifyFlushTimeout(ssl.getCloseNotifyFlushTimeout())
.closeNotifyReadTimeout(ssl.getCloseNotifyReadTimeout());
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientSslConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName();
return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
|
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public EbayFulfillmentProgram getFulfillmentProgram()
{
return fulfillmentProgram;
}
public void setFulfillmentProgram(EbayFulfillmentProgram fulfillmentProgram)
{
this.fulfillmentProgram = fulfillmentProgram;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Program program = (Program)o;
return Objects.equals(this.authenticityVerification, program.authenticityVerification) &&
Objects.equals(this.fulfillmentProgram, program.fulfillmentProgram);
}
@Override
public int hashCode()
{
return Objects.hash(authenticityVerification, fulfillmentProgram);
}
@Override
public String toString()
|
{
StringBuilder sb = new StringBuilder();
sb.append("class Program {\n");
sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n");
sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Program.java
| 2
|
请完成以下Java代码
|
public boolean isScope() {
return scope;
}
@Override
public boolean isMultiInstanceRoot() {
return multiInstanceRoot;
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
|
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("currentActivityId='" + currentActivityId + "'")
.add("processInstanceId='" + processInstanceId + "'")
.add("processDefinitionId='" + processDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java
| 1
|
请完成以下Java代码
|
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Topic Action.
@param TopicAction Topic Action */
public void setTopicAction (String TopicAction)
{
set_Value (COLUMNNAME_TopicAction, TopicAction);
}
/** Get Topic Action.
@return Topic Action */
public String getTopicAction ()
|
{
return (String)get_Value(COLUMNNAME_TopicAction);
}
/** Set Topic Status.
@param TopicStatus Topic Status */
public void setTopicStatus (String TopicStatus)
{
set_Value (COLUMNNAME_TopicStatus, TopicStatus);
}
/** Get Topic Status.
@return Topic Status */
public String getTopicStatus ()
{
return (String)get_Value(COLUMNNAME_TopicStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Topic.java
| 1
|
请完成以下Java代码
|
public void parseLongestText(char[] text, AhoCorasickDoubleArrayTrie.IHit<V> processor)
{
int length = text.length;
for (int i = 0; i < length; ++i)
{
BaseNode<V> state = transition(text[i]);
if (state != null)
{
int to = i + 1;
int end = to;
V value = state.getValue();
for (; to < length; ++to)
{
state = state.transition(text[to]);
if (state == null) break;
if (state.getValue() != null)
{
value = state.getValue();
end = to + 1;
}
}
if (value != null)
{
processor.hit(i, end, value);
i = end - 1;
}
}
}
}
/**
* 匹配文本
*
* @param text 文本
* @param processor 处理器
*/
public void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<V> processor)
{
int length = text.length();
int begin = 0;
BaseNode<V> state = this;
for (int i = begin; i < length; ++i)
{
state = state.transition(text.charAt(i));
if (state != null)
{
V value = state.getValue();
if (value != null)
{
processor.hit(begin, i + 1, value);
}
/*如果是最后一位,这里不能直接跳出循环, 要继续从下一个字符开始判断*/
if (i == length - 1)
{
i = begin;
++begin;
state = this;
}
}
else
{
i = begin;
++begin;
state = this;
}
}
}
/**
* 匹配文本
*
* @param text 文本
* @param processor 处理器
*/
public void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<V> processor)
|
{
int length = text.length;
int begin = 0;
BaseNode<V> state = this;
for (int i = begin; i < length; ++i)
{
state = state.transition(text[i]);
if (state != null)
{
V value = state.getValue();
if (value != null)
{
processor.hit(begin, i + 1, value);
}
/*如果是最后一位,这里不能直接跳出循环, 要继续从下一个字符开始判断*/
if (i == length - 1)
{
i = begin;
++begin;
state = this;
}
}
else
{
i = begin;
++begin;
state = this;
}
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\BinTrie.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class KotlinSerializationHttpMessageConvertersConfiguration {
@Bean
@ConditionalOnMissingBean(KotlinSerializationJsonHttpMessageConverter.class)
KotlinSerializationJsonConvertersCustomizer kotlinSerializationJsonConvertersCustomizer(Json json,
ResourceLoader resourceLoader) {
return new KotlinSerializationJsonConvertersCustomizer(json, resourceLoader);
}
static class KotlinSerializationJsonConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final KotlinSerializationJsonHttpMessageConverter converter;
KotlinSerializationJsonConvertersCustomizer(Json json, ResourceLoader resourceLoader) {
ClassLoader classLoader = resourceLoader.getClassLoader();
boolean hasAnyJsonSupport = ClassUtils.isPresent("tools.jackson.databind.json.JsonMapper", classLoader)
|| ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)
|| ClassUtils.isPresent("com.google.gson.Gson", classLoader);
this.converter = hasAnyJsonSupport ? new KotlinSerializationJsonHttpMessageConverter(json)
: new KotlinSerializationJsonHttpMessageConverter(json, (type) -> true);
|
}
@Override
public void customize(ClientBuilder builder) {
builder.withKotlinSerializationJsonConverter(this.converter);
}
@Override
public void customize(ServerBuilder builder) {
builder.withKotlinSerializationJsonConverter(this.converter);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\KotlinSerializationHttpMessageConvertersConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MultipleBooksController {
@Autowired
private BookService bookService;
@GetMapping(value = "/all")
public String showAll(Model model) {
model.addAttribute("books", bookService.findAll());
return "allBooks";
}
@GetMapping(value = "/create")
public String showCreateForm(Model model) {
BooksCreationDto booksForm = new BooksCreationDto();
for (int i = 1; i <= 3; i++) {
booksForm.addBook(new Book());
}
model.addAttribute("form", booksForm);
return "createBooksForm";
}
|
@GetMapping(value = "/edit")
public String showEditForm(Model model) {
List<Book> books = new ArrayList<>();
bookService.findAll()
.iterator()
.forEachRemaining(books::add);
model.addAttribute("form", new BooksCreationDto(books));
return "editBooksForm";
}
@PostMapping(value = "/save")
public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) {
bookService.saveAll(form.getBooks());
model.addAttribute("books", bookService.findAll());
return "redirect:/books/all";
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\listbindingexample\MultipleBooksController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected void traceValue(Object value, ValueFields valueFields) {
if (trackObjects && valueFields instanceof VariableInstanceEntity) {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration(valueFields);
if (variableServiceConfiguration != null) {
commandContext.addCloseListener(new TraceableVariablesCommandContextCloseListener(
new TraceableObject<>(this, value, jsonMapper.deepCopy(value), (VariableInstanceEntity) valueFields)
));
}
}
}
}
protected VariableServiceConfiguration getVariableServiceConfiguration(ValueFields valueFields) {
String engineType = getEngineType(valueFields.getScopeType());
Map<String, AbstractEngineConfiguration> engineConfigurationMap = Context.getCommandContext().getEngineConfigurations();
AbstractEngineConfiguration engineConfiguration = engineConfigurationMap.get(engineType);
if (engineConfiguration == null) {
for (AbstractEngineConfiguration possibleEngineConfiguration : engineConfigurationMap.values()) {
if (possibleEngineConfiguration instanceof HasVariableServiceConfiguration) {
engineConfiguration = possibleEngineConfiguration;
}
}
}
if (engineConfiguration == null) {
return null;
}
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
|
protected String getEngineType(String scopeType) {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return jsonMapper.isJsonNode(value);
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JsonType.java
| 2
|
请完成以下Java代码
|
public class DocumentBillLocationAdapter
implements IDocumentBillLocationAdapter, RecordBasedLocationAdapter<DocumentBillLocationAdapter>
{
private final I_C_OLCand delegate;
@Getter
@Setter
private String billToAddress;
DocumentBillLocationAdapter(@NonNull final I_C_OLCand delegate)
{
this.delegate = delegate;
}
@Override
public int getBill_BPartner_ID()
{
return delegate.getBill_BPartner_ID();
}
@Override
public void setBill_BPartner_ID(final int Bill_BPartner_ID)
{
delegate.setBill_BPartner_ID(Bill_BPartner_ID);
}
@Override
public int getBill_Location_ID()
{
return delegate.getBill_Location_ID();
}
@Override
public void setBill_Location_ID(final int Bill_Location_ID)
{
delegate.setBill_Location_ID(Bill_Location_ID);
}
@Override
public int getBill_Location_Value_ID()
{
return delegate.getBill_Location_Value_ID();
}
@Override
public void setBill_Location_Value_ID(final int Bill_Location_Value_ID)
{
delegate.setBill_Location_Value_ID(Bill_Location_Value_ID);
}
|
@Override
public int getBill_User_ID()
{
return delegate.getBill_User_ID();
}
@Override
public void setBill_User_ID(final int Bill_User_ID)
{
delegate.setBill_User_ID(Bill_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DocumentBillLocationAdapter toOldValues()
{
return new DocumentBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DocumentBillLocationAdapter.java
| 1
|
请完成以下Java代码
|
public class AuthenticationFilter implements Filter {
public static final String AUTH_CACHE_TTL_INIT_PARAM_NAME = "cacheTimeToLive";
protected Long cacheTimeToLive = null;
public void init(FilterConfig filterConfig) throws ServletException {
String authCacheTTLAsString = filterConfig.getInitParameter(AUTH_CACHE_TTL_INIT_PARAM_NAME);
if (!ServletFilterUtil.isEmpty(authCacheTTLAsString)) {
cacheTimeToLive = Long.parseLong(authCacheTTLAsString.trim());
if (cacheTimeToLive < 0) {
throw new IllegalWebAppConfigurationException("'" + AUTH_CACHE_TTL_INIT_PARAM_NAME + "' cannot be negative.");
}
}
}
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession(true);
// get authentication from session
Authentications authentications = AuthenticationUtil.getAuthsFromSession(session);
if (cacheTimeToLive != null) {
if (cacheTimeToLive > 0) {
ServletContext servletContext = request.getServletContext();
ServletContextUtil.setCacheTTLForLogin(cacheTimeToLive, servletContext);
}
AuthenticationUtil.updateCache(authentications, session, cacheTimeToLive);
}
Authentications.setCurrent(authentications);
|
try {
SecurityActions.runWithAuthentications((SecurityAction<Void>) () -> {
chain.doFilter(request, response);
return null;
}, authentications);
} finally {
Authentications.clearCurrent();
AuthenticationUtil.updateSession(req.getSession(false), authentications);
}
}
public void destroy() {
}
public Long getCacheTimeToLive() {
return cacheTimeToLive;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\AuthenticationFilter.java
| 1
|
请完成以下Java代码
|
public final class WindowId
{
@JsonCreator
public static WindowId fromJson(@NonNull final String json)
{
return new WindowId(json);
}
@Nullable
public static WindowId fromNullableJson(@Nullable final String json)
{
return json != null ? fromJson(json) : null;
}
public static WindowId of(final int windowIdInt)
{
return new WindowId(windowIdInt);
}
public static WindowId of(@NonNull final AdWindowId adWindowId)
{
return new WindowId(adWindowId.getRepoId());
}
public static WindowId of(final DocumentId documentTypeId)
{
if (documentTypeId.isInt())
{
return new WindowId(documentTypeId.toInt());
}
else
{
return new WindowId(documentTypeId.toJson());
}
}
@Nullable
public static WindowId ofNullable(@Nullable final AdWindowId adWindowId)
{
return adWindowId != null ? new WindowId(adWindowId.getRepoId()) : null;
}
private final String value;
private transient OptionalInt valueInt = null; // lazy
private WindowId(final String value)
{
Check.assumeNotEmpty(value, "value is not empty");
this.value = value;
}
private WindowId(final int valueInt)
{
Check.assumeGreaterThanZero(valueInt, "valueInt");
this.valueInt = OptionalInt.of(valueInt);
value = String.valueOf(valueInt);
}
@Override
@Deprecated
public String toString()
{
return toJson();
}
|
@JsonValue
public String toJson()
{
return value;
}
public int toInt()
{
return toOptionalInt()
.orElseThrow(() -> new AdempiereException("WindowId cannot be converted to int: " + this));
}
public int toIntOr(final int fallbackValue)
{
return toOptionalInt()
.orElse(fallbackValue);
}
private OptionalInt toOptionalInt()
{
OptionalInt valueInt = this.valueInt;
if (valueInt == null)
{
valueInt = this.valueInt = parseOptionalInt();
}
return valueInt;
}
private OptionalInt parseOptionalInt()
{
try
{
return OptionalInt.of(Integer.parseInt(value));
}
catch (final Exception ex)
{
return OptionalInt.empty();
}
}
@Nullable
public AdWindowId toAdWindowIdOrNull()
{
return AdWindowId.ofRepoIdOrNull(toIntOr(-1));
}
public AdWindowId toAdWindowId()
{
return AdWindowId.ofRepoId(toInt());
}
public boolean isInt()
{
return toOptionalInt().isPresent();
}
public DocumentId toDocumentId()
{
return DocumentId.of(value);
}
public static boolean equals(@Nullable final WindowId id1, @Nullable final WindowId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\WindowId.java
| 1
|
请完成以下Java代码
|
public List<JsonNode> waitForUpdates(long ms) {
log.trace("update latch count: {}", update.getCount());
try {
if (update.await(ms, TimeUnit.MILLISECONDS)) {
log.trace("Waited for update");
return getLastMsgs();
}
} catch (InterruptedException e) {
log.debug("Failed to await reply", e);
}
log.trace("No update arrived within {} ms", ms);
return null;
}
public JsonNode waitForReply() {
try {
if (reply.await(requestTimeoutMs, TimeUnit.MILLISECONDS)) {
log.trace("Waited for reply");
List<JsonNode> lastMsgs = getLastMsgs();
return lastMsgs.isEmpty() ? null : lastMsgs.get(0);
}
} catch (InterruptedException e) {
log.debug("Failed to await reply", e);
}
log.trace("No reply arrived within {} ms", requestTimeoutMs);
throw new IllegalStateException("No WS reply arrived within " + requestTimeoutMs + " ms");
}
private List<JsonNode> getLastMsgs() {
if (lastMsgs.isEmpty()) {
return lastMsgs;
}
List<JsonNode> errors = lastMsgs.stream()
.map(msg -> msg.get("errorMsg"))
.filter(errorMsg -> errorMsg != null && !errorMsg.isNull() && StringUtils.isNotEmpty(errorMsg.asText()))
.toList();
if (!errors.isEmpty()) {
throw new RuntimeException("WS error from server: " + errors.stream()
.map(JsonNode::asText)
.collect(Collectors.joining(", ")));
}
|
return lastMsgs;
}
public Map<String, String> getLatest(UUID deviceId) {
Map<String, String> updates = new HashMap<>();
getLastMsgs().forEach(msg -> {
EntityDataUpdate update = JacksonUtil.treeToValue(msg, EntityDataUpdate.class);
Map<String, String> latest = update.getLatest(deviceId);
updates.putAll(latest);
});
return updates;
}
@Override
protected void onSetSSLParameters(SSLParameters sslParameters) {
sslParameters.setEndpointIdentificationAlgorithm(null);
}
}
|
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\client\WsClient.java
| 1
|
请完成以下Java代码
|
public int getStatusCode(Status status) {
String code = getUniformCode(status.getCode());
return this.mappings.getOrDefault(code, WebEndpointResponse.STATUS_OK);
}
private static Map<String, Integer> getUniformMappings(Map<String, Integer> mappings) {
Map<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : mappings.entrySet()) {
String code = getUniformCode(entry.getKey());
if (code != null) {
result.putIfAbsent(code, entry.getValue());
}
}
return Collections.unmodifiableMap(result);
}
|
private static @Nullable String getUniformCode(@Nullable String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
return builder.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleHttpCodeStatusMapper.java
| 1
|
请完成以下Java代码
|
public synchronized void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l);
}
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField Model Field
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_GridField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField()
{
|
return m_GridField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VLocation
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocation.java
| 1
|
请完成以下Java代码
|
public static DocTimingType forAction(final String docAction, final BeforeAfterType beforeAfterType)
{
Check.assumeNotEmpty(docAction, "docAction not null");
Check.assumeNotNull(beforeAfterType, "beforeAfterType not null");
// NOTE: no need to use an indexed map because this method is not used very often
for (final DocTimingType timing : values())
{
if (timing.matches(docAction, beforeAfterType))
{
return timing;
}
}
throw new IllegalArgumentException("Unknown DocAction: " + docAction + ", " + beforeAfterType);
}
|
public boolean isVoid()
{
return this == BEFORE_VOID || this == AFTER_VOID;
}
public boolean isReverse()
{
return this == BEFORE_REVERSECORRECT || this == AFTER_REVERSECORRECT
|| this == BEFORE_REVERSEACCRUAL || this == AFTER_REVERSEACCRUAL;
}
public boolean isReactivate()
{
return this == BEFORE_REACTIVATE || this == AFTER_REACTIVATE;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\DocTimingType.java
| 1
|
请完成以下Java代码
|
private PrintingSegment createPrintingSegment(
@NonNull final I_AD_PrinterRouting printerRouting,
@Nullable final UserId userToPrintId,
@Nullable final String hostKey,
final int copies)
{
final I_AD_Printer_Matching printerMatchingRecord = printingDAO.retrievePrinterMatchingOrNull(hostKey/*hostKey*/, userToPrintId, printerRouting.getAD_Printer());
if (printerMatchingRecord == null)
{
logger.debug("Found no AD_Printer_Matching record for AD_PrinterRouting_ID={}, AD_User_PrinterMatchingConfig_ID={} and hostKey={}; -> creating no PrintingSegment for routing",
printerRouting, UserId.toRepoId(userToPrintId), hostKey);
return null;
}
final I_AD_PrinterTray_Matching trayMatchingRecord = printingDAO.retrievePrinterTrayMatching(printerMatchingRecord, printerRouting, false);
final int trayRepoId = trayMatchingRecord == null ? -1 : trayMatchingRecord.getAD_PrinterHW_MediaTray_ID();
final HardwarePrinterId printerId = HardwarePrinterId.ofRepoId(printerMatchingRecord.getAD_PrinterHW_ID());
|
final HardwareTrayId trayId = HardwareTrayId.ofRepoIdOrNull(printerId, trayRepoId);
final HardwarePrinter hardwarePrinter = hardwarePrinterRepository.getById(printerId);
return PrintingSegment.builder()
.printerRoutingId(PrinterRoutingId.ofRepoId(printerRouting.getAD_PrinterRouting_ID()))
.initialPageFrom(printerRouting.getPageFrom())
.initialPageTo(printerRouting.getPageTo())
.lastPages(printerRouting.getLastPages())
.routingType(printerRouting.getRoutingType())
.printer(hardwarePrinter)
.trayId(trayId)
.copies(CoalesceUtil.firstGreaterThanZero(copies, 1))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataFactory.java
| 1
|
请完成以下Java代码
|
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
|
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", profile="
+ this.getProfile() + ", posts=" + this.getPosts() + ", groups=" + this.getGroups() + ")";
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HttpResponse<String> endpoint1() {
log.info("endpoint1");
return HttpResponse.notFound();
}
@Get("/internal-server-error")
public HttpResponse<String> endpoint2(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint2");
if (isErrorSkipped == null) {
throw new RuntimeException("something went wrong");
}
return HttpResponse.ok("Endpoint 2");
}
@Get("/custom-error")
public HttpResponse<String> endpoint3(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint3");
if (isErrorSkipped == null) {
throw new CustomException("something else went wrong");
}
return HttpResponse.ok("Endpoint 3");
}
@Get("/custom-child-error")
public HttpResponse<String> endpoint4(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint4");
if (isErrorSkipped == null) {
throw new CustomChildException("something else went wrong");
|
}
return HttpResponse.ok("Endpoint 4");
}
@Error(exception = UnsupportedOperationException.class)
public HttpResponse<JsonError> unsupportedOperationExceptions(HttpRequest<?> request) {
log.info("Unsupported Operation Exception handled");
JsonError error = new JsonError("Unsupported Operation").link(Link.SELF, Link.of(request.getUri()));
return HttpResponse.<JsonError> notFound()
.body(error);
}
@Get("/unsupported-operation")
public HttpResponse<String> endpoint5() {
log.info("endpoint5");
throw new UnsupportedOperationException();
}
}
|
repos\tutorials-master\microservices-modules\micronaut-configuration\src\main\java\com\baeldung\micronaut\globalexceptionhandler\controller\ErroneousController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getIndexDateSeparator() {
return this.indexDateSeparator;
}
public void setIndexDateSeparator(String indexDateSeparator) {
this.indexDateSeparator = indexDateSeparator;
}
public String getTimestampFieldName() {
return this.timestampFieldName;
}
public void setTimestampFieldName(String timestampFieldName) {
this.timestampFieldName = timestampFieldName;
}
public boolean isAutoCreateIndex() {
return this.autoCreateIndex;
}
public void setAutoCreateIndex(boolean autoCreateIndex) {
this.autoCreateIndex = autoCreateIndex;
}
public @Nullable String getUserName() {
return this.userName;
}
public void setUserName(@Nullable String userName) {
this.userName = userName;
}
public @Nullable String getPassword() {
return this.password;
|
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getPipeline() {
return this.pipeline;
}
public void setPipeline(@Nullable String pipeline) {
this.pipeline = pipeline;
}
public @Nullable String getApiKeyCredentials() {
return this.apiKeyCredentials;
}
public void setApiKeyCredentials(@Nullable String apiKeyCredentials) {
this.apiKeyCredentials = apiKeyCredentials;
}
public boolean isEnableSource() {
return this.enableSource;
}
public void setEnableSource(boolean enableSource) {
this.enableSource = enableSource;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticProperties.java
| 2
|
请完成以下Java代码
|
private I_C_BPartner getBPartnerOrNull(@NonNull final I_M_InOut inOut)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(inOut.getC_BPartner_ID());
return bPartnerId != null
? bpartnerDAO.getById(bPartnerId, I_C_BPartner.class)
: null;
}
@Override
public CurrencyConversionContext getCurrencyConversionContext(@NonNull final InOutId inoutId)
{
final I_M_InOut inout = inOutDAO.getById(inoutId);
return getCurrencyConversionContext(inout);
}
@Override
public CurrencyConversionContext getCurrencyConversionContext(@NonNull final I_M_InOut inout)
{
final CurrencyConversionContext conversionCtx = currencyBL.createCurrencyConversionContext(
inout.getDateAcct().toInstant(),
(CurrencyConversionTypeId)null,
ClientId.ofRepoId(inout.getAD_Client_ID()),
OrgId.ofRepoId(inout.getAD_Org_ID()));
return conversionCtx;
}
@Override
public Money getCOGSBySalesOrderId(
@NonNull final OrderLineId salesOrderLineId,
@NonNull final AcctSchemaId acctSchemaId)
{
final List<FactAcctQuery> factAcctQueries = getLineIdsByOrderLineIds(ImmutableSet.of(salesOrderLineId))
.stream()
.map(inoutAndLineId -> FactAcctQuery.builder()
.acctSchemaId(acctSchemaId)
.accountConceptualName(AccountConceptualName.ofString(I_M_Product_Acct.COLUMNNAME_P_COGS_Acct))
.tableName(I_M_InOut.Table_Name)
.recordId(inoutAndLineId.getInOutId().getRepoId())
.lineId(inoutAndLineId.getInOutLineId().getRepoId())
|
.build())
.collect(Collectors.toList());
return factAcctBL.getAcctBalance(factAcctQueries)
.orElseGet(() -> Money.zero(acctSchemaBL.getAcctCurrencyId(acctSchemaId)));
}
@Override
public ImmutableSet<I_M_InOut> getNotVoidedNotReversedForOrderId(@NonNull final OrderId orderId)
{
final InOutQuery query = InOutQuery.builder()
.orderId(orderId)
.excludeDocStatuses(ImmutableSet.of(DocStatus.Voided, DocStatus.Reversed))
.build();
return inOutDAO.retrieveByQuery(query).collect(ImmutableSet.toImmutableSet());
}
@Override
public void setShipperId(@NonNull final I_M_InOut inout)
{
inout.setM_Shipper_ID(ShipperId.toRepoId(findShipperId(inout)));
}
private ShipperId findShipperId(@NonNull final I_M_InOut inout)
{
if (inout.getDropShip_BPartner_ID() > 0 && inout.getDropShip_Location_ID() > 0)
{
final Optional<ShipperId> deliveryAddressShipperId = bpartnerDAO.getShipperIdByBPLocationId(BPartnerLocationId.ofRepoId(inout.getDropShip_BPartner_ID(), inout.getDropShip_Location_ID()));
if (deliveryAddressShipperId.isPresent())
{
return deliveryAddressShipperId.get(); // we are done
}
}
return bpartnerDAO.getShipperId(CoalesceUtil.coalesceSuppliersNotNull(
() -> BPartnerId.ofRepoIdOrNull(inout.getDropShip_BPartner_ID()),
() -> BPartnerId.ofRepoIdOrNull(inout.getC_BPartner_ID())));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\impl\InOutBL.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
|
this.nm = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is
* {@link PostalAddress6 }
*
*/
public PostalAddress6 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddress6 }
*
*/
public void setPstlAdr(PostalAddress6 value) {
this.pstlAdr = 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\BranchData2.java
| 1
|
请完成以下Java代码
|
protected int argPos(String param, String[] args)
{
return argPos(param, args, true);
}
protected int argPos(String param, String[] args, boolean checkArgNum)
{
for (int i = 0; i < args.length; i++)
{
if (param.equals(args[i]))
{
if (checkArgNum && (i == args.length - 1))
throw new IllegalArgumentException(String.format("Argument missing for %s", param));
return i;
}
}
return -1;
}
|
protected void setConfig(String[] args, Config config)
{
int i;
if ((i = argPos("-size", args)) >= 0) config.setLayer1Size(Integer.parseInt(args[i + 1]));
if ((i = argPos("-output", args)) >= 0) config.setOutputFile(args[i + 1]);
if ((i = argPos("-cbow", args)) >= 0) config.setUseContinuousBagOfWords(Integer.parseInt(args[i + 1]) == 1);
if (config.useContinuousBagOfWords()) config.setAlpha(0.05f);
if ((i = argPos("-alpha", args)) >= 0) config.setAlpha(Float.parseFloat(args[i + 1]));
if ((i = argPos("-window", args)) >= 0) config.setWindow(Integer.parseInt(args[i + 1]));
if ((i = argPos("-sample", args)) >= 0) config.setSample(Float.parseFloat(args[i + 1]));
if ((i = argPos("-hs", args)) >= 0) config.setUseHierarchicalSoftmax(Integer.parseInt(args[i + 1]) == 1);
if ((i = argPos("-negative", args)) >= 0) config.setNegative(Integer.parseInt(args[i + 1]));
if ((i = argPos("-threads", args)) >= 0) config.setNumThreads(Integer.parseInt(args[i + 1]));
if ((i = argPos("-iter", args)) >= 0) config.setIter(Integer.parseInt(args[i + 1]));
if ((i = argPos("-min-count", args)) >= 0) config.setMinCount(Integer.parseInt(args[i + 1]));
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractTrainer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Binding fanoutBinding2(Queue queueTwo, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queueTwo).to(fanoutExchange);
}
/**
* 主题模式队列
* <li>路由格式必须以 . 分隔,比如 user.email 或者 user.aaa.email</li>
* <li>通配符 * ,代表一个占位符,或者说一个单词,比如路由为 user.*,那么 user.email 可以匹配,但是 user.aaa.email 就匹配不了</li>
* <li>通配符 # ,代表一个或多个占位符,或者说一个或多个单词,比如路由为 user.#,那么 user.email 可以匹配,user.aaa.email 也可以匹配</li>
*/
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(RabbitConsts.TOPIC_MODE_QUEUE);
}
/**
* 主题模式绑定分列模式
*
* @param fanoutExchange 分列模式交换器
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding1(FanoutExchange fanoutExchange, TopicExchange topicExchange) {
return BindingBuilder.bind(fanoutExchange).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_ONE);
}
/**
* 主题模式绑定队列2
*
* @param queueTwo 队列2
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding2(Queue queueTwo, TopicExchange topicExchange) {
return BindingBuilder.bind(queueTwo).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_TWO);
}
/**
* 主题模式绑定队列3
*
* @param queueThree 队列3
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding3(Queue queueThree, TopicExchange topicExchange) {
return BindingBuilder.bind(queueThree).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_THREE);
}
/**
* 延迟队列
|
*/
@Bean
public Queue delayQueue() {
return new Queue(RabbitConsts.DELAY_QUEUE, true);
}
/**
* 延迟队列交换器, x-delayed-type 和 x-delayed-message 固定
*/
@Bean
public CustomExchange delayExchange() {
Map<String, Object> args = Maps.newHashMap();
args.put("x-delayed-type", "direct");
return new CustomExchange(RabbitConsts.DELAY_MODE_QUEUE, "x-delayed-message", true, false, args);
}
/**
* 延迟队列绑定自定义交换器
*
* @param delayQueue 队列
* @param delayExchange 延迟交换器
*/
@Bean
public Binding delayBinding(Queue delayQueue, CustomExchange delayExchange) {
return BindingBuilder.bind(delayQueue).to(delayExchange).with(RabbitConsts.DELAY_QUEUE).noargs();
}
}
|
repos\spring-boot-demo-master\demo-mq-rabbitmq\src\main\java\com\xkcoding\mq\rabbitmq\config\RabbitMqConfig.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
|
return false;
} else if (!author.equals(other.author))
return false;
if (id != other.id)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" + author + "]";
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\java\com\baeldung\persistence\model\Book.java
| 1
|
请完成以下Java代码
|
public String getText()
{
return getHtmlText();
}
/**
* Compatible with CTextArea
*
* @param position
*/
public void setCaretPosition(int position)
{
this.editor.setCaretPosition(position);
}
public BoilerPlateContext getAttributes()
{
return boilerPlateMenu.getAttributes();
}
public void setAttributes(final BoilerPlateContext attributes)
{
boilerPlateMenu.setAttributes(attributes);
}
public File getPDF(String fileNamePrefix)
{
throw new UnsupportedOperationException();
}
private void actionPreview()
{
// final ReportEngine re = getReportEngine();
// ReportCtl.preview(re);
File pdf = getPDF(null);
if (pdf != null)
{
Env.startBrowser(pdf.toURI().toString());
}
}
private Dialog getParentDialog()
{
Dialog parent = null;
Container e = getParent();
while (e != null)
{
if (e instanceof Dialog)
{
parent = (Dialog)e;
break;
}
e = e.getParent();
|
}
return parent;
}
public boolean print()
{
throw new UnsupportedOperationException();
}
public static boolean isHtml(String s)
{
if (s == null)
return false;
String s2 = s.trim().toUpperCase();
return s2.startsWith("<HTML>");
}
public static String convertToHtml(String plainText)
{
if (plainText == null)
return null;
return plainText.replaceAll("[\r]*\n", "<br/>\n");
}
public boolean isResolveVariables()
{
return boilerPlateMenu.isResolveVariables();
}
public void setResolveVariables(boolean isResolveVariables)
{
boilerPlateMenu.setResolveVariables(isResolveVariables);
}
public void setEnablePrint(boolean enabled)
{
butPrint.setEnabled(enabled);
butPrint.setVisible(enabled);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
| 1
|
请完成以下Java代码
|
public class MessageEventDefinition extends EventDefinition {
protected String messageRef;
protected String messageExpression;
protected String correlationKey;
protected List<FieldExtension> fieldExtensions = new ArrayList<FieldExtension>();
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public String getMessageRef() {
return messageRef;
}
public void setMessageRef(String messageRef) {
this.messageRef = messageRef;
}
public String getMessageExpression() {
return messageExpression;
}
public void setMessageExpression(String messageExpression) {
|
this.messageExpression = messageExpression;
}
public String getCorrelationKey() {
return correlationKey;
}
public void setCorrelationKey(String correlationKey) {
this.correlationKey = correlationKey;
}
public MessageEventDefinition clone() {
MessageEventDefinition clone = new MessageEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(MessageEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setMessageRef(otherDefinition.getMessageRef());
setMessageExpression(otherDefinition.getMessageExpression());
setFieldExtensions(otherDefinition.getFieldExtensions());
setCorrelationKey(otherDefinition.getCorrelationKey());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MessageEventDefinition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
synchronized public Bucket openBucket(String name, String password) {
if (!buckets.containsKey(name)) {
Bucket bucket = cluster.openBucket(name, password);
buckets.put(name, bucket);
}
return buckets.get(name);
}
@Override
public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
List<JsonDocument> docs = new ArrayList<>();
for (String key : keys) {
JsonDocument doc = bucket.get(key);
if (doc != null) {
docs.add(doc);
}
}
return docs;
}
@Override
|
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
final List<JsonDocument> docs = new ArrayList<>();
try {
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
docs.add(doc);
}
});
} catch (Exception e) {
logger.error("Error during bulk get", e);
}
return docs;
}
}
|
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\spring\service\ClusterServiceImpl.java
| 2
|
请完成以下Spring Boot application配置
|
server.port=8080
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=123456
spring.activemq.in-memory=true
s
|
pring.activemq.pool.enabled=false
jsa.activemq.queue.name=test_queue
|
repos\spring-boot-quick-master\quick-activemq\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID()
{
return M_AttributeSetInstance_ID;
}
public Timestamp getDatePromisedOrNull()
{
return DatePromised;
}
public boolean isRowSelectionAllowed()
{
return rowSelectionAllowed;
}
public static InvoiceHistoryContextBuilder builder()
{
return new InvoiceHistoryContextBuilder();
}
public static class InvoiceHistoryContextBuilder
{
public InvoiceHistoryContext build()
{
return new InvoiceHistoryContext(this);
}
private int C_BPartner_ID = -1;
private int M_Product_ID = -1;
private int M_Warehouse_ID = -1;
private int M_AttributeSetInstance_ID = -1;
private Timestamp DatePromised = null;
private boolean rowSelectionAllowed = false;
public InvoiceHistoryContextBuilder setC_BPartner_ID(final int c_BPartner_ID)
{
C_BPartner_ID = c_BPartner_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_Product_ID(final int m_Product_ID)
{
M_Product_ID = m_Product_ID;
return this;
}
|
public InvoiceHistoryContextBuilder setM_Warehouse_ID(final int m_Warehouse_ID)
{
M_Warehouse_ID = m_Warehouse_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_AttributeSetInstance_ID(final int m_AttributeSetInstance_ID)
{
M_AttributeSetInstance_ID = m_AttributeSetInstance_ID;
return this;
}
public InvoiceHistoryContextBuilder setDatePromised(final Timestamp DatePromised)
{
this.DatePromised = DatePromised;
return this;
}
public InvoiceHistoryContextBuilder setRowSelectionAllowed(final boolean rowSelectionAllowed)
{
this.rowSelectionAllowed = rowSelectionAllowed;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\history\impl\InvoiceHistoryContext.java
| 1
|
请完成以下Java代码
|
public class BaeldungBatchSubscriberImpl<T> implements Subscriber<String> {
private Subscription subscription;
private boolean completed = false;
private int counter;
private ArrayList<String> buffer;
public static final int BUFFER_SIZE = 5;
public BaeldungBatchSubscriberImpl() {
buffer = new ArrayList<String>();
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(BUFFER_SIZE);
}
@Override
public void onNext(String item) {
buffer.add(item);
// if buffer is full, process the items.
if (buffer.size() >= BUFFER_SIZE) {
processBuffer();
}
//request more items.
subscription.request(1);
}
private void processBuffer() {
if (buffer.isEmpty())
return;
// Process all items in the buffer. Here, we just print it and sleep for 1 second.
System.out.print("Processed items: ");
buffer.stream()
.forEach(item -> {
System.out.print(" " + item);
|
});
System.out.println();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter = counter + buffer.size();
buffer.clear();
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
completed = true;
// process any remaining items in buffer before
processBuffer();
subscription.cancel();
}
}
|
repos\tutorials-master\core-java-modules\core-java-9-new-features\src\main\java\com\baeldung\java9\reactive\BaeldungBatchSubscriberImpl.java
| 1
|
请完成以下Java代码
|
public class HistoricCaseActivityStatisticsQueryImpl extends AbstractQuery<HistoricCaseActivityStatisticsQuery, HistoricCaseActivityStatistics> implements
HistoricCaseActivityStatisticsQuery {
private static final long serialVersionUID = 1L;
protected String caseDefinitionId;
public HistoricCaseActivityStatisticsQueryImpl(String caseDefinitionId, CommandExecutor commandExecutor) {
super(commandExecutor);
this.caseDefinitionId = caseDefinitionId;
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return
commandContext
.getHistoricStatisticsManager()
.getHistoricStatisticsCountGroupedByCaseActivity(this);
}
|
public List<HistoricCaseActivityStatistics> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return
commandContext
.getHistoricStatisticsManager()
.getHistoricStatisticsGroupedByCaseActivity(this, page);
}
protected void checkQueryOk() {
super.checkQueryOk();
ensureNotNull("No valid case definition id supplied", "caseDefinitionId", caseDefinitionId);
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseActivityStatisticsQueryImpl.java
| 1
|
请完成以下Java代码
|
public static final LockedByOrNotLockedAtAllFilter of(final ILock lock)
{
return new LockedByOrNotLockedAtAllFilter(lock);
}
// services
private final transient ILockManager lockManager = Services.get(ILockManager.class);
// parameters
private final ILock lock;
// status
private boolean sqlBuilt = false;
private String sql = null;
private LockedByOrNotLockedAtAllFilter(final ILock lock)
{
super();
this.lock = lock;
}
@Override
public String getSql()
{
buildSqlIfNeeded();
return sql;
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
return Collections.emptyList();
}
private final void buildSqlIfNeeded()
{
if (sqlBuilt)
{
return;
}
final String columnNameInvoiceCandidateId = I_C_Invoice_Candidate_Recompute.Table_Name + "." + I_C_Invoice_Candidate_Recompute.COLUMNNAME_C_Invoice_Candidate_ID;
final String lockedWhereClause;
//
// Case: no Lock was mentioned
// => we consider only those records which were NOT locked
if (lock == null)
|
{
lockedWhereClause = lockManager.getNotLockedWhereClause(I_C_Invoice_Candidate.Table_Name, columnNameInvoiceCandidateId);
}
//
// Case: Lock is set
// => we consider only those records which were locked by given lock
else
{
lockedWhereClause = lockManager.getLockedWhereClause(I_C_Invoice_Candidate.class, columnNameInvoiceCandidateId, lock.getOwner());
}
sql = "(" + lockedWhereClause + ")";
sqlBuilt = true;
}
@Override
public boolean accept(final I_C_Invoice_Candidate_Recompute model)
{
if (model == null)
{
return false;
}
final int invoiceCandidateId = model.getC_Invoice_Candidate_ID();
return acceptInvoiceCandidateId(invoiceCandidateId);
}
public boolean acceptInvoiceCandidateId(final int invoiceCandidateId)
{
//
// Case: no Lock was mentioned
// => we consider only those records which were NOT locked
if (lock == null)
{
return !lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId);
}
//
// Case: Lock is set
// => we consider only those records which were locked by given lock
else
{
return lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId, lock.getOwner());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\LockedByOrNotLockedAtAllFilter.java
| 1
|
请完成以下Java代码
|
public void removeAllPauses(final I_C_Flatrate_Term term)
{
final Timestamp distantPast = TimeUtil.getDay(1970, 1, 1);
final Timestamp distantFuture = TimeUtil.getDay(9999, 12, 31);
new RemovePauses(this).removePausesAroundTimeframe(term, distantPast, distantFuture);
resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID()));
}
public final List<I_C_SubscriptionProgress> retrieveNextSPsAndLogIfEmpty(
@NonNull final I_C_Flatrate_Term term,
@NonNull final Timestamp pauseFrom)
{
final ISubscriptionDAO subscriptionDAO = Services.get(ISubscriptionDAO.class);
final SubscriptionProgressQuery query = SubscriptionProgressQuery.builder()
.term(term)
.eventDateNotBefore(pauseFrom)
.build();
final List<I_C_SubscriptionProgress> sps = subscriptionDAO.retrieveSubscriptionProgresses(query);
if (sps.isEmpty())
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
Loggables.addLog(msgBL.getMsg(Env.getCtx(), MSG_NO_SPS_AFTER_DATE_1P, new Object[] { pauseFrom }));
}
return sps;
}
/**
|
* This is needed because no direct parent-child relationship can be established between these tables, as the {@code I_C_SubscriptionProgress} tabs would want to show
* records for which the C_BPartner_ID in context is either the recipient or the contract holder.
*/
private static void resetCache(@NonNull final BPartnerId bpartnerId, @NonNull final FlatrateDataId flatrateDataId)
{
final ModelCacheInvalidationService modelCacheInvalidationService = ModelCacheInvalidationService.get();
modelCacheInvalidationService.invalidate(
CacheInvalidateMultiRequest.of(
CacheInvalidateRequest.allChildRecords(I_C_Flatrate_Data.Table_Name, flatrateDataId, I_C_SubscriptionProgress.Table_Name),
CacheInvalidateRequest.allChildRecords(I_C_BPartner.Table_Name, bpartnerId, I_C_SubscriptionProgress.Table_Name)),
ModelCacheInvalidationTiming.AFTER_CHANGE
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ModelAndView formattingTags(final Model model) {
ModelAndView mv = new ModelAndView("formatting_tags");
return mv;
}
@RequestMapping(value = "/sql_tags", method = RequestMethod.GET)
public ModelAndView sqlTags(final Model model) {
ModelAndView mv = new ModelAndView("sql_tags");
return mv;
}
@RequestMapping(value = "/xml_tags", method = RequestMethod.GET)
public ModelAndView xmlTags(final Model model) {
System.out.println("dddddddddddddddddffffffffffffff");
ModelAndView mv = new ModelAndView("xml_tags");
return mv;
}
@RequestMapping(value = "/items_xml", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/xml");
return new FileSystemResource(new File(servletContext.getRealPath("/WEB-INF/items.xsl")));
}
@RequestMapping(value = "/function_tags", method = RequestMethod.GET)
public ModelAndView functionTags(final Model model) {
|
ModelAndView mv = new ModelAndView("function_tags");
return mv;
}
private void generateDummy(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO USERS " +
"(email, first_name, last_name, registered) VALUES (?, ?, ?, ?);");
preparedStatement.setString(1, "patrick@baeldung.com");
preparedStatement.setString(2, "Patrick");
preparedStatement.setString(3, "Frank");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.addBatch();
preparedStatement.setString(1, "bfrank@baeldung.com");
preparedStatement.setString(2, "Benjamin");
preparedStatement.setString(3, "Franklin");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.executeBatch();
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\jstl\controllers\JSTLController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void add(Collection<ConfigurationMetadataSource> sources) {
for (ConfigurationMetadataSource source : sources) {
String groupId = source.getGroupId();
ConfigurationMetadataGroup group = this.allGroups.computeIfAbsent(groupId,
(key) -> new ConfigurationMetadataGroup(groupId));
String sourceType = source.getType();
if (sourceType != null) {
addOrMergeSource(group.getSources(), sourceType, source);
}
}
}
/**
* Add a {@link ConfigurationMetadataProperty} with the
* {@link ConfigurationMetadataSource source} that defines it, if any.
* @param property the property to add
* @param source the source
*/
public void add(ConfigurationMetadataProperty property, ConfigurationMetadataSource source) {
if (source != null) {
source.getProperties().putIfAbsent(property.getId(), property);
}
getGroup(source).getProperties().putIfAbsent(property.getId(), property);
}
/**
* Merge the content of the specified repository to this repository.
* @param repository the repository to include
*/
public void include(ConfigurationMetadataRepository repository) {
for (ConfigurationMetadataGroup group : repository.getAllGroups().values()) {
ConfigurationMetadataGroup existingGroup = this.allGroups.get(group.getId());
if (existingGroup == null) {
|
this.allGroups.put(group.getId(), group);
}
else {
// Merge properties
group.getProperties().forEach((name, value) -> existingGroup.getProperties().putIfAbsent(name, value));
// Merge sources
group.getSources().forEach((name, value) -> addOrMergeSource(existingGroup.getSources(), name, value));
}
}
}
private ConfigurationMetadataGroup getGroup(ConfigurationMetadataSource source) {
if (source == null) {
return this.allGroups.computeIfAbsent(ROOT_GROUP, (key) -> new ConfigurationMetadataGroup(ROOT_GROUP));
}
return this.allGroups.get(source.getGroupId());
}
private void addOrMergeSource(Map<String, ConfigurationMetadataSource> sources, String name,
ConfigurationMetadataSource source) {
ConfigurationMetadataSource existingSource = sources.get(name);
if (existingSource == null) {
sources.put(name, source);
}
else {
source.getProperties().forEach((k, v) -> existingSource.getProperties().putIfAbsent(k, v));
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\SimpleConfigurationMetadataRepository.java
| 2
|
请完成以下Java代码
|
public byte[] ofbEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] ofbDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[][] ctrEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return new byte[][] { cipher.getIV(), cipher.doFinal(data) };
}
public byte[] ctrDecrypt(SecretKey key, byte[] iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return cipher.doFinal(cipherText);
}
|
public byte[][] gcmEncrypt(SecretKey key, byte[] iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] ciphertext = cipher.doFinal(data);
return new byte[][] { iv, ciphertext };
}
public byte[] gcmDecrypt(SecretKey key, byte[] iv, byte[] ciphertext) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
return plaintext;
}
}
|
repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\CryptoDriver.java
| 1
|
请完成以下Java代码
|
private String getRecordWhere(
final TableNameAndAlias tableNameAndAlias,
final AdTableId adTableId,
final String keyColumnNameFQ,
final Access access)
{
final StringBuilder sqlWhereFinal = new StringBuilder();
//
// Private data record access
final UserId userId = getUserId();
if (!hasAccessToPersonalDataOfOtherUsers())
{
final String sqlWhere = buildPersonalDataRecordAccessSqlWhereClause(adTableId, keyColumnNameFQ, userId);
if (sqlWhereFinal.length() > 0)
{
sqlWhereFinal.append(" AND ");
}
sqlWhereFinal.append(sqlWhere);
}
//
// User/Group record access
{
final String sqlWhere = getUserGroupRecordAccessService().buildUserGroupRecordAccessSqlWhereClause(
tableNameAndAlias.getTableName(),
adTableId,
keyColumnNameFQ,
userId,
getUserGroupIds(),
getRoleId());
if (!Check.isEmpty(sqlWhere))
{
if (sqlWhereFinal.length() > 0)
{
sqlWhereFinal.append(" AND ");
}
sqlWhereFinal.append(sqlWhere);
|
}
}
//
return sqlWhereFinal.toString();
} // getRecordWhere
private String buildPersonalDataRecordAccessSqlWhereClause(
@NonNull final AdTableId adTableId,
@NonNull final String keyColumnNameFQ,
@NonNull final UserId userId)
{
final StringBuilder sql = new StringBuilder(" NOT EXISTS ( SELECT Record_ID FROM " + I_AD_Private_Access.Table_Name
+ " WHERE"
+ " IsActive='Y'"
+ " AND AD_Table_ID=" + adTableId.getRepoId()
+ " AND Record_ID=" + keyColumnNameFQ);
//
// User
sql.append(" AND AD_User_ID <> " + userId.getRepoId());
//
// User Group
final Set<UserGroupId> userGroupIds = getUserGroupIds();
if (!userGroupIds.isEmpty())
{
sql.append(" AND NOT (").append(DB.buildSqlList("AD_UserGroup_ID", userGroupIds)).append(")");
}
//
sql.append(")");
return sql.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsSqlHelpers.java
| 1
|
请完成以下Java代码
|
private ExternalSystemIdWithExternalIds getExternalSystemIdWithExternalIds(@NonNull final JsonCreateReceiptInfo receiptInfo)
{
return ExternalSystemIdWithExternalIds.builder()
.externalSystemId(externalSystemRepository.getIdByType(ExternalSystemType.ofValue(receiptInfo.getExternalSystemCode())))
.externalHeaderIdWithExternalLineIds(ExternalHeaderIdWithExternalLineIds.builder()
.externalHeaderId(ExternalId.of(receiptInfo.getExternalHeaderId()))
.externalLineId(ExternalId.of(receiptInfo.getExternalLineId()))
.build())
.build();
}
//
//
//utility class
private static class ReceiptScheduleCache
{
private final IReceiptScheduleDAO receiptScheduleDAO;
private final HashMap<ReceiptScheduleId, I_M_ReceiptSchedule> receiptScheduleHashMap = new HashMap<>();
private ReceiptScheduleCache(@NonNull final IReceiptScheduleDAO receiptScheduleDAO)
{
this.receiptScheduleDAO = receiptScheduleDAO;
}
void refreshCacheForIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds)
{
this.receiptScheduleHashMap.putAll(receiptScheduleDAO.getByIds(receiptScheduleIds));
}
private I_M_ReceiptSchedule getById(@NonNull final ReceiptScheduleId receiptScheduleId)
{
return this.receiptScheduleHashMap.computeIfAbsent(receiptScheduleId, receiptScheduleDAO::getById);
|
}
private List<I_M_ReceiptSchedule> getByIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds)
{
return receiptScheduleIds.stream()
.map(this::getById)
.collect(ImmutableList.toImmutableList());
}
private OrgId getOrgId(@NonNull final ReceiptScheduleId receiptScheduleId)
{
final I_M_ReceiptSchedule receiptSchedule = getById(receiptScheduleId);
return OrgId.ofRepoId(receiptSchedule.getAD_Org_ID());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\ReceiptService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setLastNotifyTime(Date lastNotifyTime) {
this.lastNotifyTime = lastNotifyTime;
}
/** 通知次数 **/
public Integer getNotifyTimes() {
return notifyTimes;
}
/** 通知次数 **/
public void setNotifyTimes(Integer notifyTimes) {
this.notifyTimes = notifyTimes;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
|
/** 限制通知次数 **/
public Integer getLimitNotifyTimes() {
return limitNotifyTimes;
}
/** 限制通知次数 **/
public void setLimitNotifyTimes(Integer limitNotifyTimes) {
this.limitNotifyTimes = limitNotifyTimes;
}
public String getBankOrderNo() {
return bankOrderNo;
}
public void setBankOrderNo(String bankOrderNo) {
this.bankOrderNo = bankOrderNo;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpOrderResultQueryVo.java
| 2
|
请完成以下Java代码
|
public class VariableValue<T extends TypedValue> {
protected String executionId;
protected String variableName;
protected TypedValueField typedValueField;
protected ValueMappers mappers;
protected ValueMapper<T> serializer;
protected T cachedValue;
public VariableValue(String executionId, String variableName, TypedValueField typedValueField, ValueMappers mappers) {
this.executionId = executionId;
this.variableName = variableName;
this.typedValueField = typedValueField;
this.mappers = mappers;
}
public Object getValue() {
TypedValue typedValue = getTypedValue();
if (typedValue != null) {
return typedValue.getValue();
} else {
return null;
}
}
public T getTypedValue() {
return getTypedValue(true);
}
public T getTypedValue(boolean deserializeValue) {
if (cachedValue != null && cachedValue instanceof SerializableValue) {
SerializableValue serializableValue = (SerializableValue) cachedValue;
if(deserializeValue && !serializableValue.isDeserialized()) {
cachedValue = null;
}
}
if (cachedValue == null) {
cachedValue = getSerializer().readValue(typedValueField, deserializeValue);
if (cachedValue instanceof DeferredFileValueImpl) {
DeferredFileValueImpl fileValue = (DeferredFileValueImpl) cachedValue;
fileValue.setExecutionId(executionId);
|
fileValue.setVariableName(variableName);
}
}
return cachedValue;
}
@SuppressWarnings("unchecked")
public ValueMapper<T> getSerializer() {
if (serializer == null) {
serializer = mappers.findMapperForTypedValueField(typedValueField);
}
return serializer;
}
@Override
public String toString() {
return "VariableValue ["
+ "cachedValue=" + cachedValue + ", "
+ "executionId=" + executionId + ", "
+ "variableName=" + variableName + ", "
+ "typedValueField=" + typedValueField + "]";
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\VariableValue.java
| 1
|
请完成以下Java代码
|
public Message sayHello() {
return new Message().setMessage(String.format(
"hello %s, it's %s",
RestxSession.current().getPrincipal().get().getName(),
DateTime.now(DateTimeZone.UTC).toString("HH:mm:ss")));
}
/**
* Say hello to anybody.
*
* Does not require authentication.
*
* @return a Message to say hello
*/
@GET("/hello")
@PermitAll
public Message helloPublic(String who) {
return new Message().setMessage(String.format(
|
"hello %s, it's %s",
who, DateTime.now(DateTimeZone.UTC).toString("HH:mm:ss")));
}
public static class MyPOJO {
@NotNull
String value;
public String getValue(){ return value; }
public void setValue(String value){ this.value = value; }
}
@POST("/mypojo")
@PermitAll
public MyPOJO helloPojo(MyPOJO pojo){
pojo.setValue("hello "+pojo.getValue());
return pojo;
}
}
|
repos\tutorials-master\web-modules\restx\src\main\java\restx\demo\rest\HelloResource.java
| 1
|
请完成以下Java代码
|
public class WebuiSessionId
{
@JsonCreator
public static WebuiSessionId ofString(@NonNull final String sessionId)
{
return new WebuiSessionId(sessionId);
}
@Nullable
public static WebuiSessionId ofNullableString(@Nullable final String sessionId)
{
final String sessionIdNorm = StringUtils.trimBlankToNull(sessionId);
return sessionIdNorm != null ? new WebuiSessionId(sessionIdNorm) : null;
}
private final String sessionId;
private WebuiSessionId(@NonNull final String sessionId)
{
this.sessionId = StringUtils.trimBlankToNull(sessionId);
if (this.sessionId == null)
{
|
throw new AdempiereException("sessionId shall not be empty");
}
}
/**
* @deprecated please use {@link #getAsString()}
*/
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return sessionId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\json\WebuiSessionId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> edit(@RequestBody SysMessage sysMessage) {
sysMessageService.updateById(sysMessage);
return Result.ok("修改成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysMessageService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysMessageService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
|
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessage sysMessage = sysMessageService.getById(id);
return Result.ok(sysMessage);
}
/**
* 导出excel
*
* @param request
*/
@GetMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) {
return super.exportXls(request,sysMessage,SysMessage.class, "推送消息模板");
}
/**
* excel导入
*
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importExcel")
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysMessage.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\SysMessageController.java
| 2
|
请完成以下Java代码
|
protected final void setPattern(String pattern, String applicationPath) {
String[] parts = pattern.split("/");
ArrayList<String> groupList = new ArrayList<String>();
StringBuilder regexBuilder = new StringBuilder();
if (!applicationPath.isEmpty()) {
regexBuilder.append(applicationPath);
}
boolean first = true;
for (String part: parts) {
String group = null;
String regex = part;
// parse group
if (part.startsWith("{") && part.endsWith("}")) {
String groupStr = part.substring(1, part.length() - 1);
String[] groupSplit = groupStr.split(":");
if (groupSplit.length > 2) {
throw new IllegalArgumentException("cannot parse uri part " + regex + " in " + pattern + ": expected {asdf(:pattern)}");
}
group = groupSplit[0];
|
if (groupSplit.length > 1) {
regex = "(" + groupSplit[1] + ")";
} else {
regex = "([^/]+)";
}
}
if (!first) {
regexBuilder.append("/");
} else {
first = false;
}
regexBuilder.append(regex);
if (group != null) {
groupList.add(group);
}
}
this.groups = groupList.toArray(new String[0]);
this.pattern = Pattern.compile(regexBuilder.toString());
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\RequestFilter.java
| 1
|
请完成以下Java代码
|
private boolean isTypeMatch(PropertyDescriptor property, Object value) {
return value == null || property.getPropertyType().isInstance(value);
}
@Override
public String getClassName() {
return getParent().getClassName();
}
@Override
public boolean isDeserializable() {
return getParent().isDeserializable();
}
@Override
public boolean isEnum() {
return getParent().isEnum();
}
@Override
public Object getField(String fieldName) {
return getParent().getField(fieldName);
}
@Override
public List<String> getFieldNames() {
return getParent().getFieldNames();
}
@Override
public boolean isIdentityField(String fieldName) {
return getParent().isIdentityField(fieldName);
}
@Override
public Object getObject() {
|
return getParent().getObject();
}
@Override
public WritablePdxInstance createWriter() {
return this;
}
@Override
public boolean hasField(String fieldName) {
return getParent().hasField(fieldName);
}
};
}
/**
* Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
* on the underlying, target {@link Object}.
*
* @param fieldName {@link String} containing the name of the field to match against
* a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
* @return a boolean value that determines whether the given {@link String field name}
* is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
* @see #getFieldNames()
*/
@Override
public boolean hasField(String fieldName) {
return getFieldNames().contains(fieldName);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.