instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
class Authenticator implements Interceptor { private final String apiKey; Authenticator(String apiKey) { this.apiKey = apiKey; } @Override public Response intercept(Chain chain) throws IOException { HttpUrl url = chain .request() .url() .newBuilder() .addQueryParameter("api_key", apiKey) .build(); Request request = chain .request() .newBuilder() .url(url) .build(); return chain.proceed(request); } } @JsonAutoDetect(fieldVisibility = ANY) class TopTags { private Map<String, Object> tags; @SuppressWarnings("unchecked") public Set<String> all() { List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag"); return topTags .stream() .map(e -> ((String) e.get("name"))) .collect(Collectors.toSet()); } } @JsonAutoDetect(fieldVisibility = ANY) class Tags { @JsonProperty("toptags") private Map<String, Object> topTags;
@SuppressWarnings("unchecked") public Map<String, Double> all() { try { Map<String, Double> all = new HashMap<>(); List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag"); for (Map<String, Object> tag : tags) { all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue()); } return all; } catch (Exception e) { return Collections.emptyMap(); } } } @JsonAutoDetect(fieldVisibility = ANY) class Artists { private Map<String, Object> artists; @SuppressWarnings("unchecked") public List<String> all() { try { List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist"); return artists .stream() .map(e -> ((String) e.get("name"))) .collect(toList()); } catch (Exception e) { return Collections.emptyList(); } } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\LastFmService.java
1
请在Spring Boot框架中完成以下Java代码
public class OpenApiLogController extends JeecgController<OpenApiLog, OpenApiLogService> { /** * 分页列表查询 * * @param OpenApiLog * @param pageNo * @param pageSize * @param req * @return */ @GetMapping(value = "/list") public Result<?> queryPageList(OpenApiLog OpenApiLog, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { QueryWrapper<OpenApiLog> queryWrapper = QueryGenerator.initQueryWrapper(OpenApiLog, req.getParameterMap()); Page<OpenApiLog> page = new Page<>(pageNo, pageSize); IPage<OpenApiLog> pageList = service.page(page, queryWrapper); return Result.ok(pageList); } /** * 添加 * * @param OpenApiLog * @return */ @PostMapping(value = "/add") public Result<?> add(@RequestBody OpenApiLog OpenApiLog) { service.save(OpenApiLog); return Result.ok("添加成功!"); } /** * 编辑 * * @param OpenApiLog * @return */ @PutMapping(value = "/edit") public Result<?> edit(@RequestBody OpenApiLog OpenApiLog) { service.updateById(OpenApiLog); return Result.ok("修改成功!"); } /** * 通过id删除 * * @param id * @return */ @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name = "id", required = true) String id) { service.removeById(id); return Result.ok("删除成功!"); }
/** * 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.service.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) { OpenApiLog OpenApiLog = service.getById(id); return Result.ok(OpenApiLog); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiLogController.java
2
请在Spring Boot框架中完成以下Java代码
private GetPurchaseOrderFromFileRouteBuilder getPurchaseOrdersFromFileRouteBuilder(@NonNull final JsonExternalSystemRequest request, @NonNull final CamelContext camelContext) { return GetPurchaseOrderFromFileRouteBuilder .builder() .fileEndpointConfig(PCMConfigUtil.extractLocalFileConfig(request, camelContext)) .camelContext(camelContext) .enabledByExternalSystemRequest(request) .processLogger(processLogger) .routeId(getPurchaseOrdersFromLocalFileRouteId(request)) .build(); } @NonNull @VisibleForTesting public static String getPurchaseOrdersFromLocalFileRouteId(@NonNull final JsonExternalSystemRequest externalSystemRequest) { return "GetPurchaseOrderFromLocalFile#" + externalSystemRequest.getExternalSystemChildConfigValue(); } @Override public String getServiceValue() { return "LocalFileSyncPurchaseOrders"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME;
} @Override public String getEnableCommand() { return START_PURCHASE_ORDER_SYNC_LOCAL_FILE_ROUTE; } @Override public String getDisableCommand() { return STOP_PURCHASE_ORDER_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartPurchaseOrderRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopPurchaseOrderRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\LocalFilePurchaseOrderSyncServicePCMRouteBuilder.java
2
请完成以下Java代码
public void setIsUseForPartnerRequestWindow (boolean IsUseForPartnerRequestWindow) { set_Value (COLUMNNAME_IsUseForPartnerRequestWindow, Boolean.valueOf(IsUseForPartnerRequestWindow)); } /** Get IsUseForPartnerRequestWindow. @return Flag that tells if the R_Request entries of this type will be displayed or not in the business partner request window (Vorgang) */ @Override public boolean isUseForPartnerRequestWindow () { Object oo = get_Value(COLUMNNAME_IsUseForPartnerRequestWindow); 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 */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ @Override public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ @Override public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } @Override
public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class); } @Override public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory) { set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory); } /** Set Status Category. @param R_StatusCategory_ID Request Status Category */ @Override public void setR_StatusCategory_ID (int R_StatusCategory_ID) { if (R_StatusCategory_ID < 1) set_Value (COLUMNNAME_R_StatusCategory_ID, null); else set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID)); } /** Get Status Category. @return Request Status Category */ @Override public int getR_StatusCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestType.java
1
请在Spring Boot框架中完成以下Java代码
public Address getSender() { return sender; } /** * Sets the value of the sender property. * * @param value * allowed object is * {@link Address } * */ public void setSender(Address value) { this.sender = value; } /** * Gets the value of the recipient property. * * @return * possible object is * {@link Address } *
*/ public Address getRecipient() { return recipient; } /** * Sets the value of the recipient property. * * @param value * allowed object is * {@link Address } * */ public void setRecipient(Address value) { this.recipient = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\GeneralShipmentData.java
2
请完成以下Java代码
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { ScriptingEngines scriptingEngines = CommandContextUtil.getCmmnEngineConfiguration().getScriptingEngines(); if (scriptingEngines == null) { throw new FlowableException("Could not execute script task instance: no scripting engines found. For " + planItemInstanceEntity); } String scriptFormat = scriptTask.getScriptFormat() != null ? scriptTask.getScriptFormat() : ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE; try { ScriptEngineRequest.Builder request = ScriptEngineRequest.builder() .language(scriptFormat) .script(scriptTask.getScript()) .scopeContainer(planItemInstanceEntity) .traceEnhancer(trace -> trace.addTraceTag("type", "scriptTask")); if (scriptTask.isAutoStoreVariables()) { request.storeScriptVariables(); } List<IOParameter> inParameters = scriptTask.getInParameters(); if (inParameters != null && !inParameters.isEmpty()) { MapDelegateVariableContainer inputVariableContainer = new MapDelegateVariableContainer(); IOParameterUtil.processInParameters(inParameters, planItemInstanceEntity, inputVariableContainer, CommandContextUtil.getExpressionManager(commandContext)); request.inputVariableContainer(inputVariableContainer); } else if (scriptTask.isDoNotIncludeVariables()) { request.inputVariableContainer(VariableContainer.empty()); }
Object result = scriptingEngines.evaluate(request.build()).getResult(); String resultVariableName = scriptTask.getResultVariableName(); if (StringUtils.isNotBlank(scriptTask.getResultVariableName())) { planItemInstanceEntity.setVariable(resultVariableName.trim(), result); } CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstanceEntity); } catch (FlowableException e) { Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause instanceof FlowableException) { throw (FlowableException) rootCause; } else { throw e; } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\ScriptTaskActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public void setType(@Nullable List<PropagationType> type) { this.type = type; } public void setProduce(List<PropagationType> produce) { this.produce = produce; } public void setConsume(List<PropagationType> consume) { this.consume = consume; } public @Nullable List<PropagationType> getType() { return this.type; } public List<PropagationType> getProduce() { return this.produce; } public List<PropagationType> getConsume() { return this.consume; } /**
* Supported propagation types. The declared order of the values matter. */ public enum PropagationType { /** * <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation. */ W3C, /** * <a href="https://github.com/openzipkin/b3-propagation#single-header">B3 * single header</a> propagation. */ B3, /** * <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3 * multiple headers</a> propagation. */ B3_MULTI } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java
2
请完成以下Java代码
public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getRemote_Addr()); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set User Agent. @param UserAgent Browser Used */ public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } public I_W_CounterCount getW_CounterCount() throws RuntimeException { return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name) .getPO(getW_CounterCount_ID(), get_TrxName()); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); }
/** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Web Counter. @param W_Counter_ID Individual Count hit */ public void setW_Counter_ID (int W_Counter_ID) { if (W_Counter_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID)); } /** Get Web Counter. @return Individual Count hit */ public int getW_Counter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Counter.java
1
请在Spring Boot框架中完成以下Java代码
public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId;
} public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the link property. * * @return * possible object is * {@link String } * */ public String getLink() { return link;
} /** * Sets the value of the link property. * * @param value * allowed object is * {@link String } * */ public void setLink(String value) { this.link = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AttachmentsType.java
2
请完成以下Java代码
public void setInputs(List<HistoricDecisionInputInstance> inputs) { this.inputs = inputs; } public void setOutputs(List<HistoricDecisionOutputInstance> outputs) { this.outputs = outputs; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); } public void addInput(HistoricDecisionInputInstance decisionInputInstance) { if(inputs == null) { inputs = new ArrayList<HistoricDecisionInputInstance>(); } inputs.add(decisionInputInstance); } public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) { if(outputs == null) { outputs = new ArrayList<HistoricDecisionOutputInstance>(); } outputs.add(decisionOutputInstance); } public Double getCollectResultValue() { return collectResultValue; } public void setCollectResultValue(Double collectResultValue) {
this.collectResultValue = collectResultValue; } public String getRootDecisionInstanceId() { return rootDecisionInstanceId; } public void setRootDecisionInstanceId(String rootDecisionInstanceId) { this.rootDecisionInstanceId = rootDecisionInstanceId; } public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java
1
请完成以下Java代码
public class StockDetailsRowsData implements IRowsData<StockDetailsRow> { public static StockDetailsRowsData of(@NonNull final Stream<HUStockInfo> huStockInfos) { return new StockDetailsRowsData(huStockInfos); } private final Map<DocumentId, StockDetailsRow> document2StockDetailsRow; private StockDetailsRowsData(@NonNull final Stream<HUStockInfo> huStockInfos) { final ImmutableMap.Builder<DocumentId, StockDetailsRow> builder = ImmutableMap.builder(); final Iterator<HUStockInfo> iterator = huStockInfos.iterator(); while (iterator.hasNext()) { final HUStockInfo huStockInfo = iterator.next(); final StockDetailsRow row = StockDetailsRow.of(huStockInfo); builder.put(row.getId(), row); } document2StockDetailsRow = builder.build(); }
@Override public Map<DocumentId, StockDetailsRow> getDocumentId2TopLevelRows() { return document2StockDetailsRow; } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { return DocumentIdsSelection.EMPTY; } @Override public void invalidateAll() { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsRowsData.java
1
请在Spring Boot框架中完成以下Java代码
public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-bpmn-2.0-process") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } @ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } @ApiModelProperty(example = "someTenantId") public String getTenantId() { return tenantId; } // Added by Ryan Johnston public boolean isCompleted() { return completed; } // Added by Ryan Johnston public void setCompleted(boolean completed) { this.completed = completed; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceResponse.java
2
请完成以下Java代码
public static DocumentPrintOptions ofMap( @NonNull final Map<String, String> map, @Nullable final String sourceName) { if (map.isEmpty() && sourceName == null) { return NONE; } final HashMap<String, Boolean> options = new HashMap<>(); for (final String name : map.keySet()) { final Boolean value = StringUtils.toBoolean(map.get(name), null); if (value == null) { continue; } options.put(name, value); } return builder() .sourceName(sourceName) .options(options) .build(); } public boolean isEmpty() { return options.isEmpty(); } private boolean isNone() { return this.equals(NONE); } public ImmutableSet<String> getOptionNames() { if (fallback != null && !fallback.isEmpty()) { return ImmutableSet.<String>builder() .addAll(options.keySet()) .addAll(fallback.getOptionNames()) .build(); } else { return options.keySet(); } } public DocumentPrintOptionValue getOption(@NonNull final String name) { final Boolean value = options.get(name); if (value != null) { return DocumentPrintOptionValue.builder() .value(OptionalBoolean.ofBoolean(value)) .sourceName(sourceName) .build(); } else if (fallback != null) { return fallback.getOption(name); } else
{ return DocumentPrintOptionValue.MISSING; } } public DocumentPrintOptions mergeWithFallback(@NonNull final DocumentPrintOptions fallback) { if (fallback.isNone()) { return this; } else if (isNone()) { return fallback; } else { if (this == fallback) { throw new IllegalArgumentException("Merging with itself is not allowed"); } final DocumentPrintOptions newFallback; if (this.fallback != null) { newFallback = this.fallback.mergeWithFallback(fallback); } else { newFallback = fallback; } return !Objects.equals(this.fallback, newFallback) ? toBuilder().fallback(newFallback).build() : this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptions.java
1
请完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext() == this.applicationContext) { this.contextRefreshed = true; } } public JmsOperations getJmsOperations() { return jmsOperations; } public void setJmsOperations(JmsOperations jmsOperations) { this.jmsOperations = jmsOperations; } public JmsListenerEndpointRegistry getEndpointRegistry() { return endpointRegistry; }
public void setEndpointRegistry(JmsListenerEndpointRegistry endpointRegistry) { this.endpointRegistry = endpointRegistry; } public String getContainerFactoryBeanName() { return containerFactoryBeanName; } public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } public JmsListenerContainerFactory<?> getContainerFactory() { return containerFactory; } public void setContainerFactory(JmsListenerContainerFactory<?> containerFactory) { this.containerFactory = containerFactory; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsChannelModelProcessor.java
1
请完成以下Java代码
public ILatchStragegy getLatchStrategy() { return NullLatchStrategy.INSTANCE; } public final <T> List<T> retrieveItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType); } /** * Retrieves all active POs, even the ones that are caught in other packages */ public final <T> List<T> retrieveAllItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType);
} public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems) { return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems); } /** * retrieves all active PO's IDs, even the ones that are caught in other packages */ public final Set<Integer> retrieveAllItemIds() { return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .junction("SJ") .state("high") .state("medium") .state("low") .end("SF"); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions.withExternal() .source("SI").target("SJ").event("E1") .and() .withJunction()
.source("SJ") .first("high", highGuard()) .then("medium", mediumGuard()) .last("low") .and().withExternal() .source("low").target("SF").event("end"); } @Bean public Guard<String, String> mediumGuard() { return ctx -> false; } @Bean public Guard<String, String> highGuard() { return ctx -> false; } }
repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\JunctionStateMachineConfiguration.java
2
请完成以下Java代码
public void afterPropertiesSet() throws Exception { if (this.debug) { System.setProperty("sun.security.krb5.debug", "true"); } if (this.krbConfLocation != null) { System.setProperty("java.security.krb5.conf", this.krbConfLocation); } } /** * Enable debug logs from the Sun Kerberos Implementation. Default is false. * @param debug true if debug should be enabled */ public void setDebug(boolean debug) { this.debug = debug; } /** * Kerberos config file location can be specified here. * @param krbConfLocation the path to krb config file */ public void setKrbConfLocation(String krbConfLocation) { this.krbConfLocation = krbConfLocation; } // The following methods are not used here. This Bean implements only
// BeanPostProcessor to ensure that it // is created before any other bean is created, because the system properties needed // to be set very early // in the startup-phase, but after the BeanFactoryPostProcessing. @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\GlobalSunJaasKerberosConfig.java
1
请完成以下Java代码
public void setUserElementString6 (final @Nullable String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVATCode (final @Nullable String VATCode) { set_Value (COLUMNNAME_VATCode, VATCode); } @Override public String getVATCode() { return get_ValueAsString(COLUMNNAME_VATCode); } @Override public org.compiere.model.I_C_CostClassification_Category getC_CostClassification_Category() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class); } @Override public void setC_CostClassification_Category(final org.compiere.model.I_C_CostClassification_Category C_CostClassification_Category) {
set_ValueFromPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class, C_CostClassification_Category); } @Override public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID) { if (C_CostClassification_Category_ID < 1) set_Value (COLUMNNAME_C_CostClassification_Category_ID, null); else set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID); } @Override public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID); } @Override public org.compiere.model.I_C_CostClassification getC_CostClassification() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class); } @Override public void setC_CostClassification(final org.compiere.model.I_C_CostClassification C_CostClassification) { set_ValueFromPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class, C_CostClassification); } @Override public void setC_CostClassification_ID (final int C_CostClassification_ID) { if (C_CostClassification_ID < 1) set_Value (COLUMNNAME_C_CostClassification_ID, null); else set_Value (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID); } @Override public int getC_CostClassification_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Fact_Acct_Transactions_View.java
1
请完成以下Java代码
public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public boolean isWorking() { return isWorking; } public void waitForComplete(int timeout) { setTimeout(timeout); waitForComplete(); } public void stop() { workerThread.interrupt(); } public void waitForComplete() { boolean to = getTimeout() > -1;
int c = 0; int i = 1000; while(isWorking()) { try { Thread.sleep(i); c+= to ? c+=i : -1; } catch(Exception e) {} if(to && c >= getTimeout()) { workerThread.interrupt(); workerThread = null; break; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\tools\worker\MultiWorker.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { @Autowired EmployeeService employeeService; @Autowired private RedisTemplate redisTemplate; @GetMapping(value = "/list") public List<Employee> getEmployees() { return employeeService.list( null ); } @GetMapping(value = "/{id}") public Employee getEmployeeById(@PathVariable("id") int id) { return employeeService.getById( id ); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String updateEmployee(@PathVariable("id") int id, @RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) { Employee employee = new Employee(); employee.setId( id ); employee.setLastName( lastName ); employee.setEmail( email ); employee.setGender( gender ); employee.setDId( dId ); Employee res = employeeService.updateEmployeeById( employee ); if (res != null) { return "update success"; } else { return "update fail"; }
} @DeleteMapping(value = "/{id}") public String delete(@PathVariable(value = "id")int id) { boolean b = employeeService.removeById( id ); if(b) { return "delete success"; }else { return "delete fail"; } } @PostMapping(value = "") public String postEmployee(@RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) { Employee employee = new Employee(); employee.setLastName( lastName ); employee.setEmail( email ); employee.setGender( gender ); employee.setDId( dId ); boolean b = employeeService.save( employee ); if(b) { return "sava success"; }else { return "sava fail"; } } }
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\controller\EmployeeController.java
2
请完成以下Java代码
public class EventModel { protected String key; protected String name; protected Map<String, EventPayload> payload = new LinkedHashMap<>(); public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonIgnore public Collection<EventPayload> getHeaders() { return payload.values() .stream() .filter(EventPayload::isHeader) .collect(Collectors.toList()); } @JsonIgnore public Collection<EventPayload> getCorrelationParameters() { return payload.values() .stream() .filter(EventPayload::isCorrelationParameter) .collect(Collectors.toList()); } public EventPayload getPayload(String name) { return payload.get(name); } @JsonGetter public Collection<EventPayload> getPayload() { return payload.values(); } @JsonSetter public void setPayload(Collection<EventPayload> payload) { for (EventPayload eventPayload : payload) { this.payload.put(eventPayload.getName(), eventPayload); } } public void addHeader(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setHeader(true); } else { payload.put(name, EventPayload.header(name, type));
} } public void addPayload(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setType(type); } else { payload.put(name, new EventPayload(name, type)); } } public void addPayload(EventPayload payload) { this.payload.put(payload.getName(), payload); } public void addCorrelation(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setCorrelationParameter(true); } else { payload.put(name, EventPayload.correlation(name, type)); } } public void addFullPayload(String name) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setFullPayload(true); eventPayload.setCorrelationParameter(false); eventPayload.setHeader(false); } else { payload.put(name, EventPayload.fullPayload(name)); } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventModel.java
1
请完成以下Java代码
protected void transformFunctions(List<FeelCustomFunctionProvider> functionProviders) { functionProviders.forEach(functionProvider -> { Collection<String> functionNames = functionProvider.getFunctionNames(); functionNames.forEach(functionName -> { CustomFunction customFunction = functionProvider.resolveFunction(functionName) .orElseThrow(LOGGER::customFunctionNotFoundException); List<String> params = customFunction.getParams(); Function<List<Val>, Val> function = transformFunction(customFunction); boolean hasVarargs = customFunction.hasVarargs(); JavaFunction javaFunction = new JavaFunction(params, function, hasVarargs); this.functions.put(functionName, javaFunction); }); }); } protected Function<List<Val>, Val> transformFunction(CustomFunction function) { return args -> { List<Object> unpackedArgs = unpackVals(args); Function<List<Object>, Object> functionHandler = function.getFunction(); Object result = functionHandler.apply(unpackedArgs); return toVal(result); }; } protected List<Object> unpackVals(List<Val> args) { return args.stream() .map(this::unpackVal)
.collect(Collectors.toList()); } protected Val toVal(Object rawResult) { return valueMapper.toVal(rawResult); } protected Object unpackVal(Val arg) { return valueMapper.unpackVal(arg); } @Override public Optional<JavaFunction> resolveFunction(String functionName) { return Optional.ofNullable(functions.get(functionName)); } @Override public Collection<String> getFunctionNames() { return functions.keySet(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\function\CustomFunctionTransformer.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((country == null) ? 0 : country.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; NameCountriesEntity other = (NameCountriesEntity) obj; if (name == null) { if (other.name != null) return false;
} else if (!name.equals(other.name)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; return true; } @Override public String toString() { return "NameCountriesModel [name=" + name + ", country=" + country + "]"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameCountriesEntity.java
1
请完成以下Java代码
public static void sendMessageTo(String userId, String pageId, String message) { VxeSocket socketItem = getUserPool(userId).get(pageId); if (socketItem != null) { socketItem.sendMessage(message); } else { log.warn("【vxeSocket】消息发送失败:userId\"" + userId + "\"的pageId\"" + pageId + "\"不存在或未在线!"); } } /** * 向多个用户的所有页面发送消息 * * @param userIds 接收消息的用户ID数组 * @param message 消息内容 */ public static void sendMessageTo(String[] userIds, String message) { for (String userId : userIds) { VxeSocket.sendMessageTo(userId, message); } } /** * 向所有用户的所有页面发送消息 * * @param message 消息内容 */ public static void sendMessageToAll(String message) { for (VxeSocket socketItem : socketPool.values()) { socketItem.sendMessage(message); } } /** * websocket 开启连接 */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("pageId") String pageId) { try { this.userId = userId; this.pageId = pageId; this.socketId = userId + pageId; this.session = session; socketPool.put(this.socketId, this); getUserPool(userId).put(this.pageId, this); log.info("【vxeSocket】有新的连接,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 断开连接 */ @OnClose public void onClose() { try { socketPool.remove(this.socketId); getUserPool(this.userId).remove(this.pageId); log.info("【vxeSocket】连接断开,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 收到消息 */ @OnMessage public void onMessage(String message) { // log.info("【vxeSocket】onMessage:" + message); JSONObject json; try {
json = JSON.parseObject(message); } catch (Exception e) { log.warn("【vxeSocket】收到不合法的消息:" + message); return; } String type = json.getString(VxeSocketConst.TYPE); switch (type) { // 心跳检测 case VxeSocketConst.TYPE_HB: this.sendMessage(VxeSocket.packageMessage(type, true)); break; // 更新form数据 case VxeSocketConst.TYPE_UVT: this.handleUpdateForm(json); break; default: log.warn("【vxeSocket】收到不识别的消息类型:" + type); break; } } /** * 处理 UpdateForm 事件 */ private void handleUpdateForm(JSONObject json) { // 将事件转发给所有人 JSONObject data = json.getJSONObject(VxeSocketConst.DATA); VxeSocket.sendMessageToAll(VxeSocket.packageMessage(VxeSocketConst.TYPE_UVT, data)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\vxe\websocket\VxeSocket.java
1
请完成以下Java代码
public static void updateWorkDates(final IRfQWorkDatesAware workDatesAware) { // Calculate Complete Date (also used to verify) final Timestamp dateWorkStart = workDatesAware.getDateWorkStart(); final Timestamp dateWorkComplete = workDatesAware.getDateWorkComplete(); final int deliveryDays = workDatesAware.getDeliveryDays(); if (dateWorkStart != null && deliveryDays != 0) { setDateWorkComplete(workDatesAware); } // Calculate Delivery Days else if (dateWorkStart != null && deliveryDays == 0 && dateWorkComplete != null) { setDeliveryDays(workDatesAware); } // Calculate Start Date else if (dateWorkStart == null && deliveryDays != 0 && dateWorkComplete != null) { setDateWorkStart(workDatesAware); } } public static void updateFromDateWorkStart(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = workDatesAware.getDateWorkStart(); if(dateWorkStart == null) { return; } setDateWorkComplete(workDatesAware); } public static void updateFromDateWorkComplete(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkComplete = workDatesAware.getDateWorkComplete();
if(dateWorkComplete == null) { return; } setDeliveryDays(workDatesAware); } public static void updateFromDeliveryDays(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = workDatesAware.getDateWorkStart(); if(dateWorkStart == null) { return; } setDateWorkComplete(workDatesAware); } public static void setDateWorkStart(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = TimeUtil.addDays(workDatesAware.getDateWorkComplete(), workDatesAware.getDeliveryDays() * -1); workDatesAware.setDateWorkStart(dateWorkStart); } public static void setDeliveryDays(final IRfQWorkDatesAware workDatesAware) { final int deliveryDays = TimeUtil.getDaysBetween(workDatesAware.getDateWorkStart(), workDatesAware.getDateWorkComplete()); workDatesAware.setDeliveryDays(deliveryDays); } public static void setDateWorkComplete(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkComplete = TimeUtil.addDays(workDatesAware.getDateWorkStart(), workDatesAware.getDeliveryDays()); workDatesAware.setDateWorkComplete(dateWorkComplete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\util\RfQWorkDatesUtil.java
1
请完成以下Java代码
public void setAD_Image_ID (int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID)); } /** Get Image. @return Image or Icon */ public int getAD_Image_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Workbench. @param AD_Workbench_ID Collection of windows, reports */ public void setAD_Workbench_ID (int AD_Workbench_ID) { if (AD_Workbench_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workbench_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workbench_ID, Integer.valueOf(AD_Workbench_ID)); } /** Get Workbench. @return Collection of windows, reports */ public int getAD_Workbench_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workbench_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); } /** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workbench.java
1
请在Spring Boot框架中完成以下Java代码
public class Person { @Id @GeneratedValue private Long id; private String name; private int age; @OneToMany(mappedBy = "author") private Set<Post> posts = new HashSet<>(); public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public Set<Post> getPosts() { return posts; } public void setPosts(Set<Post> posts) { this.posts = posts; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
repos\tutorials-master\persistence-modules\blaze-persistence\src\main\java\com\baeldung\model\Person.java
2
请在Spring Boot框架中完成以下Java代码
public class FileUploadController { @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) public String displayForm() { return "fileUploadForm"; } @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { modelMap.addAttribute("file", file); return "fileUploadView"; } @RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST) public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) { modelMap.addAttribute("files", files); return "fileUploadView"; } @RequestMapping(value = "/uploadFileWithAddtionalData", method = RequestMethod.POST)
public String submit(@RequestParam final MultipartFile file, @RequestParam final String name, @RequestParam final String email, final ModelMap modelMap) { modelMap.addAttribute("name", name); modelMap.addAttribute("email", email); modelMap.addAttribute("file", file); return "fileUploadView"; } @RequestMapping(value = "/uploadFileModelAttribute", method = RequestMethod.POST) public String submit(@ModelAttribute final FormDataWithFile formDataWithFile, final ModelMap modelMap) { modelMap.addAttribute("formDataWithFile", formDataWithFile); return "fileUploadView"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\web\controller\FileUploadController.java
2
请完成以下Java代码
protected CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition) { return findTransition(processDefinition); } protected TransitionImpl findTransition(ProcessDefinitionImpl processDefinition) { PvmActivity activity = processDefinition.findActivity(activityId); EnsureUtil.ensureNotNull(NotValidException.class, describeFailure("Activity '" + activityId + "' does not exist"), "activity", activity); if (activity.getOutgoingTransitions().isEmpty()) { throw new ProcessEngineException("Cannot start after activity " + activityId + "; activity " + "has no outgoing sequence flow to take"); } else if (activity.getOutgoingTransitions().size() > 1) { throw new ProcessEngineException("Cannot start after activity " + activityId + "; " + "activity has more than one outgoing sequence flow"); } return (TransitionImpl) activity.getOutgoingTransitions().get(0); } @Override public String getTargetElementId() { return activityId;
} @Override protected String describe() { StringBuilder sb = new StringBuilder(); sb.append("Start after activity '"); sb.append(activityId); sb.append("'"); if (ancestorActivityInstanceId != null) { sb.append(" with ancestor activity instance '"); sb.append(ancestorActivityInstanceId); sb.append("'"); } return sb.toString(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivityAfterInstantiationCmd.java
1
请完成以下Java代码
public String getBody() { return super.getBody(); } @NoXss(fieldName = "web notification button text") @Length(fieldName = "web notification button text", max = 50, message = "cannot be longer than 50 chars") @JsonIgnore public String getButtonText() { return getButtonConfigProperty("text"); } @JsonIgnore public void setButtonText(String buttonText) { getButtonConfig().ifPresent(buttonConfig -> { buttonConfig.set("text", new TextNode(buttonText)); }); } @NoXss(fieldName = "web notification button link") @Length(fieldName = "web notification button link", max = 300, message = "cannot be longer than 300 chars") @JsonIgnore public String getButtonLink() { return getButtonConfigProperty("link"); } @JsonIgnore public void setButtonLink(String buttonLink) { getButtonConfig().ifPresent(buttonConfig -> { buttonConfig.set("link", new TextNode(buttonLink)); }); } private String getButtonConfigProperty(String property) { return getButtonConfig()
.map(buttonConfig -> buttonConfig.get(property)) .filter(JsonNode::isTextual) .map(JsonNode::asText).orElse(null); } private Optional<ObjectNode> getButtonConfig() { return Optional.ofNullable(additionalConfig) .map(config -> config.get("actionButtonConfig")).filter(JsonNode::isObject) .map(config -> (ObjectNode) config); } @Override public NotificationDeliveryMethod getMethod() { return NotificationDeliveryMethod.WEB; } @Override public WebDeliveryMethodNotificationTemplate copy() { return new WebDeliveryMethodNotificationTemplate(this); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\template\WebDeliveryMethodNotificationTemplate.java
1
请完成以下Java代码
private static <T extends Message> String buildTextMessage(String type, T message) { JSONObject messageObject = new JSONObject(); messageObject.put("type", type); messageObject.put("body", message); return messageObject.toString(); } /** * 真正发送消息 * * @param session Session * @param messageText 消息 */ private static void sendTextMessage(Session session, String messageText) { if (session == null) { LOGGER.error("[sendTextMessage][session 为 null]"); return;
} RemoteEndpoint.Basic basic = session.getBasicRemote(); if (basic == null) { LOGGER.error("[sendTextMessage][session 的 为 null]"); return; } try { basic.sendText(messageText); } catch (IOException e) { LOGGER.error("[sendTextMessage][session({}) 发送消息{}) 发生异常", session, messageText, e); } } }
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\util\WebSocketUtil.java
1
请完成以下Java代码
protected boolean isAbleToHandle(@Nullable Resource resource) { return resource != null; } /** * Reads data from the target {@link Resource} (intentionally) by using the {@link InputStream} returned by * {@link Resource#getInputStream()}. * * However, other algorithm/strategy implementations are free to read from the {@link Resource} as is appropriate * for the given context (e.g. cloud environment). In those cases, implementors should override * the {@link #read(Resource)} method. * * @param resourceInputStream {@link InputStream} used to read data from the target {@link Resource}. * @return a {@literal non-null} byte array containing the data from the target {@link Resource}. * @throws IOException if an I/O error occurs while reading from the {@link Resource}.
* @see java.io.InputStream * @see #read(Resource) */ protected abstract @NonNull byte[] doRead(@NonNull InputStream resourceInputStream) throws IOException; /** * Pre-processes the target {@link Resource} before reading from the {@link Resource}. * * @param resource {@link Resource} to pre-process; never {@literal null}. * @return the given, target {@link Resource}. * @see org.springframework.core.io.Resource */ protected @NonNull Resource preProcess(@NonNull Resource resource) { return resource; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\AbstractResourceReader.java
1
请完成以下Java代码
public int size() { return deque.size(); } @Override public boolean isEmpty() { return deque.isEmpty(); } @Override public boolean contains(Object o) { return deque.contains(o); } @Override public Iterator<E> iterator() { return deque.iterator(); } @Override public Object[] toArray() { return deque.toArray(); } @Override public <T> T[] toArray(T[] a) { return deque.toArray(a); } @Override public boolean add(E e) { return deque.add(e); } @Override public boolean remove(Object o) { return deque.remove(o); }
@Override public boolean containsAll(Collection<?> c) { return deque.containsAll(c); } @Override public boolean addAll(Collection<? extends E> c) { return deque.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return deque.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return deque.retainAll(c); } @Override public void clear() { deque.clear(); } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void close() { AppEngines.unregister(this); appEngineConfiguration.close(); if (appEngineConfiguration.getEngineLifecycleListeners() != null) { for (EngineLifecycleListener engineLifecycleListener : appEngineConfiguration.getEngineLifecycleListeners()) { engineLifecycleListener.onEngineClosed(this); } } } @Override public AppEngineConfiguration getAppEngineConfiguration() { return appEngineConfiguration; } public void setAppEngineConfiguration(AppEngineConfiguration appEngineConfiguration) { this.appEngineConfiguration = appEngineConfiguration; }
@Override public AppManagementService getAppManagementService() { return appManagementService; } public void setAppManagementService(AppManagementService appManagementService) { this.appManagementService = appManagementService; } @Override public AppRepositoryService getAppRepositoryService() { return appRepositoryService; } public void setAppRepositoryService(AppRepositoryService appRepositoryService) { this.appRepositoryService = appRepositoryService; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AppEngineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public AllocationAmounts withInvoiceProcessingFee(@NonNull final Money invoiceProcessingFee) { return Objects.equals(this.invoiceProcessingFee, invoiceProcessingFee) ? this : toBuilder().invoiceProcessingFee(invoiceProcessingFee).build(); } public AllocationAmounts movePayAmtToDiscount() { if (payAmt.signum() == 0) { return this; } else { return toBuilder() .payAmt(payAmt.toZero()) .discountAmt(discountAmt.add(payAmt)) .build(); } } public AllocationAmounts movePayAmtToWriteOff() { if (payAmt.signum() == 0) { return this; } else { return toBuilder() .payAmt(payAmt.toZero()) .writeOffAmt(writeOffAmt.add(payAmt)) .build(); } } public AllocationAmounts add(@NonNull final AllocationAmounts other) { return toBuilder() .payAmt(this.payAmt.add(other.payAmt)) .discountAmt(this.discountAmt.add(other.discountAmt)) .writeOffAmt(this.writeOffAmt.add(other.writeOffAmt)) .invoiceProcessingFee(this.invoiceProcessingFee.add(other.invoiceProcessingFee)) .build(); } public AllocationAmounts subtract(@NonNull final AllocationAmounts other) { return toBuilder() .payAmt(this.payAmt.subtract(other.payAmt)) .discountAmt(this.discountAmt.subtract(other.discountAmt)) .writeOffAmt(this.writeOffAmt.subtract(other.writeOffAmt)) .invoiceProcessingFee(this.invoiceProcessingFee.subtract(other.invoiceProcessingFee))
.build(); } public AllocationAmounts convertToRealAmounts(@NonNull final InvoiceAmtMultiplier invoiceAmtMultiplier) { return negateIf(invoiceAmtMultiplier.isNegateToConvertToRealValue()); } private AllocationAmounts negateIf(final boolean condition) { return condition ? negate() : this; } public AllocationAmounts negate() { if (isZero()) { return this; } return toBuilder() .payAmt(this.payAmt.negate()) .discountAmt(this.discountAmt.negate()) .writeOffAmt(this.writeOffAmt.negate()) .invoiceProcessingFee(this.invoiceProcessingFee) // never negate the processing fee because it will be paid to the service provider no matter what kind of invoice it is applied to. .build(); } public Money getTotalAmt() { return payAmt.add(discountAmt).add(writeOffAmt).add(invoiceProcessingFee); } public boolean isZero() { return payAmt.signum() == 0 && discountAmt.signum() == 0 && writeOffAmt.signum() == 0 && invoiceProcessingFee.signum() == 0; } public AllocationAmounts toZero() { return isZero() ? this : AllocationAmounts.zero(getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationAmounts.java
2
请完成以下Java代码
private IViewRowType getType() { return type; } public Builder setType(final IViewRowType type) { this.type = type; return this; } public Builder setProcessed(final boolean processed) { this.processed = processed; return this; } private boolean isProcessed() { if (processed == null) { // NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example. // return DisplayType.toBoolean(values.getOrDefault("Processed", false)); return false; } else { return processed.booleanValue(); } } public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue) { if (jsonValue == null || JSONNullValue.isNull(jsonValue)) { values.remove(fieldName); } else { values.put(fieldName, jsonValue); }
return this; } private Map<String, Object> getValues() { return values; } public LookupValue getFieldValueAsLookupValue(final String fieldName) { return LookupValue.cast(values.get(fieldName)); } public Builder addIncludedRow(final IViewRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow); return this; } private List<IViewRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
1
请完成以下Java代码
public class AmountAndDirection35 { @XmlElement(name = "Amt", required = true) protected BigDecimal amt; @XmlElement(name = "CdtDbtInd", required = true) @XmlSchemaType(name = "string") protected CreditDebitCode cdtDbtInd; /** * Gets the value of the amt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmt(BigDecimal value) { this.amt = value; }
/** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = 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\AmountAndDirection35.java
1
请完成以下Java代码
public class MAccessLog extends X_AD_AccessLog { /** * */ private static final long serialVersionUID = -7169782622717772940L; /** * Standard Constructor * @param ctx context * @param AD_AccessLog_ID id * @param trxName transaction */ public MAccessLog (Properties ctx, int AD_AccessLog_ID, String trxName) { super (ctx, AD_AccessLog_ID, trxName); } // MAccessLog /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MAccessLog (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MAccessLog /** * New Constructor * @param ctx context * @param Remote_Host host * @param Remote_Addr address * @param TextMsg text message * @param trxName transaction */ public MAccessLog (Properties ctx, String Remote_Host, String Remote_Addr, String TextMsg, String trxName) { this (ctx, 0, trxName); setRemote_Addr(Remote_Addr); setRemote_Host(Remote_Host);
setTextMsg(TextMsg); } // MAccessLog /** * New Constructor * @param ctx context * @param AD_Table_ID table * @param AD_Column_ID column * @param Record_ID record * @param trxName transaction */ public MAccessLog (Properties ctx, int AD_Table_ID, int AD_Column_ID, int Record_ID, String trxName) { this (ctx, 0, trxName); setAD_Table_ID(AD_Table_ID); setAD_Column_ID(AD_Column_ID); setRecord_ID(Record_ID); } // MAccessLog } // MAccessLog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAccessLog.java
1
请在Spring Boot框架中完成以下Java代码
public String getLogoURL() { return logoURL; } /** * Sets the value of the logoURL property. * * @param value * allowed object is * {@link String } * */ public void setLogoURL(String value) { this.logoURL = value; } /** * A certain layout id. * * @return * possible object is * {@link String } * */ public String getLayoutID() { return layoutID; } /** * Sets the value of the layoutID property. * * @param value * allowed object is * {@link String } * */ public void setLayoutID(String value) { this.layoutID = value; } /** * Indicates whether an amount of 0 shall be shown or not. * * @return * possible object is * {@link Boolean } * */
public Boolean isSuppressZero() { return suppressZero; } /** * Sets the value of the suppressZero property. * * @param value * allowed object is * {@link Boolean } * */ public void setSuppressZero(Boolean value) { this.suppressZero = value; } /** * Gets the value of the presentationDetailsExtension property. * * @return * possible object is * {@link PresentationDetailsExtensionType } * */ public PresentationDetailsExtensionType getPresentationDetailsExtension() { return presentationDetailsExtension; } /** * Sets the value of the presentationDetailsExtension property. * * @param value * allowed object is * {@link PresentationDetailsExtensionType } * */ public void setPresentationDetailsExtension(PresentationDetailsExtensionType value) { this.presentationDetailsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PresentationDetailsType.java
2
请完成以下Java代码
private void actionPerformed0(final ActionEvent e) { if (m_updating) return; final Object src = e.getSource(); if (src == bOK) { updateCConnection(); // Make sure the database connection is OK. // Else, there is no point to continue because it will fail a bit later. if (!m_cc.isDatabaseOK()) { cmd_testDB(); updateInfo(); // update the UI fields from "m_cc" } if (!m_cc.isDatabaseOK()) { // NOTE: we assume an error popup was already displayed to user. return; } m_ccResult = m_cc; dispose(); isCancel = false; return; } else if (src == bCancel) { dispose(); return; } updateCConnection(); if (src == bTestDB) { cmd_testDB(); } updateInfo(); } // actionPerformed private void updateCConnection() { m_cc.setDbHost(hostField.getText()); m_cc.setDbPort(dbPortField.getText()); m_cc.setDbName(sidField.getText()); m_cc.setDbUid(dbUidField.getText()); m_cc.setDbPwd(String.valueOf(dbPwdField.getPassword())); } /** * Update Fields from Connection */ private void updateInfo() { m_updating = true; try { final boolean dbSettingsWritable; dbSettingsWritable = true; hostLabel.setReadWrite(dbSettingsWritable); hostField.setReadWrite(dbSettingsWritable); hostField.setText(m_cc.getDbHost()); portLabel.setReadWrite(dbSettingsWritable); dbPortField.setReadWrite(dbSettingsWritable); dbPortField.setText(String.valueOf(m_cc.getDbPort())); sidLabel.setReadWrite(dbSettingsWritable); sidField.setReadWrite(dbSettingsWritable); sidField.setText(m_cc.getDbName());
// dbUidLabel.setReadWrite(dbSettingsWritable); dbUidField.setReadWrite(dbSettingsWritable); dbUidField.setText(m_cc.getDbUid()); dbPwdField.setEditable(dbSettingsWritable); dbPwdField.setText(m_cc.getDbPwd()); // bTestDB.setToolTipText(m_cc.getConnectionURL()); bTestDB.setIcon(getStatusIcon(m_cc.isDatabaseOK())); } finally { m_updating = false; } } // updateInfo /** * Get Status Icon - ok or not */ private Icon getStatusIcon(boolean ok) { if (ok) return bOK.getIcon(); else return bCancel.getIcon(); } // getStatusIcon private void showError(final String title, final Object messageObj) { JOptionPane.showMessageDialog(this, messageObj, // message title, JOptionPane.ERROR_MESSAGE); } /** * Test Database connection. * * If the database connection is not OK, an error popup will be displayed to user. */ private void cmd_testDB() { setBusy(true); try { m_cc.testDatabase(); } catch (Exception e) { log.error(e.getMessage(), e); showError(res.getString("ConnectionError") + ": " + m_cc.getConnectionURL(), e); } finally { setBusy(false); } } // cmd_testDB public boolean isCancel() { return isCancel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionDialog.java
1
请完成以下Java代码
public final class CustomerEntity extends BaseVersionedEntity<Customer> { @Column(name = ModelConstants.CUSTOMER_TENANT_ID_PROPERTY) private UUID tenantId; @Column(name = ModelConstants.CUSTOMER_TITLE_PROPERTY) private String title; @Column(name = ModelConstants.COUNTRY_PROPERTY) private String country; @Column(name = ModelConstants.STATE_PROPERTY) private String state; @Column(name = ModelConstants.CITY_PROPERTY) private String city; @Column(name = ModelConstants.ADDRESS_PROPERTY) private String address; @Column(name = ModelConstants.ADDRESS2_PROPERTY) private String address2; @Column(name = ModelConstants.ZIP_PROPERTY) private String zip; @Column(name = ModelConstants.PHONE_PROPERTY) private String phone; @Column(name = ModelConstants.EMAIL_PROPERTY) private String email; @Column(name = ModelConstants.CUSTOMER_IS_PUBLIC_PROPERTY) private boolean isPublic; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.CUSTOMER_ADDITIONAL_INFO_PROPERTY) private JsonNode additionalInfo; @Column(name = ModelConstants.EXTERNAL_ID_PROPERTY) private UUID externalId; public CustomerEntity() { super(); } public CustomerEntity(Customer customer) { super(customer); this.tenantId = customer.getTenantId().getId(); this.title = customer.getTitle(); this.country = customer.getCountry(); this.state = customer.getState(); this.city = customer.getCity(); this.address = customer.getAddress(); this.address2 = customer.getAddress2(); this.zip = customer.getZip(); this.phone = customer.getPhone(); this.email = customer.getEmail(); this.additionalInfo = customer.getAdditionalInfo();
this.isPublic = customer.isPublic(); if (customer.getExternalId() != null) { this.externalId = customer.getExternalId().getId(); } } @Override public Customer toData() { Customer customer = new Customer(new CustomerId(this.getUuid())); customer.setCreatedTime(createdTime); customer.setVersion(version); customer.setTenantId(TenantId.fromUUID(tenantId)); customer.setTitle(title); customer.setCountry(country); customer.setState(state); customer.setCity(city); customer.setAddress(address); customer.setAddress2(address2); customer.setZip(zip); customer.setPhone(phone); customer.setEmail(email); customer.setAdditionalInfo(additionalInfo); if (externalId != null) { customer.setExternalId(new CustomerId(externalId)); } return customer; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\CustomerEntity.java
1
请完成以下Java代码
public class InstructionForCreditorAgent1 { @XmlElement(name = "Cd") @XmlSchemaType(name = "string") protected Instruction3Code cd; @XmlElement(name = "InstrInf") protected String instrInf; /** * Gets the value of the cd property. * * @return * possible object is * {@link Instruction3Code } * */ public Instruction3Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link Instruction3Code } * */ public void setCd(Instruction3Code value) { this.cd = value; } /** * Gets the value of the instrInf property. * * @return * possible object is * {@link String }
* */ public String getInstrInf() { return instrInf; } /** * Sets the value of the instrInf property. * * @param value * allowed object is * {@link String } * */ public void setInstrInf(String value) { this.instrInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\InstructionForCreditorAgent1.java
1
请在Spring Boot框架中完成以下Java代码
public class DunningDocDocumentLocationAdapterFactory implements DocumentLocationAdapterFactory { public static DunningDocDocumentLocationAdapter locationAdapter(@NonNull final I_C_DunningDoc delegate) { return new DunningDocDocumentLocationAdapter(delegate); } @Override public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record) { return toDunningDoc(record).map(DunningDocDocumentLocationAdapterFactory::locationAdapter); } @Override public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { return Optional.empty(); } @Override
public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { return Optional.empty(); } @Override public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { return Optional.empty(); } private static Optional<I_C_DunningDoc> toDunningDoc(final Object record) { return InterfaceWrapperHelper.isInstanceOf(record, I_C_DunningDoc.class) ? Optional.of(InterfaceWrapperHelper.create(record, I_C_DunningDoc.class)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDocDocumentLocationAdapterFactory.java
2
请完成以下Java代码
public class X_AD_WF_Block extends org.compiere.model.PO implements I_AD_WF_Block, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1036331149L; /** Standard Constructor */ public X_AD_WF_Block (final Properties ctx, final int AD_WF_Block_ID, @Nullable final String trxName) { super (ctx, AD_WF_Block_ID, trxName); } /** Load Constructor */ public X_AD_WF_Block (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_WF_Block_ID (final int AD_WF_Block_ID) { if (AD_WF_Block_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Block_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Block_ID, AD_WF_Block_ID); } @Override public int getAD_WF_Block_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Block_ID); } @Override public void setAD_Workflow_ID (final int AD_Workflow_ID) {
if (AD_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); } @Override public int getAD_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Block.java
1
请完成以下Java代码
public Object getOrgValue() { return orgValue; } public void setOrgValue(Object orgValue) { this.orgValue = orgValue; } public Object getNewValue() { return newValue; } public void setNewValue(Object newValue) { this.newValue = newValue; } public String getNewValueString() { return valueAsString(newValue); } public String getOrgValueString() { return valueAsString(orgValue);
} protected String valueAsString(Object value) { if(value == null) { return null; } else if(value instanceof Date){ return String.valueOf(((Date)value).getTime()); } else { return value.toString(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\PropertyChange.java
1
请完成以下Java代码
private static String getMandatoryProperty(final String name, final String defaultValue) { final String systemPropertyValue = System.getProperty(name); if (isNotBlank(systemPropertyValue)) { return systemPropertyValue; } final String envVarValue = System.getenv(name); if (isNotBlank(envVarValue)) { return envVarValue; } final String envVarValueWithUnderscore = System.getenv(name.replace('.', '_')); if (isNotBlank(envVarValueWithUnderscore)) { return envVarValueWithUnderscore; } if (isNotBlank(defaultValue)) { logger.info("Considering default config: {}={}. To override it start JVM with '-D{}=...' OR set environment-variable '{}=...'.", name, defaultValue, name, name); return defaultValue; } throw new RuntimeException("Property '" + name + "' was not set. " + "\n Please start JVM with '-D" + name + "=...'" + " OR set environment-variable '" + name + "=...'."); } private static boolean getBooleanProperty(final String name, final boolean defaultValue) { final String systemPropertyValue = System.getProperty(name); if (isNotBlank(systemPropertyValue))
{ return Boolean.parseBoolean(systemPropertyValue.trim()); } final String evnVarValue = System.getenv(name); if (isNotBlank(evnVarValue)) { return Boolean.parseBoolean(evnVarValue); } final String envVarValueWithUnderscore = System.getenv(name.replace('.', '_')); if (isNotBlank(envVarValueWithUnderscore)) { return Boolean.parseBoolean(envVarValueWithUnderscore); } logger.info("Considering default config: {}={}. To override it start JVM with '-D{}=...' OR set environment-variable '{}=...'.", name, defaultValue, name, name); return defaultValue; } private static boolean isNotBlank(@Nullable final String str) { return str != null && !str.trim().isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\Main.java
1
请在Spring Boot框架中完成以下Java代码
public String findSimpleHelloWorld() { String cacheKey = "simple-hello"; return simpleHelloWorldCache.computeIfAbsent(cacheKey, k -> repository.getHelloWorld()); } public String findExpiringHelloWorld() { String cacheKey = "expiring-hello"; String helloWorld = simpleHelloWorldCache.get(cacheKey); if (helloWorld == null) { helloWorld = repository.getHelloWorld(); simpleHelloWorldCache.put(cacheKey, helloWorld, 1, TimeUnit.SECONDS); } return helloWorld; } public String findIdleHelloWorld() { String cacheKey = "idle-hello"; String helloWorld = simpleHelloWorldCache.get(cacheKey); if (helloWorld == null) { helloWorld = repository.getHelloWorld(); simpleHelloWorldCache.put(cacheKey, helloWorld, -1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS); } return helloWorld; } public String findSimpleHelloWorldInExpiringCache() { String cacheKey = "simple-hello"; String helloWorld = expiringHelloWorldCache.get(cacheKey); if (helloWorld == null) { helloWorld = repository.getHelloWorld(); expiringHelloWorldCache.put(cacheKey, helloWorld); } return helloWorld;
} public String findEvictingHelloWorld(String key) { String value = evictingHelloWorldCache.get(key); if (value == null) { value = repository.getHelloWorld(); evictingHelloWorldCache.put(key, value); } return value; } public String findPassivatingHelloWorld(String key) { return passivatingHelloWorldCache.computeIfAbsent(key, k -> repository.getHelloWorld()); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\infinispan\service\HelloWorldService.java
2
请完成以下Java代码
public JsonSerde<T> noTypeInfo() { this.jsonSerializer.noTypeInfo(); return this; } /** * Don't remove type information headers after deserialization. * @return the serde. * @since 2.3 */ public JsonSerde<T> dontRemoveTypeHeaders() { this.jsonDeserializer.dontRemoveTypeHeaders(); return this; } /** * Ignore type information headers and use the configured target class. * @return the serde. * @since 2.3 */ public JsonSerde<T> ignoreTypeHeaders() { this.jsonDeserializer.ignoreTypeHeaders();
return this; } /** * Use the supplied {@link org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper}. * @param mapper the mapper. * @return the serde. * @since 2.3 */ public JsonSerde<T> typeMapper(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper mapper) { this.jsonSerializer.setTypeMapper(mapper); this.jsonDeserializer.setTypeMapper(mapper); return this; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JsonSerde.java
1
请完成以下Java代码
public void purgeBuffer() { synchronized (lock) { buffer.clear(); } } public void shutdown() { executor.shutdown(); } /* public static void main(String[] args) throws InterruptedException { final Debouncer<Integer> debouncer = Debouncer.<Integer>builder() .name("test-debouncer") .delayInMillis(500) .bufferMaxSize(500) .consumer(items -> System.out.println("Got " + items.size() + " items: " + items.get(0) + "..." + items.get(items.size() - 1))) .build();
System.out.println("Start sending events..."); for (int i = 1; i <= 100; i++) { debouncer.add(i); //Thread.yield(); Thread.sleep(0, 1); } System.out.println("Enqueuing done. Waiting a bit to finish..."); Thread.sleep(5000); } */ }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\async\Debouncer.java
1
请完成以下Java代码
public class X_C_Print_Job_Detail extends org.compiere.model.PO implements I_C_Print_Job_Detail, org.compiere.model.I_Persistent { private static final long serialVersionUID = -328508281L; /** Standard Constructor */ public X_C_Print_Job_Detail (Properties ctx, int C_Print_Job_Detail_ID, String trxName) { super (ctx, C_Print_Job_Detail_ID, trxName); } /** Load Constructor */ public X_C_Print_Job_Detail (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_PrinterRouting_ID (int AD_PrinterRouting_ID) { if (AD_PrinterRouting_ID < 1) set_Value (COLUMNNAME_AD_PrinterRouting_ID, null); else set_Value (COLUMNNAME_AD_PrinterRouting_ID, Integer.valueOf(AD_PrinterRouting_ID)); } @Override public int getAD_PrinterRouting_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterRouting_ID); } @Override public void setC_Print_Job_Detail_ID (int C_Print_Job_Detail_ID) { if (C_Print_Job_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, Integer.valueOf(C_Print_Job_Detail_ID)); } @Override
public int getC_Print_Job_Detail_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Detail_ID); } @Override public de.metas.printing.model.I_C_Print_Job_Line getC_Print_Job_Line() { return get_ValueAsPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class); } @Override public void setC_Print_Job_Line(de.metas.printing.model.I_C_Print_Job_Line C_Print_Job_Line) { set_ValueFromPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class, C_Print_Job_Line); } @Override public void setC_Print_Job_Line_ID (int C_Print_Job_Line_ID) { if (C_Print_Job_Line_ID < 1) set_Value (COLUMNNAME_C_Print_Job_Line_ID, null); else set_Value (COLUMNNAME_C_Print_Job_Line_ID, Integer.valueOf(C_Print_Job_Line_ID)); } @Override public int getC_Print_Job_Line_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Line_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Detail.java
1
请完成以下Java代码
public class DoubleNonValue { public static double findLargestThrowException(double[] array) { if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty"); } double max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } public static double findLargestIgnoreNonValues(double[] array) { double max = Double.NEGATIVE_INFINITY; boolean foundValidValue = false; for (double value : array) { if (!Double.isNaN(value) && !Double.isInfinite(value)) { if (!foundValidValue || value > max) { max = value; foundValidValue = true; } } } return foundValidValue ? max : -1.0; } public static double findLargestReturnNegativeOne(double[] array) { if (array.length == 0) { return -1.0; } double max = Double.NEGATIVE_INFINITY; boolean foundValidValue = false; for (double value : array) { if (!Double.isNaN(value) && !Double.isInfinite(value)) { if (!foundValidValue || value > max) { max = value; foundValidValue = true; } } } return foundValidValue ? max : -1.0; } public static Double findLargestWithWrapper(double[] array) {
Double max = null; for (double value : array) { if (!Double.isNaN(value) && !Double.isInfinite(value)) { if (max == null || value > max) { max = value; } } } return max; } public static double findLargestReturnNaN(double[] array) { double max = Double.NEGATIVE_INFINITY; boolean foundValidValue = false; for (double value : array) { if (!Double.isNaN(value) && !Double.isInfinite(value)) { if (!foundValidValue || value > max) { max = value; foundValidValue = true; } } } return foundValidValue ? max : Double.NaN; } }
repos\tutorials-master\core-java-modules\core-java-numbers-10\src\main\java\com\baeldung\doublenonvalues\DoubleNonValue.java
1
请完成以下Java代码
public String variablesCss() { return "variables.css"; } @GetMapping(path = "/login", produces = MediaType.TEXT_HTML_VALUE) public String login() { return "login"; } @lombok.Data @lombok.Builder public static class Settings { private final String title; private final String brand; private final String loginIcon; private final String favicon; private final String faviconDanger; private final PollTimer pollTimer; private final UiTheme theme; private final boolean notificationFilterEnabled; private final boolean rememberMeEnabled; private final List<String> availableLanguages; private final List<String> routes; private final List<ExternalView> externalViews; private final List<ViewSettings> viewSettings; private final Boolean enableToasts; private final Boolean hideInstanceUrl; private final Boolean disableInstanceUrl; } @lombok.Data @JsonInclude(Include.NON_EMPTY) public static class ExternalView { /** * Label to be shown in the navbar. */ private final String label; /** * Url for the external view to be linked */ private final String url; /** * Order in the navbar. */ private final Integer order; /** * Should the page shown as an iframe or open in a new window. */ private final boolean iframe;
/** * A list of child views. */ private final List<ExternalView> children; public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) { Assert.hasText(label, "'label' must not be empty"); if (isEmpty(children)) { Assert.hasText(url, "'url' must not be empty"); } this.label = label; this.url = url; this.order = order; this.iframe = iframe; this.children = children; } } @lombok.Data @JsonInclude(Include.NON_EMPTY) public static class ViewSettings { /** * Name of the view to address. */ private final String name; /** * Set view enabled. */ private boolean enabled; public ViewSettings(String name, boolean enabled) { Assert.hasText(name, "'name' must not be empty"); this.name = name; this.enabled = enabled; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java
1
请完成以下Java代码
public void incrementCountRetries() { this.countRetries++; } public int getRetriesLeft() { return Math.max(0, totalRetries - countRetries); } protected class FailedJobListenerCmd implements Command<Void> { protected String jobId; protected Command<Object> cmd; public FailedJobListenerCmd(String jobId, Command<Object> cmd) { this.jobId = jobId; this.cmd = cmd; } @Override public Void execute(CommandContext commandContext) {
JobEntity job = commandContext .getJobManager() .findJobById(jobId); if (job != null) { job.setFailedActivityId(jobFailureCollector.getFailedActivityId()); fireHistoricJobFailedEvt(job); cmd.execute(commandContext); } else { LOG.debugFailedJobNotFound(jobId); } return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\FailedJobListener.java
1
请完成以下Java代码
public KeyStroke getKeyStroke() { return getActionType().getKeyStroke(); } @Override public boolean isAvailable() { return !NullCopyPasteSupportEditor.isNull(getCopyPasteSupport()); } @Override public boolean isRunnable() { return getCopyPasteSupport().isCopyPasteActionAllowed(getActionType());
} @Override public boolean isHideWhenNotRunnable() { return false; // just gray it out } @Override public void run() { getCopyPasteSupport().executeCopyPasteAction(getActionType()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CopyPasteContextMenuAction.java
1
请在Spring Boot框架中完成以下Java代码
public String getMEASUREUNIT() { return measureunit; } /** * Sets the value of the measureunit property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREUNIT(String value) { this.measureunit = value; } /** * Gets the value of the measurevalue property. * * @return * possible object is * {@link String } * */ public String getMEASUREVALUE() { return measurevalue; } /** * Sets the value of the measurevalue property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREVALUE(String value) { this.measurevalue = value; } /** * Gets the value of the ppack1 property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ppack1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPPACK1().add(newItem); * </pre>
* * * <p> * Objects of the following type(s) are allowed in the list * {@link PPACK1 } * * */ public List<PPACK1> getPPACK1() { if (ppack1 == null) { ppack1 = new ArrayList<PPACK1>(); } return this.ppack1; } /** * Gets the value of the detail property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the detail property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDETAIL().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DETAILXlief } * * */ public List<DETAILXlief> getDETAIL() { if (detail == null) { detail = new ArrayList<DETAILXlief>(); } return this.detail; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PACKINXlief.java
2
请完成以下Java代码
public int hashCode() { return new HashcodeBuilder() .append(C_City_ID) .append(C_Region_ID) .append(CityName) .append(RegionName) .toHashcode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final CityVO other = EqualsBuilder.getOther(this, obj); if (other == null) return false; return new EqualsBuilder() .append(C_City_ID, other.C_City_ID) .append(C_Region_ID, other.C_Region_ID) .append(CityName, other.CityName) .append(RegionName, other.RegionName) .isEqual(); } @Override public String getText() { return CityName; } @Override public String toString() { // needed for ListCellRenderer final StringBuilder sb = new StringBuilder(); if (this.CityName != null) { sb.append(this.CityName); }
if (this.RegionName != null) { sb.append(" (").append(this.RegionName).append(")"); } return sb.toString(); } public int getC_City_ID() { return C_City_ID; } public String getCityName() { return CityName; } public int getC_Region_ID() { return C_Region_ID; } public String getRegionName() { return RegionName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CityVO.java
1
请在Spring Boot框架中完成以下Java代码
public class ThreadPoolTaskSchedulerExamples { @Autowired private ThreadPoolTaskScheduler taskScheduler; @Autowired private CronTrigger cronTrigger; @Autowired private PeriodicTrigger periodicTrigger; @PostConstruct public void scheduleRunnableWithCronTrigger() { taskScheduler.schedule(new RunnableTask("Current Date"), new Date()); taskScheduler.scheduleWithFixedDelay(new RunnableTask("Fixed 1 second Delay"), 1000); taskScheduler.scheduleWithFixedDelay(new RunnableTask("Current Date Fixed 1 second Delay"), new Date(), 1000); taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), new Date(), 2000); taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), 2000); taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);
taskScheduler.schedule(new RunnableTask("Periodic Trigger"), periodicTrigger); } class RunnableTask implements Runnable { private String message; public RunnableTask(String message) { this.message = message; } @Override public void run() { } } }
repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\taskscheduler\ThreadPoolTaskSchedulerExamples.java
2
请完成以下Java代码
public void onGLJournalLineCompleted(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementLineId -> bankStatementBL.markAsReconciledWithGLJournalLine(bankStatementLineId, line.getIdNotNull())); } } @Override public void onGLJournalLineReactivated(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null)
{ // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementBL::unreconcile); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\open_items_handler\BankStatementOIHandler.java
1
请完成以下Java代码
public boolean isEmpty() {return header.isEmpty() || rowsList.isEmpty();} public void addRow(@NonNull final Row row) { rowsList.add(row); } public void addRows(@NonNull final Collection<Row> rows) { rowsList.addAll(rows); } public void addRows(@NonNull final Table other) { rowsList.addAll(other.rowsList); } public void removeColumnsWithBlankValues() { header.removeIf(this::isBlankColumn); } private boolean isBlankColumn(final String columnName) { return rowsList.stream().allMatch(row -> row.isBlankColumn(columnName)); } public void moveColumnsToStart(final String... columnNamesToMove) { if (columnNamesToMove == null || columnNamesToMove.length == 0) { return; } for (int i = columnNamesToMove.length - 1; i >= 0; i--) { if (columnNamesToMove[i] == null) { continue; } final String columnNameToMove = columnNamesToMove[i]; if (header.remove(columnNameToMove)) { header.add(0, columnNameToMove); } } } public void moveColumnsToEnd(final String... columnNamesToMove) { if (columnNamesToMove == null) { return; } for (final String columnNameToMove : columnNamesToMove) { if (columnNameToMove == null) { continue; } if (header.remove(columnNameToMove)) { header.add(columnNameToMove); } }
} public Optional<Table> removeColumnsWithSameValue() { if (rowsList.isEmpty()) { return Optional.empty(); } final Table removedTable = new Table(); for (final String columnName : new ArrayList<>(header)) { final Cell commonValue = getCommonValue(columnName).orElse(null); if (commonValue != null) { header.remove(columnName); removedTable.addHeader(columnName); removedTable.setCell(0, columnName, commonValue); } } if (removedTable.isEmpty()) { return Optional.empty(); } return Optional.of(removedTable); } private Optional<Cell> getCommonValue(@NonNull final String columnName) { if (rowsList.isEmpty()) { return Optional.empty(); } final Cell firstValue = rowsList.get(0).getCell(columnName); for (int i = 1; i < rowsList.size(); i++) { final Cell value = rowsList.get(i).getCell(columnName); if (!Objects.equals(value, firstValue)) { return Optional.empty(); } } return Optional.of(firstValue); } public TablePrinter toPrint() { return new TablePrinter(this); } public String toTabularString() { return toPrint().toString(); } @Override @Deprecated public String toString() {return toTabularString();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Table.java
1
请完成以下Java代码
public ListenableFuture<AlarmComment> findAlarmCommentByIdAsync(TenantId tenantId, AlarmCommentId alarmCommentId) { log.trace("Executing findAlarmCommentByIdAsync by alarmCommentId [{}]", alarmCommentId); validateId(alarmCommentId, id -> "Incorrect alarmCommentId " + id); return alarmCommentDao.findAlarmCommentByIdAsync(tenantId, alarmCommentId.getId()); } @Override public AlarmComment findAlarmCommentById(TenantId tenantId, AlarmCommentId alarmCommentId) { log.trace("Executing findAlarmCommentByIdAsync by alarmCommentId [{}]", alarmCommentId); validateId(alarmCommentId, id -> "Incorrect alarmCommentId " + id); return alarmCommentDao.findById(tenantId, alarmCommentId.getId()); } private AlarmComment createAlarmComment(TenantId tenantId, AlarmComment alarmComment) { log.debug("New Alarm comment : {}", alarmComment); if (alarmComment.getType() == null) { alarmComment.setType(AlarmCommentType.OTHER); } return alarmCommentDao.save(tenantId, alarmComment); }
private AlarmComment updateAlarmComment(TenantId tenantId, AlarmComment newAlarmComment) { log.debug("Update Alarm comment : {}", newAlarmComment); AlarmComment existing = alarmCommentDao.findAlarmCommentById(tenantId, newAlarmComment.getId().getId()); if (existing != null) { if (newAlarmComment.getComment() != null) { JsonNode comment = newAlarmComment.getComment(); ((ObjectNode) comment).put("edited", "true"); ((ObjectNode) comment).put("editedOn", System.currentTimeMillis()); existing.setComment(comment); } return alarmCommentDao.save(tenantId, existing); } return null; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\alarm\BaseAlarmCommentService.java
1
请完成以下Java代码
public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } @Override public Long getLongValue() { return longValue; } @Override public void setLongValue(Long longValue) { this.longValue = longValue; } @Override public Double getDoubleValue() { return doubleValue; } @Override public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } @Override public String getTextValue() { return textValue; } @Override public void setTextValue(String textValue) { this.textValue = textValue; } @Override public String getTextValue2() { return textValue2; } @Override public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } @Override public Object getCachedValue() { return cachedValue; } @Override public void setCachedValue(Object cachedValue) { this.cachedValue = cachedValue; } // misc methods ///////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("VariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(type != null ? type.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
} sb.append("]"); return sb.toString(); } // non-supported (v6) @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } @Override public void setScopeId(String scopeId) { } @Override public void setSubScopeId(String subScopeId) { } @Override public void setScopeType(String scopeType) { } @Override public void setScopeDefinitionId(String scopeDefinitionId) { } @Override public String getScopeDefinitionId() { return null; } @Override public void setMetaInfo(String metaInfo) { } @Override public String getMetaInfo() { return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableInstanceEntity.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID) { if (M_DiscountSchema_Calculated_Surcharge_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID); } @Override public int getM_DiscountSchema_Calculated_Surcharge_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID);
} @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSurcharge_Calc_SQL (final java.lang.String Surcharge_Calc_SQL) { set_Value (COLUMNNAME_Surcharge_Calc_SQL, Surcharge_Calc_SQL); } @Override public java.lang.String getSurcharge_Calc_SQL() { return get_ValueAsString(COLUMNNAME_Surcharge_Calc_SQL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge.java
1
请完成以下Java代码
public boolean isFirstPage() { return pageNo <= 1; } public boolean isLastPage() { return pageNo >= getTotalPage(); } public int getNextPage() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } public int getPrePage() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } protected int totalCount = 0; protected int pageSize = 20; protected int pageNo = 1; public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public void setPageSize(int pageSize) { this.pageSize = pageSize; }
public void setPageNo(int pageNo) { this.pageNo = pageNo; } protected int filterNo; public int getFilterNo() { return filterNo; } public void setFilterNo(int filterNo) { this.filterNo = filterNo; } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\page\SimplePage.java
1
请在Spring Boot框架中完成以下Java代码
public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } @Override public String toString() {
return "ProductEntity{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请完成以下Java代码
public boolean isStoreAttachmentsOnFileSystem () { Object oo = get_Value(COLUMNNAME_StoreAttachmentsOnFileSystem); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Unix Archive Path. @param UnixArchivePath Unix Archive Path */ @Override public void setUnixArchivePath (java.lang.String UnixArchivePath) { set_Value (COLUMNNAME_UnixArchivePath, UnixArchivePath); } /** Get Unix Archive Path. @return Unix Archive Path */ @Override public java.lang.String getUnixArchivePath () { return (java.lang.String)get_Value(COLUMNNAME_UnixArchivePath); } /** Set Unix Attachment Path. @param UnixAttachmentPath Unix Attachment Path */ @Override public void setUnixAttachmentPath (java.lang.String UnixAttachmentPath) { set_Value (COLUMNNAME_UnixAttachmentPath, UnixAttachmentPath); } /** Get Unix Attachment Path. @return Unix Attachment Path */ @Override public java.lang.String getUnixAttachmentPath () { return (java.lang.String)get_Value(COLUMNNAME_UnixAttachmentPath); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value);
} /** Set Windows Archive Path. @param WindowsArchivePath Windows Archive Path */ @Override public void setWindowsArchivePath (java.lang.String WindowsArchivePath) { set_Value (COLUMNNAME_WindowsArchivePath, WindowsArchivePath); } /** Get Windows Archive Path. @return Windows Archive Path */ @Override public java.lang.String getWindowsArchivePath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsArchivePath); } /** Set Windows Attachment Path. @param WindowsAttachmentPath Windows Attachment Path */ @Override public void setWindowsAttachmentPath (java.lang.String WindowsAttachmentPath) { set_Value (COLUMNNAME_WindowsAttachmentPath, WindowsAttachmentPath); } /** Get Windows Attachment Path. @return Windows Attachment Path */ @Override public java.lang.String getWindowsAttachmentPath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsAttachmentPath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Client.java
1
请完成以下Java代码
default Instant getIssuedAt() { return this.getClaimAsInstant(IdTokenClaimNames.IAT); } /** * Returns the time when the End-User authentication occurred {@code (auth_time)}. * @return the time when the End-User authentication occurred */ default Instant getAuthenticatedAt() { return this.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME); } /** * Returns a {@code String} value {@code (nonce)} used to associate a Client session * with an ID Token, and to mitigate replay attacks. * @return the nonce used to associate a Client session with an ID Token */ default String getNonce() { return this.getClaimAsString(IdTokenClaimNames.NONCE); } /** * Returns the Authentication Context Class Reference {@code (acr)}. * @return the Authentication Context Class Reference */ default String getAuthenticationContextClass() { return this.getClaimAsString(IdTokenClaimNames.ACR); } /** * Returns the Authentication Methods References {@code (amr)}. * @return the Authentication Methods References */ default List<String> getAuthenticationMethods() { return this.getClaimAsStringList(IdTokenClaimNames.AMR); } /** * Returns the Authorized party {@code (azp)} to which the ID Token was issued. * @return the Authorized party to which the ID Token was issued
*/ default String getAuthorizedParty() { return this.getClaimAsString(IdTokenClaimNames.AZP); } /** * Returns the Access Token hash value {@code (at_hash)}. * @return the Access Token hash value */ default String getAccessTokenHash() { return this.getClaimAsString(IdTokenClaimNames.AT_HASH); } /** * Returns the Authorization Code hash value {@code (c_hash)}. * @return the Authorization Code hash value */ default String getAuthorizationCodeHash() { return this.getClaimAsString(IdTokenClaimNames.C_HASH); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\IdTokenClaimAccessor.java
1
请完成以下Java代码
public void setWaitingTime (final int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public int getWaitingTime() { return get_ValueAsInt(COLUMNNAME_WaitingTime); } /** * WorkflowType AD_Reference_ID=328 * Reference name: AD_Workflow Type */ public static final int WORKFLOWTYPE_AD_Reference_ID=328; /** General = G */ public static final String WORKFLOWTYPE_General = "G"; /** Document Process = P */ public static final String WORKFLOWTYPE_DocumentProcess = "P"; /** Document Value = V */ public static final String WORKFLOWTYPE_DocumentValue = "V"; /** Manufacturing = M */ public static final String WORKFLOWTYPE_Manufacturing = "M"; /** Quality = Q */ public static final String WORKFLOWTYPE_Quality = "Q"; /** Repair = R */ public static final String WORKFLOWTYPE_Repair = "R"; @Override public void setWorkflowType (final java.lang.String WorkflowType) { set_Value (COLUMNNAME_WorkflowType, WorkflowType); } @Override public java.lang.String getWorkflowType() { return get_ValueAsString(COLUMNNAME_WorkflowType); }
@Override public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow.java
1
请在Spring Boot框架中完成以下Java代码
class WebMvcEndpointChildContextConfiguration { /* * The error controller is present but not mapped as an endpoint in this context * because of the DispatcherServlet having had its HandlerMapping explicitly disabled. * So we expose the same feature but only for machine endpoints. */ @Bean @ConditionalOnBean(ErrorAttributes.class) ManagementErrorEndpoint errorEndpoint(ErrorAttributes errorAttributes, WebProperties webProperties) { return new ManagementErrorEndpoint(errorAttributes, webProperties.getError()); } @Bean @ConditionalOnBean(ErrorAttributes.class) ManagementErrorPageCustomizer managementErrorPageCustomizer(WebProperties webProperties) { return new ManagementErrorPageCustomizer(webProperties); } @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) DispatcherServlet dispatcherServlet() { DispatcherServlet dispatcherServlet = new DispatcherServlet(); // Ensure the parent configuration does not leak down to us dispatcherServlet.setDetectAllHandlerAdapters(false); dispatcherServlet.setDetectAllHandlerExceptionResolvers(false); dispatcherServlet.setDetectAllHandlerMappings(false); dispatcherServlet.setDetectAllViewResolvers(false); return dispatcherServlet; } @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) { return new DispatcherServletRegistrationBean(dispatcherServlet, "/"); } @Bean(name = DispatcherServlet.HANDLER_MAPPING_BEAN_NAME) CompositeHandlerMapping compositeHandlerMapping() { return new CompositeHandlerMapping(); } @Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME) CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) { return new CompositeHandlerAdapter(beanFactory); } @Bean(name = DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME) CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() { return new CompositeHandlerExceptionResolver(); } @Bean @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } /**
* {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the * {@link ManagementErrorEndpoint} can be used. */ static class ManagementErrorPageCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered { private final WebProperties properties; ManagementErrorPageCustomizer(WebProperties properties) { this.properties = properties; } @Override public void customize(ConfigurableServletWebServerFactory factory) { factory.addErrorPages(new ErrorPage(this.properties.getError().getPath())); } @Override public int getOrder() { return 10; // Run after ManagementWebServerFactoryCustomizer } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java
2
请完成以下Java代码
public I_C_BP_BankAccount createNewC_BP_BankAccount(final IContextAware contextProvider, final int bpartnerId) { final PaymentString paymentString = getPaymentString(); final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class, contextProvider); Check.assume(bpartnerId > 0, "We assume the bPartnerId to be greater than 0. This={}", this); bpBankAccount.setC_BPartner_ID(bpartnerId); final Currency currency = currencyDAO.getByCurrencyCode(CurrencyCode.CHF); // CHF, because it's ESR bpBankAccount.setC_Currency_ID(currency.getId().getRepoId()); bpBankAccount.setIsEsrAccount(true); // ..because we are creating this from an ESR/QRR string bpBankAccount.setIsACH(true); final String bPartnerName = bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(bpartnerId)); bpBankAccount.setA_Name(bPartnerName); bpBankAccount.setName(bPartnerName);
bpBankAccount.setQR_IBAN(paymentString.getIBAN()); bpBankAccount.setAccountNo(paymentString.getInnerAccountNo()); bpBankAccount.setESR_RenderedAccountNo(paymentString.getPostAccountNo()); // we can not know it InterfaceWrapperHelper.save(bpBankAccount); return bpBankAccount; } @Override public String toString() { return String.format("QRPaymentStringDataProvider [getPaymentString()=%s]", getPaymentString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\api\impl\QRPaymentStringDataProvider.java
1
请完成以下Java代码
public class VertragsdatenAbfragen { @XmlElement(namespace = "", required = true) protected String clientSoftwareKennung; /** * Gets the value of the clientSoftwareKennung property. * * @return * possible object is * {@link String } * */ public String getClientSoftwareKennung() { return clientSoftwareKennung;
} /** * Sets the value of the clientSoftwareKennung property. * * @param value * allowed object is * {@link String } * */ public void setClientSoftwareKennung(String value) { this.clientSoftwareKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenAbfragen.java
1
请完成以下Java代码
public void validate(I_AD_ColumnCallout callout) { if (Check.isEmpty(callout.getClassname(), true)) { throw new AdempiereException("No classname specified"); } final String fqMethodName = callout.getClassname(); final int idx = fqMethodName.lastIndexOf('.'); final String classname = fqMethodName.substring(0, idx); final String methodName = fqMethodName.substring(idx + 1); final Method method = validateJavaMethodName(classname, org.compiere.model.Callout.class, methodName); // Expected params, variant 1: Properties ctx, int windowNo, GridTab gridTab, GridField gridField, Object value final Class<?>[] expectedParams1 = new Class<?>[] { java.util.Properties.class, int.class, GridTab.class, GridField.class, Object.class }; // Expected params, variant 2: Properties ctx, int windowNo, GridTab gridTab, GridField gridField, Object value, Object valueOld final Class<?>[] expectedParams2 = new Class<?>[] { java.util.Properties.class, int.class, GridTab.class, GridField.class, Object.class, Object.class }; if (!Objects.equals(expectedParams1, method.getParameterTypes()) && !Objects.equals(expectedParams2, method.getParameterTypes())) { throw new AdempiereException("Invalid parameters for callout method " + method); } } @Override public String getLogMessage(final IADValidatorViolation violation) { final StringBuilder message = new StringBuilder(); try
{ final I_AD_ColumnCallout callout = InterfaceWrapperHelper.create(violation.getItem(), I_AD_ColumnCallout.class); final I_AD_Column column = callout.getAD_Column(); final String tableName = Services.get(IADTableDAO.class).retrieveTableName(column.getAD_Table_ID()); message.append("Error on ").append(tableName).append(".").append(column.getColumnName()).append(" - ").append(callout.getClassname()) .append(" (IsActive=").append(callout.isActive()).append("): "); } catch (Exception e) { message.append("Error (InterfaceWrapperHelper exception: ").append(e.getLocalizedMessage()).append(") on ").append(violation.getItem()).append(": "); } message.append(violation.getError().getLocalizedMessage()); return message.toString(); } @Override public Class<I_AD_ColumnCallout> getType() { return I_AD_ColumnCallout.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\spi\impl\ADColumnCalloutADValidator.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Standard. @param IsDefault Default value */ @Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Standard. @return Default value */ @Override public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); 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 */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Region.java
1
请完成以下Java代码
public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) { this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected; } /** * Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt> * object for the user. Defaults to an {@link AccountStatusUserDetailsChecker}. * @param userDetailsChecker */ public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { Assert.notNull(userDetailsChecker, "userDetailsChecker cannot be null"); this.userDetailsChecker = userDetailsChecker; } /** * Sets authorities that this provider should grant once authentication completes * @param grantedAuthoritySupplier the supplier that grants authorities
*/ public void setGrantedAuthoritySupplier(Supplier<Collection<GrantedAuthority>> grantedAuthoritySupplier) { Assert.notNull(grantedAuthoritySupplier, "grantedAuthoritySupplier cannot be null"); this.grantedAuthoritySupplier = grantedAuthoritySupplier; } @Override public int getOrder() { return this.order; } public void setOrder(int i) { this.order = i; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\PreAuthenticatedAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public void fetchAuthorByBook() { Book book = bookRepository.findById(4L).orElseThrow(); Author author = authorRepository.findByBooks(book); System.out.println("Fetched author: " + author); } @Transactional public void fetchBooksByAuthor() { Author author = authorRepository.findById(4L).orElseThrow(); List<Book> books = bookRepository.findByAuthor(author); System.out.println("Fetched books: " + books); } @Transactional public void fetchAuthorByBooksReviews() { Review review = reviewRepository.findById(1L).orElseThrow(); Author author = authorRepository.findByBooksReviews(review); System.out.println("Fetched author: " + author); } @Transactional(readOnly = true) public void fetchAuthorByBookDto() { Book book = bookRepository.findById(4L).orElseThrow(); AuthorDto author = authorRepository.queryByBooks(book); System.out.println("Fetched author (DTO): " + author.getName()); } @Transactional(readOnly = true) public void fetchBooksByAuthorDto() {
Author author = authorRepository.findById(4L).orElseThrow(); List<BookDto> books = bookRepository.queryByAuthor(author); System.out.println("Fetched books (DTO):"); books.forEach(b -> System.out.println(b.getTitle())); } @Transactional(readOnly = true) public void fetchAuthorByBooksReviewsDto() { Review review = reviewRepository.findById(1L).orElseThrow(); AuthorDto author = authorRepository.queryByBooksReviews(review); System.out.println("Fetched author (DTO): " + author.getName()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class LambdaVariables { private volatile boolean run = true; private int start = 0; private ExecutorService executor = Executors.newFixedThreadPool(3); public static void main(String[] args) { new LambdaVariables().localVariableMultithreading(); } Supplier<Integer> incrementer(int start) { return () -> start; // can't modify start parameter inside the lambda } Supplier<Integer> incrementer() { return () -> start++; } public void localVariableMultithreading() { boolean run = true; executor.execute(() -> { while (run) { // do operation } }); // commented because it doesn't compile, it's just an example of non-final local variables in lambdas // run = false; } public void instanceVariableMultithreading() { executor.execute(() -> { while (run) { // do operation } }); run = false; } /**
* WARNING: always avoid this workaround!! */ public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]); holder[0] = 0; System.out.println(sums.sum()); } /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() { int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0]) .sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请在Spring Boot框架中完成以下Java代码
public class User implements Serializable { /** * 编号 */ @Id @GeneratedValue private Long id; /** * 名称 */ @NotEmpty(message = "姓名不能为空") @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") private String name; /** * 年龄 */ @NotNull(message = "年龄不能为空") @Min(value = 0, message = "年龄大于 0") @Max(value = 300, message = "年龄不大于 300") private Integer age; /** * 出生时间 */ @NotEmpty(message = "出生时间不能为空") private String birthday; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) {
this.age = age; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public User(String name, Integer age, String birthday) { this.name = name; this.age = age; this.birthday = birthday; } public User() {} @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } }
repos\springboot-learning-example-master\chapter-4-spring-boot-validating-form-input\src\main\java\spring\boot\core\domain\User.java
2
请在Spring Boot框架中完成以下Java代码
public FileVisitResult visitFile(@NonNull final Path currentFile, final BasicFileAttributes attrs) { if (bpartnerFileMatcher.matches(currentFile.getFileName())) { existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } if (warehouseFileMatcher.matches(currentFile.getFileName())) { existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } if (productFileMatcher.matches(currentFile.getFileName())) { existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(rootLocation, options, 1, visitor); // maxDepth=1 means to check the folder and its included files } catch (final IOException e) { throw new RuntimeCamelException("Caught exception while checking for existing master data files", e); }
final boolean atLEastOneFileFound = existingMasterDataFile[0] != null; if (atLEastOneFileFound) { final String fileName = exchange.getIn().getBody(GenericFile.class).getFileName(); pInstanceLogger.logMessage("There is at least the masterdata file " + existingMasterDataFile[0].getFileName() + " which has to be processed first => stall the processing of orders file " + fileName + " for now"); } return atLEastOneFileFound; } @Override protected void doStop() { stopWaitLoop.set(true); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\StallWhileMasterdataFilesExistPolicy.java
2
请完成以下Java代码
public class UserAggregate { private EventStore writeRepository; public UserAggregate(EventStore repository) { this.writeRepository = repository; } public List<Event> handleCreateUserCommand(CreateUserCommand command) { UserCreatedEvent event = new UserCreatedEvent(command.getUserId(), command.getFirstName(), command.getLastName()); writeRepository.addEvent(command.getUserId(), event); return Arrays.asList(event); } public List<Event> handleUpdateUserCommand(UpdateUserCommand command) { User user = UserUtility.recreateUserState(writeRepository, command.getUserId()); List<Event> events = new ArrayList<>(); List<Contact> contactsToRemove = user.getContacts() .stream() .filter(c -> !command.getContacts() .contains(c)) .collect(Collectors.toList()); for (Contact contact : contactsToRemove) { UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail()); events.add(contactRemovedEvent); writeRepository.addEvent(command.getUserId(), contactRemovedEvent); } List<Contact> contactsToAdd = command.getContacts() .stream() .filter(c -> !user.getContacts() .contains(c)) .collect(Collectors.toList()); for (Contact contact : contactsToAdd) { UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail()); events.add(contactAddedEvent);
writeRepository.addEvent(command.getUserId(), contactAddedEvent); } List<Address> addressesToRemove = user.getAddresses() .stream() .filter(a -> !command.getAddresses() .contains(a)) .collect(Collectors.toList()); for (Address address : addressesToRemove) { UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode()); events.add(addressRemovedEvent); writeRepository.addEvent(command.getUserId(), addressRemovedEvent); } List<Address> addressesToAdd = command.getAddresses() .stream() .filter(a -> !user.getAddresses() .contains(a)) .collect(Collectors.toList()); for (Address address : addressesToAdd) { UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode()); events.add(addressAddedEvent); writeRepository.addEvent(command.getUserId(), addressAddedEvent); } return events; } }
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\escqrs\aggregates\UserAggregate.java
1
请在Spring Boot框架中完成以下Java代码
public Guard<String, String> simpleGuard() { return ctx -> { int approvalCount = (int) ctx .getExtendedState() .getVariables() .getOrDefault("approvalCount", 0); return approvalCount > 0; }; } @Bean public Action<String, String> entryAction() { return ctx -> LOGGER.info("Entry " + ctx .getTarget() .getId()); } @Bean public Action<String, String> doAction() { return ctx -> LOGGER.info("Do " + ctx .getTarget() .getId()); } @Bean public Action<String, String> executeAction() { return ctx -> { LOGGER.info("Execute " + ctx .getTarget() .getId()); int approvals = (int) ctx .getExtendedState() .getVariables() .getOrDefault("approvalCount", 0);
approvals++; ctx .getExtendedState() .getVariables() .put("approvalCount", approvals); }; } @Bean public Action<String, String> exitAction() { return ctx -> LOGGER.info("Exit " + ctx .getSource() .getId() + " -> " + ctx .getTarget() .getId()); } @Bean public Action<String, String> errorAction() { return ctx -> LOGGER.info("Error " + ctx .getSource() .getId() + ctx.getException()); } @Bean public Action<String, String> initAction() { return ctx -> LOGGER.info(ctx .getTarget() .getId()); } }
repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\SimpleStateMachineConfiguration.java
2
请完成以下Java代码
public class DeleteProcessInstanceStartEventSubscriptionCmd extends AbstractProcessStartEventSubscriptionCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected final ProcessInstanceStartEventSubscriptionDeletionBuilderImpl builder; public DeleteProcessInstanceStartEventSubscriptionCmd(ProcessInstanceStartEventSubscriptionDeletionBuilderImpl builder) { this.builder = builder; } @Override public Void execute(CommandContext commandContext) { Process process = getProcess(builder.getProcessDefinitionId(), commandContext); List<StartEvent> startEvents = process.findFlowElementsOfType(StartEvent.class, false); for (StartEvent startEvent : startEvents) { // looking for a start event based on an event-registry event subscription List<ExtensionElement> eventTypeElements = startEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE); if (eventTypeElements != null && eventTypeElements.size() > 0) { // looking for a dynamic, manually subscribed behavior of the event-registry start event List<ExtensionElement> correlationConfiguration = startEvent.getExtensionElements().get(BpmnXMLConstants.START_EVENT_CORRELATION_CONFIGURATION); if (correlationConfiguration != null && correlationConfiguration.size() > 0 && BpmnXMLConstants.START_EVENT_CORRELATION_MANUAL.equals(correlationConfiguration.get(0).getElementText())) {
String eventDefinitionKey = eventTypeElements.get(0).getElementText(); String correlationKey = null; if (builder.hasCorrelationParameterValues()) { correlationKey = generateCorrelationConfiguration(eventDefinitionKey, builder.getTenantId(), builder.getCorrelationParameterValues(), commandContext); } getEventSubscriptionService(commandContext).deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(builder.getProcessDefinitionId(), eventDefinitionKey, startEvent.getId(), correlationKey); } } } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\DeleteProcessInstanceStartEventSubscriptionCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class BookController { @Autowired private BookService bookService; @GetMapping public List<Book> findAllBooks() { return bookService.findAllBooks(); } @GetMapping("/{bookId}") public Book findBook(@PathVariable("bookId") Long bookId) { return bookService.findBookById(bookId); } @PostMapping public Book createBook(@RequestBody Book book) { return bookService.createBook(book);
} @DeleteMapping("/{bookId}") public void deleteBook(@PathVariable("bookId") Long bookId) { bookService.deleteBook(bookId); } @PutMapping("/{bookId}") public Book updateBook(@RequestBody Book book, @PathVariable("bookId") Long bookId) { return bookService.updateBook(book, bookId); } @PatchMapping("/{bookId}") public Book updateBook(@RequestBody Map<String, String> updates, @PathVariable("bookId") Long bookId) { return bookService.updateBook(updates, bookId); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-book\src\main\java\com\baeldung\spring\cloud\bootstrap\svcbook\book\BookController.java
2
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public Book title(String title) { this.title = title; return this; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public Book isbn(String isbn) { this.isbn = isbn; return this; } public void setIsbn(String isbn) { this.isbn = isbn; } public Author getAuthor() { return author; } public Book author(Author author) { this.author = author; return this; } public void setAuthor(Author author) { this.author = author; } @Override public boolean equals(Object obj) {
if (this == obj) { return true; } if (!(obj instanceof Book)) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFluentApiAdditionalMethods\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public void setPercentage(BigDecimal value) { this.percentage = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmount(BigDecimal value) { this.amount = value; } /** * Gets the value of the calcuationCode property. * * @return * possible object is * {@link String } * */ public String getCalcuationCode() { return calcuationCode; } /** * Sets the value of the calcuationCode property. * * @param value * allowed object is * {@link String } * */ public void setCalcuationCode(String value) { this.calcuationCode = value; } /** * Gets the value of the vatRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getVATRate() { return vatRate; }
/** * Sets the value of the vatRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setVATRate(BigDecimal value) { this.vatRate = value; } /** * Gets the value of the allowanceOrChargeQualifier property. * * @return * possible object is * {@link String } * */ public String getAllowanceOrChargeQualifier() { return allowanceOrChargeQualifier; } /** * Sets the value of the allowanceOrChargeQualifier property. * * @param value * allowed object is * {@link String } * */ public void setAllowanceOrChargeQualifier(String value) { this.allowanceOrChargeQualifier = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdditionalChargesAndReductionsType.java
2
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ @Override public void setNode_ID (int Node_ID)
{ if (Node_ID < 0) set_Value (COLUMNNAME_Node_ID, null); else set_Value (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ @Override public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_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_AD_TreeBar.java
1
请完成以下Java代码
public class Signal extends BaseElement { public static final String SCOPE_GLOBAL = "global"; public static final String SCOPE_PROCESS_INSTANCE = "processInstance"; protected String name; protected String scope; public Signal() {} public Signal(String id, String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getScope() { return scope; } public void setScope(String scope) {
this.scope = scope; } public Signal clone() { Signal clone = new Signal(); clone.setValues(this); return clone; } public void setValues(Signal otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setScope(otherElement.getScope()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Signal.java
1
请完成以下Java代码
public String getTour() { return tour; } /** * Sets the value of the tour property. * * @param value * allowed object is * {@link String } * */ public void setTour(String value) { this.tour = value; } /** * Gets the value of the grund property. * * @return * possible object is * {@link VerfuegbarkeitDefektgrund } * */ public VerfuegbarkeitDefektgrund getGrund() { return grund; } /** * Sets the value of the grund property.
* * @param value * allowed object is * {@link VerfuegbarkeitDefektgrund } * */ public void setGrund(VerfuegbarkeitDefektgrund value) { this.grund = value; } /** * Gets the value of the tourabweichung property. * */ public boolean isTourabweichung() { return tourabweichung; } /** * Sets the value of the tourabweichung property. * */ public void setTourabweichung(boolean value) { this.tourabweichung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VerfuegbarkeitAnteil.java
1
请完成以下Java代码
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public int getAge() { return age; } public void setAge(int age) { this.age = age;
} public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\java\com\neo\entity\User.java
1
请完成以下Java代码
public void setSttlmPlc(BranchAndFinancialInstitutionIdentification4 value) { this.sttlmPlc = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryAgent2 } * * */ public List<ProprietaryAgent2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryAgent2>(); } return this.prtry; } }
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\TransactionAgents2.java
1
请在Spring Boot框架中完成以下Java代码
public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("driverClassName")); dataSource.setUrl(env.getProperty("url")); dataSource.setUsername(env.getProperty("user")); dataSource.setPassword(env.getProperty("password")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.baeldung.relationships.models"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; }
final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); if (env.getProperty("hibernate.hbm2ddl.auto") != null) { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); } if (env.getProperty("hibernate.dialect") != null) { hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); } if (env.getProperty("hibernate.show_sql") != null) { hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); } return hibernateProperties; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\AppConfig.java
2
请完成以下Java代码
public void setSeparator (final java.lang.String Separator) { set_Value (COLUMNNAME_Separator, Separator); } @Override public java.lang.String getSeparator() { return get_ValueAsString(COLUMNNAME_Separator); } /** * TaxCorrectionType AD_Reference_ID=392 * Reference name: C_AcctSchema TaxCorrectionType */ public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392; /** None = N */ public static final String TAXCORRECTIONTYPE_None = "N"; /** Write_OffOnly = W */ public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */ public static final String TAXCORRECTIONTYPE_DiscountOnly = "D"; /** Write_OffAndDiscount = B */ public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B"; @Override public void setTaxCorrectionType (final java.lang.String TaxCorrectionType) { set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType); } @Override public java.lang.String getTaxCorrectionType() { return get_ValueAsString(COLUMNNAME_TaxCorrectionType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Event{" + "id=" + id + ", name='" + name + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}'; } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\localdatetimequery\Event.java
1
请完成以下Java代码
public class MqttTopicMatcher { @Getter private final String topic; private final Pattern topicRegex; public MqttTopicMatcher(String topic) { if (topic == null) { throw new NullPointerException("topic"); } this.topic = topic; this.topicRegex = Pattern.compile(topic.replace("+", "[^/]+").replace("#", ".+") + "$"); } public boolean matches(String topic) { return this.topicRegex.matcher(topic).matches(); } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MqttTopicMatcher that = (MqttTopicMatcher) o; return topic.equals(that.topic); } @Override public int hashCode() { return topic.hashCode(); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\MqttTopicMatcher.java
1
请完成以下Java代码
private static String newEventId() { return UUID.randomUUID().toString(); } public ClientId getClientId() { return getClientAndOrgId().getClientId(); } public OrgId getOrgId() { return getClientAndOrgId().getOrgId(); }
@NonNull public EventDescriptor withNewEventId() { return toBuilder() .eventId(newEventId()) .build(); } @NonNull public EventDescriptor withClientAndOrg(@NonNull final ClientAndOrgId clientAndOrgId) { return toBuilder() .clientAndOrgId(clientAndOrgId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\EventDescriptor.java
1
请完成以下Java代码
public static final class Builder { private final Map<DependencyType, ImmutableSetMultimap.Builder<String, String>> type2name2dependencies = new HashMap<>(); private Builder() { super(); } public DocumentFieldDependencyMap build() { if (type2name2dependencies.isEmpty()) { return EMPTY; } return new DocumentFieldDependencyMap(this); } private ImmutableMap<DependencyType, Multimap<String, String>> getType2Name2DependenciesMap() { final ImmutableMap.Builder<DependencyType, Multimap<String, String>> builder = ImmutableMap.builder(); for (final Entry<DependencyType, ImmutableSetMultimap.Builder<String, String>> e : type2name2dependencies.entrySet()) { final DependencyType dependencyType = e.getKey(); final Multimap<String, String> name2dependencies = e.getValue().build(); if (name2dependencies.isEmpty()) { continue; } builder.put(dependencyType, name2dependencies); } return builder.build(); } public Builder add( @NonNull final String fieldName, @Nullable final Collection<String> dependsOnFieldNames, @NonNull final DependencyType dependencyType) { if (dependsOnFieldNames == null || dependsOnFieldNames.isEmpty()) { return this; }
final ImmutableSetMultimap.Builder<String, String> fieldName2dependsOnFieldNames = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder()); for (final String dependsOnFieldName : dependsOnFieldNames) { fieldName2dependsOnFieldNames.put(dependsOnFieldName, fieldName); } return this; } public Builder add(@Nullable final DocumentFieldDependencyMap dependencies) { if (dependencies == null || dependencies == EMPTY) { return this; } for (final Map.Entry<DependencyType, Multimap<String, String>> l1 : dependencies.type2name2dependencies.entrySet()) { final DependencyType dependencyType = l1.getKey(); final ImmutableSetMultimap.Builder<String, String> name2dependencies = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder()); name2dependencies.putAll(l1.getValue()); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDependencyMap.java
1
请完成以下Java代码
public void show(Component invoker, int x, int y) { boolean available = checkAvailableActions(); if (available) { super.show(invoker, x, y); } else { setVisible(false); } } /** * Check and update all menu items if available * * @return true if ANY item is available */ private boolean checkAvailableActions() { initActions(); final boolean available = checkAvailable(this); return available; } /** * Check and update menu item if available * * @return true if item is available */ private boolean checkAvailable(MenuElement item) { final Component itemComp = item.getComponent(); final boolean isRoot = item == this; if (!isRoot) { final IContextMenuAction action = getAction(item); if (action == null) { // not controlled by this editor, take it's status and return final boolean available = itemComp.isVisible(); return available; } if (!action.isAvailable()) { itemComp.setVisible(false); return false; } if (!action.isRunnable()) { final boolean hideWhenNotRunnable = action.isHideWhenNotRunnable(); itemComp.setVisible(!hideWhenNotRunnable); itemComp.setEnabled(false); return false; } } final MenuElement[] children = getSubElements(item); if (children != null && children.length > 0) { boolean submenuAvailable = false; for (MenuElement subitem : children) { final boolean subitemAvailable = checkAvailable(subitem); if (subitemAvailable) { submenuAvailable = true; } } itemComp.setVisible(submenuAvailable); return submenuAvailable; }
else { itemComp.setVisible(true); itemComp.setEnabled(true); } return true; } private final IContextMenuAction getAction(MenuElement me) { final Component c = me.getComponent(); if (c instanceof JComponent) { final JComponent jc = (JComponent)c; final IContextMenuAction action = (IContextMenuAction)jc.getClientProperty(ATTR_Action); return action; } return null; } public void add(final IContextMenuAction action) { Check.assumeNotNull(action, "action not null"); // make sure actions are initialized and UI created before we are adding our new action initActions(); createUI(this, action); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\EditorContextPopupMenu.java
1
请完成以下Java代码
public synchronized boolean hasActiveSubscriptions() { return !activeSubscriptionIds.isEmpty(); } public synchronized boolean isShallBeDestroyed() { return destroyIfNoActiveSubscriptions && !hasActiveSubscriptions(); } private WebSocketProducerInstance toNullIfShallBeDestroyed() { return isShallBeDestroyed() ? null : this; } private void stopIfNoSubscription() { if (hasActiveSubscriptions()) { return; } final boolean wasRunning = running.getAndSet(false); if (wasRunning) { producerControls.onStop(); } stopScheduledFuture(); logger.debug("{} stopped", this); } private void startScheduledFutureIfApplies() { // Does not apply if (onPollingEventsSupplier == null) { return; } // // Check if the producer was already scheduled if (scheduledFuture != null) { return; } // // Schedule producer final long initialDelayMillis = 1000; final long periodMillis = 1000; scheduledFuture = scheduler.scheduleAtFixedRate(this::pollAndPublish, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS); logger.trace("{}: start producing using initialDelayMillis={}, periodMillis={}", this, initialDelayMillis, periodMillis); } private void stopScheduledFuture() {
if (scheduledFuture == null) { return; } try { scheduledFuture.cancel(true); } catch (final Exception ex) { logger.warn("{}: Failed stopping scheduled future: {}. Ignored and considering it as stopped", this, scheduledFuture, ex); } scheduledFuture = null; } private void pollAndPublish() { if (onPollingEventsSupplier == null) { return; } try { final List<?> events = onPollingEventsSupplier.produceEvents(); if (events != null && !events.isEmpty()) { for (final Object event : events) { websocketSender.convertAndSend(topicName, event); logger.trace("Event sent to {}: {}", topicName, event); } } else { logger.trace("Got no events from {}", onPollingEventsSupplier); } } catch (final Exception ex) { logger.warn("Failed producing event for {}. Ignored.", this, ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducersRegistry.java
1
请完成以下Java代码
public Builder attribute(String name, Object value) { if (this.attributes == null) { this.attributes = new HashMap<>(); } this.attributes.put(name, value); return this; } /** * Builds a new {@link OAuth2AuthorizationContext}. * @return a {@link OAuth2AuthorizationContext} */ public OAuth2AuthorizationContext build() { Assert.notNull(this.principal, "principal cannot be null"); OAuth2AuthorizationContext context = new OAuth2AuthorizationContext(); if (this.authorizedClient != null) {
context.clientRegistration = this.authorizedClient.getClientRegistration(); context.authorizedClient = this.authorizedClient; } else { context.clientRegistration = this.clientRegistration; } context.principal = this.principal; context.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes) ? Collections.emptyMap() : new LinkedHashMap<>(this.attributes)); return context; } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizationContext.java
1
请完成以下Java代码
public TbMsgBuilder metaData(TbMsgMetaData metaData) { this.metaData = metaData; return this; } public TbMsgBuilder copyMetaData(TbMsgMetaData metaData) { this.metaData = metaData.copy(); return this; } public TbMsgBuilder dataType(TbMsgDataType dataType) { this.dataType = dataType; return this; } public TbMsgBuilder data(String data) { this.data = data; return this; } public TbMsgBuilder ruleChainId(RuleChainId ruleChainId) { this.ruleChainId = ruleChainId; return this; } public TbMsgBuilder ruleNodeId(RuleNodeId ruleNodeId) { this.ruleNodeId = ruleNodeId; return this; } public TbMsgBuilder resetRuleNodeId() { return ruleNodeId(null); } public TbMsgBuilder correlationId(UUID correlationId) { this.correlationId = correlationId; return this; } public TbMsgBuilder partition(Integer partition) { this.partition = partition; return this; } public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds); return this;
} public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) { this.ctx = ctx; return this; } public TbMsgBuilder callback(TbMsgCallback callback) { this.callback = callback; return this; } public TbMsg build() { return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback); } public String toString() { return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts + ", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator + ", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType + ", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId + ", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds + ", ctx=" + this.ctx + ", callback=" + this.callback + ")"; } } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
1
请在Spring Boot框架中完成以下Java代码
public UnitPriceType getSalesValue() { return salesValue; } /** * Sets the value of the salesValue property. * * @param value * allowed object is * {@link UnitPriceType } * */ public void setSalesValue(UnitPriceType value) { this.salesValue = value; } /** * Extra charge for the given list line item. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getExtraCharge() { return extraCharge; } /** * Sets the value of the extraCharge property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setExtraCharge(BigDecimal value) { this.extraCharge = value; } /** * The tax amount for this line item (gross - net = tax amount) * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxAmount() { return taxAmount; } /** * Sets the value of the taxAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxAmount(BigDecimal value) { this.taxAmount = value;
} /** * The overall amount for this line item (net value). * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getLineItemAmount() { return lineItemAmount; } /** * Sets the value of the lineItemAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setLineItemAmount(BigDecimal value) { this.lineItemAmount = value; } /** * Gets the value of the listLineItemExtension property. * * @return * possible object is * {@link ListLineItemExtensionType } * */ public ListLineItemExtensionType getListLineItemExtension() { return listLineItemExtension; } /** * Sets the value of the listLineItemExtension property. * * @param value * allowed object is * {@link ListLineItemExtensionType } * */ public void setListLineItemExtension(ListLineItemExtensionType value) { this.listLineItemExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemType.java
2