instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private String getToken(SysUser user) { // 生成token String token = JwtUtil.sign(user.getUsername(), user.getPassword(), CommonConstant.CLIENT_TYPE_PC); redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token); // 设置超时时间 1个小时 redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 1 / 1000); return token; } /** * 是否定时发送邮箱 * @param toUser * @param title * @param content * @return */ private boolean isTimeJobSendEmail(String toUser, String title, String content) { StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class); Boolean timeJobSend = staticConfig.getTimeJobSend(); if(null != timeJobSend && timeJobSend){
this.addSysSmsSend(toUser,title,content); return true; } return false; } /** * 保存到短信发送表 */ private void addSysSmsSend(String toUser, String title, String content) { SysMessage sysMessage = new SysMessage(); sysMessage.setEsTitle(title); sysMessage.setEsContent(content); sysMessage.setEsReceiver(toUser); sysMessage.setEsSendStatus("0"); sysMessage.setEsSendNum(0); sysMessage.setEsType(MessageTypeEnum.YJ.getType()); sysMessageMapper.insert(sysMessage); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\handle\impl\EmailSendMsgHandle.java
1
请完成以下Spring Boot application配置
spring: data: # MongoDB 配置项,对应 MongoProperties 类 mongodb: host: 127.0.0.1 port: 27017 database: yourdatabase username: test01 password: password01 # 上述属性,也可以只配置 uri logging: level: org: s
pringframework: data: mongodb: core: DEBUG # 打印 mongodb 操作的具体语句。生产环境下,不建议开启。
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\resources\application.yaml
2
请完成以下Java代码
public VariableContainer getInputVariableContainer() { return inputVariableContainer; } /** * @see Builder#storeScriptVariables */ public boolean isStoreScriptVariables() { return storeScriptVariables; } /** * @see Builder#additionalResolver(Resolver) */ public List<Resolver> getAdditionalResolvers() { return additionalResolvers; }
/** * @see Builder#traceEnhancer(ScriptTraceEnhancer) */ public ScriptTraceEnhancer getTraceEnhancer() { return traceEnhancer; } @Override public String toString() { return new StringJoiner(", ", ScriptEngineRequest.class.getSimpleName() + "[", "]") .add("language='" + language + "'") .add("script='" + script + "'") .add("variableContainer=" + scopeContainer) .add("storeScriptVariables=" + storeScriptVariables) .toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptEngineRequest.java
1
请完成以下Java代码
public Builder withBusinessKey(String businessKey) { this.businessKey = businessKey; return this; } /** * Builder method for configuration parameter. * @param configuration field to set * @return builder */ public Builder withConfiguration(String configuration) { this.configuration = configuration; return this; } /** * Builder method for activityId parameter. * @param activityId field to set * @return builder */ public Builder withActivityId(String activityId) { this.activityId = activityId; return this; } /** * Builder method for created parameter.
* @param created field to set * @return builder */ public Builder withCreated(Date created) { this.created = created; return this; } /** * Builder method of the builder. * @return built class */ public MessageSubscriptionImpl build() { return new MessageSubscriptionImpl(this); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\MessageSubscriptionImpl.java
1
请完成以下Java代码
public void setInvoicedQty (java.math.BigDecimal InvoicedQty) { set_Value (COLUMNNAME_InvoicedQty, InvoicedQty); } /** Get Berechnete Menge. @return The quantity invoiced */ @Override public java.math.BigDecimal getInvoicedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoicedQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zeilennetto. @param LineNetAmt Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public void setLineNetAmt (java.math.BigDecimal LineNetAmt) { set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); } /** Get Zeilennetto. @return Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public java.math.BigDecimal getLineNetAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineNetAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Position. @param LineNo Zeile Nr. */ @Override public void setLineNo (int LineNo) { set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo)); } /** Get Position. @return Zeile Nr. */ @Override public int getLineNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LineNo); if (ii == null)
return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customs_Invoice_Line.java
1
请完成以下Java代码
public void setExecutionId(String executionId) {} @Override public Object getValue() { return variableValue; } @Override public void setValue(Object value) { variableValue = value; } @Override public String getTypeName() { return TYPE_TRANSIENT; } @Override public void setTypeName(String typeName) {} @Override public String getProcessInstanceId() {
return null; } @Override public String getTaskId() { return null; } @Override public void setTaskId(String taskId) {} @Override public String getExecutionId() { return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
1
请完成以下Java代码
private final BigDecimal getQtyCapacity() { if (_qtyCapacity != null) { return _qtyCapacity; } return getM_HU_PI_Item_Product().getQty(); } private final String getQtyCapacityUOMSymbol() { final I_C_UOM uom = IHUPIItemProductBL.extractUOMOrNull(getM_HU_PI_Item_Product()); if (uom == null) { return null; } return uom.getUOMSymbol(); } /** * * @return QtyMoved / QtyPlanned string */ private String getQtysDisplayName() { if (_qtyTUPlanned == null && _qtyTUMoved == null) { return null; } final StringBuilder sb = new StringBuilder(); // // Qty Moved if (_qtyTUMoved != null) { sb.append(toQtyTUString(_qtyTUMoved)); } // // Qty Planned { if (sb.length() > 0) { sb.append(" / "); } sb.append(toQtyTUString(_qtyTUPlanned)); } return sb.toString(); } private final String toQtyTUString(final BigDecimal qtyTU) { if (qtyTU == null) { return "?"; } return qtyTU .setScale(0, RoundingMode.UP) // it's general integer, just making sure we don't end up with 3.0000000 .toString(); } @Override public IHUPIItemProductDisplayNameBuilder setM_HU_PI_Item_Product(final I_M_HU_PI_Item_Product huPIItemProduct) { _huPIItemProduct = huPIItemProduct; return this; } @Override public IHUPIItemProductDisplayNameBuilder setM_HU_PI_Item_Product(@NonNull final HUPIItemProductId id) { final I_M_HU_PI_Item_Product huPIItemProduct = Services.get(IHUPIItemProductDAO.class).getRecordById(id); return setM_HU_PI_Item_Product(huPIItemProduct); } private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product() { Check.assumeNotNull(_huPIItemProduct, "_huPIItemProduct not null"); return _huPIItemProduct; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final BigDecimal qtyTUPlanned) { _qtyTUPlanned = qtyTUPlanned; return this; }
@Override public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final int qtyTUPlanned) { setQtyTUPlanned(BigDecimal.valueOf(qtyTUPlanned)); return this; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final BigDecimal qtyTUMoved) { _qtyTUMoved = qtyTUMoved; return this; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final int qtyTUMoved) { setQtyTUMoved(BigDecimal.valueOf(qtyTUMoved)); return this; } @Override public HUPIItemProductDisplayNameBuilder setQtyCapacity(final BigDecimal qtyCapacity) { _qtyCapacity = qtyCapacity; return this; } @Override public IHUPIItemProductDisplayNameBuilder setShowAnyProductIndicator(boolean showAnyProductIndicator) { this._showAnyProductIndicator = showAnyProductIndicator; return this; } private boolean isShowAnyProductIndicator() { return _showAnyProductIndicator; } private boolean isAnyProductAllowed() { return getM_HU_PI_Item_Product().isAllowAnyProduct(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDisplayNameBuilder.java
1
请完成以下Java代码
public Response getResourceBinary() { U queryResult = baseQueryForBinaryVariable().singleResult(); if (queryResult != null) { TypedValue variableInstance = transformQueryResultIntoTypedValue(queryResult); return new VariableResponseProvider().getResponseForTypedVariable(variableInstance, id); } else { throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); } } protected String getId() { return id; } protected ProcessEngine getEngine() { return engine; } /** * Create the query we need for fetching the desired result. Setting * properties in the query like disableCustomObjectDeserialization() or * disableBinaryFetching() should be done in this method. */ protected abstract Query<T, U> baseQueryForBinaryVariable(); /** * TODO change comment Create the query we need for fetching the desired
* result. Setting properties in the query like * disableCustomObjectDeserialization() or disableBinaryFetching() should be * done in this method. * * @param deserializeObjectValue */ protected abstract Query<T, U> baseQueryForVariable(boolean deserializeObjectValue); protected abstract TypedValue transformQueryResultIntoTypedValue(U queryResult); protected abstract DTO transformToDto(U queryResult); protected abstract String getResourceNameForErrorMessage(); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\AbstractResourceProvider.java
1
请完成以下Java代码
public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port;
} public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class Warehouse { @Id @GeneratedValue private Long id; private String name; private String location; @Type(type = "json") @Column(columnDefinition = "json") private Map<String, String> attributes = new HashMap<>(); 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 String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Map<String, String> getAttributes() { return attributes; } public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\persistjson\Warehouse.java
2
请完成以下Java代码
public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column) { // log.debug( "IDColumnEditor.getTableCellEditorComponent", value); m_table = table; // set value if (value != null && value instanceof IDColumn) m_value = (IDColumn)value; else { m_value = null; return null; //throw new IllegalArgumentException("ICColumnEditor.getTableCellEditorComponent - value=" + value); } // set editor value m_check.setSelected(m_value.isSelected()); return m_check; } // getTableCellEditorComponent /** * Can we edit it * @param anEvent * @return true (constant) */ @Override public boolean isCellEditable (EventObject anEvent) { return true; } // isCellEditable
/** * Can the cell be selected * @param anEvent * @return true (constant) */ @Override public boolean shouldSelectCell (EventObject anEvent) { return true; } // shouldSelectCell /** * Action Listener * @param e */ @Override public void actionPerformed (ActionEvent e) { if (m_table != null) { m_table.editingStopped(new ChangeEvent(this)); } } // actionPerformed } // IDColumnEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\IDColumnEditor.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { private static final String EXECUTION_EXCEPTION_TYPE = "Execution-Exception-Type"; private static final String EXECUTION_EXCEPTION_MESSAGE = "Execution-Exception-Message"; private static final String ROOT_CAUSE_EXCEPTION_TYPE = "Root-Cause-Exception-Type"; private static final String ROOT_CAUSE_EXCEPTION_MESSAGE = "Root-Cause-Exception-Message"; private String executionExceptionTypeHeaderName = EXECUTION_EXCEPTION_TYPE; private String executionExceptionMessageHeaderName = EXECUTION_EXCEPTION_MESSAGE; private String rootCauseExceptionTypeHeaderName = ROOT_CAUSE_EXCEPTION_TYPE; private String rootCauseExceptionMessageHeaderName = ROOT_CAUSE_EXCEPTION_MESSAGE; public String getExecutionExceptionTypeHeaderName() { return executionExceptionTypeHeaderName; } public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) { this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName; } public String getExecutionExceptionMessageHeaderName() { return executionExceptionMessageHeaderName; }
public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) { this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName; } public String getRootCauseExceptionTypeHeaderName() { return rootCauseExceptionTypeHeaderName; } public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) { this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName; } public String getRootCauseExceptionMessageHeaderName() { return rootCauseExceptionMessageHeaderName; } public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) { this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\FallbackHeadersGatewayFilterFactory.java
2
请完成以下Java代码
public Optional<ProductBOM> retrieveValidProductBOM(@NonNull final ProductBOMRequest request) { return bomDAO.retrieveValidProductBOM(request); } @Override public Map<ProductDescriptor, Quantity> calculateRequiredQtyInStockUOMForComponents(@NonNull final Quantity qty, @NonNull final ProductBOM productBOM) { final Map<ProductDescriptor, Quantity> result = new HashMap<>(); final ProductId productId = ProductId.ofRepoId(productBOM.getProductDescriptor().getProductId()); final Quantity qtyInBomUom = uomConversionBL.convertQuantityTo(qty, productId, productBOM.getUomId()); for (final I_PP_Product_BOMLine component : productBOM.getComponents()) { final ProductDescriptor productDescriptor = ProductDescriptor.forProductAndAttributes(component.getM_Product_ID(), AttributesKey.NONE, component.getM_AttributeSetInstance_ID());
final ProductId componentProductId = ProductId.ofRepoId(component.getM_Product_ID()); final I_C_UOM componentUOM = uomDAO.getById(component.getC_UOM_ID()); final Quantity componentQty = Quantity.of(computeQtyRequired(component, productId, qtyInBomUom.toBigDecimal()), componentUOM); final Quantity componentQtyInStockUOM = uomConversionBL.convertToProductUOM(componentQty, ProductId.ofRepoId(component.getM_Product_ID())); result.merge(productDescriptor, componentQtyInStockUOM, Quantity::add); if (productBOM.getComponentsProductBOMs().containsKey(productDescriptor)) { final ProductBOM componentProductBOM = productBOM.getComponentsProductBOMs().get(productDescriptor); final Quantity componentQtyInBomUom = uomConversionBL.convertQuantityTo(componentQtyInStockUOM, componentProductId, componentProductBOM.getUomId()); calculateRequiredQtyInStockUOMForComponents(componentQtyInBomUom, componentProductBOM).forEach((key, value) -> result.merge(key, value, Quantity::add)); } } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMBL.java
1
请完成以下Java代码
public void setIfForeignDiscountsExist (final java.lang.String IfForeignDiscountsExist) { set_Value (COLUMNNAME_IfForeignDiscountsExist, IfForeignDiscountsExist); } @Override public java.lang.String getIfForeignDiscountsExist() { return get_ValueAsString(COLUMNNAME_IfForeignDiscountsExist); } @Override public void setMatchIfTermEndsWithCalendarYear (final boolean MatchIfTermEndsWithCalendarYear) { set_Value (COLUMNNAME_MatchIfTermEndsWithCalendarYear, MatchIfTermEndsWithCalendarYear); } @Override public boolean isMatchIfTermEndsWithCalendarYear() { return get_ValueAsBoolean(COLUMNNAME_MatchIfTermEndsWithCalendarYear); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); }
@Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStartDay (final int StartDay) { set_Value (COLUMNNAME_StartDay, StartDay); } @Override public int getStartDay() { return get_ValueAsInt(COLUMNNAME_StartDay); } @Override public void setStartMonth (final int StartMonth) { set_Value (COLUMNNAME_StartMonth, StartMonth); } @Override public int getStartMonth() { return get_ValueAsInt(COLUMNNAME_StartMonth); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java
1
请完成以下Java代码
public ImmutableSet<ForecastId> createForecasts(@NonNull final List<ForecastRequest> requests) { return requests.stream() .map(forecastDAO::createForecast) .collect(ImmutableSet.toImmutableSet()); } public void completeAndNotifyUser(@NonNull final ImmutableSet<ForecastId> ids, @NonNull final UserId userId) { forecastDAO.streamRecordsByIds(ids).forEach(forecast -> { complete(forecast); sendForecastCompleteNotification(forecast, userId); }); } private void complete(@NonNull final I_M_Forecast forecast)
{ docActionBL.processEx(forecast, IDocument.ACTION_Complete, IDocument.STATUS_Completed); } private void sendForecastCompleteNotification(@NonNull final I_M_Forecast forecast, @NonNull final UserId userId) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .recipientUserId(userId) .contentADMessage(FORECAST_COMPLETED_NOTIFICATION) .contentADMessageParam(forecast.getName() + "|" + forecast.getM_Forecast_ID()) .targetAction(UserNotificationRequest.TargetRecordAction.of(TableRecordReference.of(forecast))) .build(); userNotifications.send(userNotificationRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impl\ForecastService.java
1
请完成以下Java代码
public synchronized boolean contains(Object value) { // TODO: check if that value exists in one of our GridFields return this.ctx.contains(value); } @Override public synchronized boolean containsKey(Object key) { String columnName = getColumnName(key); if (columnName != null && gridTable.findColumn(columnName) != -1) return true; return ctx.containsKey(key); } @Override public boolean containsValue(Object value) { // TODO: check if that value exists in one of our GridFields return ctx.containsValue(value); } @Override public synchronized Enumeration<Object> elements() { // TODO: implement for GridField values too return ctx.elements(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { // TODO: implement for GridField values too return ctx.entrySet(); } @Override public synchronized boolean isEmpty() { return false; } @Override public synchronized Enumeration<Object> keys() { // TODO: implement for GridField values too return ctx.keys(); } @Override public Set<Object> keySet() { // TODO: implement for GridField values too return ctx.keySet(); } @Override public synchronized Object put(Object key, Object value) { if (gridTab == null) throw new IllegalStateException("Method not supported (gridTab is null)"); if (gridTab.getCurrentRow() != row) { return ctx.put(key, value); } String columnName = getColumnName(key); if (columnName == null) { return ctx.put(key, value); } GridField field = gridTab.getField(columnName); if (field == null) { return ctx.put(key, value); } Object valueOld = field.getValue(); field.setValue(value, false); // inserting=false return valueOld;
} @Override public synchronized void putAll(Map<? extends Object, ? extends Object> t) { for (Map.Entry<? extends Object, ? extends Object> e : t.entrySet()) put(e.getKey(), e.getValue()); } @Override public synchronized Object remove(Object key) { // TODO: implement for GridField values too return ctx.remove(key); } @Override public synchronized int size() { // TODO: implement for GridField values too return ctx.size(); } @Override public synchronized String toString() { // TODO: implement for GridField values too return ctx.toString(); } @Override public Collection<Object> values() { return ctx.values(); } @Override public String getProperty(String key) { // I need to override this method, because Properties.getProperty method // is calling super.get() instead of get() Object oval = get(key); return oval == null ? null : oval.toString(); } @Override public String get_ValueAsString(String variableName) { final int windowNo = getWindowNo(); final int tabNo = getTabNo(); // Check value at Tab level, fallback to Window level final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
1
请完成以下Java代码
public final class MetadataBuildItemResolver implements BuildItemResolver { private final InitializrMetadata metadata; private final Version platformVersion; /** * Creates an instance for the specified {@link InitializrMetadata} and {@link Version * platform version}. * @param metadata the metadata to use * @param platformVersion the platform version to consider */ public MetadataBuildItemResolver(InitializrMetadata metadata, Version platformVersion) { this.metadata = metadata; this.platformVersion = platformVersion; } @Override public Dependency resolveDependency(String id) { io.spring.initializr.metadata.Dependency dependency = this.metadata.getDependencies().get(id); if (dependency != null) { return MetadataBuildItemMapper.toDependency(dependency.resolve(this.platformVersion)); } return null;
} @Override public BillOfMaterials resolveBom(String id) { io.spring.initializr.metadata.BillOfMaterials bom = this.metadata.getConfiguration().getEnv().getBoms().get(id); if (bom != null) { return MetadataBuildItemMapper.toBom(bom.resolve(this.platformVersion)); } return null; } @Override public MavenRepository resolveRepository(String id) { if (id.equals(MavenRepository.MAVEN_CENTRAL.getId())) { return MavenRepository.MAVEN_CENTRAL; } return MetadataBuildItemMapper.toRepository(id, this.metadata.getConfiguration().getEnv().getRepositories().get(id)); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\support\MetadataBuildItemResolver.java
1
请在Spring Boot框架中完成以下Java代码
public RouterFunction<ServerResponse> userGetRouterFunction() { return RouterFunctions.route(RequestPredicates.GET("/users2/get"), new HandlerFunction<ServerResponse>() { @Override public Mono<ServerResponse> handle(ServerRequest request) { // 获得编号 Integer id = request.queryParam("id") .map(s -> StringUtils.isEmpty(s) ? null : Integer.valueOf(s)).get(); // 查询用户 UserVO user = new UserVO().setId(id).setUsername(UUID.randomUUID().toString()); // 返回列表 return ServerResponse.ok().bodyValue(user); } }); } @Bean public RouterFunction<ServerResponse> demoRouterFunction() { return route(GET("/users2/demo"), request -> ok().bodyValue("demo")); } @Bean public RouterFunction<ServerResponse> demo2RouterFunction() { return route(GET("/users2/demo2"), request -> ok().bodyValue("demo")) .filter(new HandlerFilterFunction<ServerResponse, ServerResponse>() { @Override
public Mono<ServerResponse> filter(ServerRequest request, HandlerFunction<ServerResponse> next) { return next.handle(request).doOnSuccess(new Consumer<ServerResponse>() { // 执行成功后回调 @Override public void accept(ServerResponse serverResponse) { logger.info("[accept][执行成功]"); } }); } }); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserRouter.java
2
请完成以下Java代码
public String login (int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { m_AD_Org_ID = AD_Org_ID; m_AD_Role_ID = AD_Role_ID; m_AD_User_ID = AD_User_ID; log.info("AD_Org_ID =" + m_AD_Org_ID); log.info("AD_Role_ID =" + m_AD_Role_ID); log.info("AD_User_ID =" + m_AD_User_ID); return null; } /** * Get Client to be monitored * @return AD_Client_ID client */ public int getAD_Client_ID()
{ return m_AD_Client_ID; } /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer (ExportModelValidator.class.getName()); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\ExportModelValidator.java
1
请完成以下Java代码
public class X_AD_User_OrgAccess extends org.compiere.model.PO implements I_AD_User_OrgAccess, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -1666389449L; /** Standard Constructor */ public X_AD_User_OrgAccess (Properties ctx, int AD_User_OrgAccess_ID, String trxName) { super (ctx, AD_User_OrgAccess_ID, trxName); /** if (AD_User_OrgAccess_ID == 0) { setAD_User_ID (0); setIsReadOnly (false); // N } */ } /** Load Constructor */ public X_AD_User_OrgAccess (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override 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 Schreibgeschützt. @param IsReadOnly Field is read only */ @Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt. @return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_OrgAccess.java
1
请在Spring Boot框架中完成以下Java代码
public class Instructor { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @Column(name="email") private String email; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="instructor_detail_id") private InstructorDetail instructorDetail; public Instructor() { } public Instructor(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public InstructorDetail getInstructorDetail() { return instructorDetail; } public void setInstructorDetail(InstructorDetail instructorDetail) { this.instructorDetail = instructorDetail; } @Override public String toString() { return "Instructor [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", instructorDetail=" + instructorDetail + "]"; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\model\Instructor.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(cancelCompletedDate, cancelInitiator, cancelReason, cancelRequestedDate, cancelRequestId, cancelRequestState); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CancelRequest {\n"); sb.append(" cancelCompletedDate: ").append(toIndentedString(cancelCompletedDate)).append("\n"); sb.append(" cancelInitiator: ").append(toIndentedString(cancelInitiator)).append("\n"); sb.append(" cancelReason: ").append(toIndentedString(cancelReason)).append("\n"); sb.append(" cancelRequestedDate: ").append(toIndentedString(cancelRequestedDate)).append("\n"); sb.append(" cancelRequestId: ").append(toIndentedString(cancelRequestId)).append("\n"); sb.append(" cancelRequestState: ").append(toIndentedString(cancelRequestState)).append("\n"); sb.append("}"); return sb.toString(); }
/** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\CancelRequest.java
2
请完成以下Java代码
public class EntityActionNotificationInfo implements RuleOriginatedNotificationInfo { private EntityId entityId; private String entityName; private ActionType actionType; private CustomerId entityCustomerId; private UUID userId; private String userTitle; private String userEmail; private String userFirstName; private String userLastName; @Override public Map<String, String> getTemplateData() { return mapOf( "entityType", entityId.getEntityType().getNormalName(), "entityId", entityId.toString(), "entityName", entityName, "actionType", actionType.name().toLowerCase(), "userId", userId.toString(), "userTitle", userTitle, "userEmail", userEmail, "userFirstName", userFirstName,
"userLastName", userLastName ); } @Override public CustomerId getAffectedCustomerId() { return entityCustomerId; } @Override public EntityId getStateEntityId() { return entityId; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\EntityActionNotificationInfo.java
1
请在Spring Boot框架中完成以下Java代码
public JWKSource<SecurityContext> jwkSource() { JWKSet jwkSet = new JWKSet(rsaKey()); return (((jwkSelector, securityContext) -> jwkSelector.select(jwkSet))); } @Bean JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) { return new NimbusJwtEncoder(jwkSource); } @Bean JwtDecoder jwtDecoder() throws JOSEException { return NimbusJwtDecoder .withPublicKey(rsaKey().toRSAPublicKey()) .build(); } @Bean public RSAKey rsaKey() { KeyPair keyPair = keyPair(); return new RSAKey .Builder((RSAPublicKey) keyPair.getPublic()) .privateKey((RSAPrivateKey) keyPair.getPrivate()) .keyID(UUID.randomUUID().toString()) .build(); }
@Bean public KeyPair keyPair() { try { var keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } catch (Exception e) { throw new IllegalStateException( "Unable to generate an RSA Key Pair", e); } } }
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\jwt\JwtSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UrlUserService urlUserService; @Autowired SessionRegistry sessionRegistry; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/logout").permitAll() .antMatchers("/images/**").permitAll() .antMatchers("/js/**").permitAll() .antMatchers("/css/**").permitAll() .antMatchers("/fonts/**").permitAll() .antMatchers("/favicon.ico").permitAll() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry) .and() .and() .logout() .invalidateHttpSession(true) .clearAuthentication(true) .and() .httpBasic();
} @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() { @Override public String encode(CharSequence rawPassword) { return MD5Util.encode((String) rawPassword); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return encodedPassword.equals(MD5Util.encode((String) rawPassword)); } }); } @Bean public SessionRegistry getSessionRegistry(){ SessionRegistry sessionRegistry=new SessionRegistryImpl(); return sessionRegistry; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\config\WebSecurityConfig.java
2
请完成以下Java代码
public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public List<String> getCandidateUsers() {
return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateCasePageTaskBeforeContext.java
1
请完成以下Java代码
public DirContext getContext(String principal, String credentials) throws PasswordPolicyException { if (principal.equals(getUserDn())) { return super.getContext(principal, credentials); } this.logger.trace(LogMessage.format("Binding as %s, prior to reconnect as user %s", getUserDn(), principal)); // First bind as manager user before rebinding as the specific principal. LdapContext ctx = (LdapContext) super.getContext(getUserDn(), getPassword()); Control[] rctls = { new PasswordPolicyControl(false) }; try { ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); ctx.reconnect(rctls); } catch (javax.naming.NamingException ex) { PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Failed to bind with %s", ctrl), ex); }
LdapUtils.closeContext(ctx); if (ctrl != null && ctrl.isLocked()) { throw new PasswordPolicyException(ctrl.getErrorStatus()); } throw LdapUtils.convertLdapException(ex); } this.logger.debug(LogMessage.of(() -> "Bound with " + PasswordPolicyControlExtractor.extractControl(ctx))); return ctx; } @Override @SuppressWarnings("unchecked") protected Hashtable getAuthenticatedEnv(String principal, String credentials) { Hashtable<String, Object> env = super.getAuthenticatedEnv(principal, credentials); env.put(LdapContext.CONTROL_FACTORIES, PasswordPolicyControlFactory.class.getName()); return env; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\ppolicy\PasswordPolicyAwareContextSource.java
1
请完成以下Java代码
public int getParameterCount() { return 1; } @Override public String getLabel(int index) { if (index == 0) return Msg.translate(Env.getCtx(), "search"); return null; } @Override public Object getParameterToComponent(int index) { return null; } @Override public String[] getWhereClauses(List<Object> params) { final List<String> whereClauses = new ArrayList<String>(); String search = getText(); if (!(search.equals("") || search.equals("%"))) { // search = search.trim(); // metas: Permutationen ueber alle Search-Kombinationen // z.B. 3 Tokens ergeben 3! Moeglichkeiten als Ergebnis. if (search.contains(" ")) { StringTokenizer st = new StringTokenizer(search, " "); int tokens = st.countTokens(); String input[] = new String[tokens]; Permutation perm = new Permutation(); perm.setMaxIndex(tokens - 1); for (int token = 0; token < tokens; token++) { input[token] = st.nextToken(); } perm.permute(input, tokens - 1); Iterator<String> itr = perm.getResult().iterator(); while (itr.hasNext()) { search = ("%" + itr.next() + "%").replace(" ", "%"); whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)"); params.add(search); log.debug("Search: " + search); } } else
{ if (!search.startsWith("%")) search = "%" + search; // metas-2009_0021_AP1_CR064: end if (!search.endsWith("%")) search += "%"; whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)"); params.add(search); log.debug("Search(2): " + search); } // list.add ("UPPER(bpcs.Search) LIKE ?"); // metas ende } return whereClauses.toArray(new String[whereClauses.size()]); } public IInfoSimple getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPSearchAbstract.java
1
请在Spring Boot框架中完成以下Java代码
static class GraphQlDataAutoConfiguration { @Bean @ConditionalOnMissingBean EncodingCursorStrategy<ScrollPosition> cursorStrategy() { return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64()); } @Bean @SuppressWarnings("unchecked") GraphQlSourceBuilderCustomizer cursorStrategyCustomizer(CursorStrategy<?> cursorStrategy) { if (cursorStrategy.supports(ScrollPosition.class)) { CursorStrategy<ScrollPosition> scrollCursorStrategy = (CursorStrategy<ScrollPosition>) cursorStrategy; ConnectionFieldTypeVisitor connectionFieldTypeVisitor = ConnectionFieldTypeVisitor .create(List.of(new WindowConnectionAdapter(scrollCursorStrategy), new SliceConnectionAdapter(scrollCursorStrategy))); return (builder) -> builder.typeVisitors(List.of(connectionFieldTypeVisitor)); }
return (builder) -> { }; } } static class GraphQlResourcesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("graphql/**/*.graphqls").registerPattern("graphql/**/*.gqls"); } } }
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\GraphQlAutoConfiguration.java
2
请完成以下Java代码
public String convertToJson(EventModel definition) { ObjectMapper objectMapper = objectMapperSupplier.get(); ObjectNode modelNode = objectMapper.createObjectNode(); if (definition.getKey() != null) { modelNode.put("key", definition.getKey()); } if (definition.getName() != null) { modelNode.put("name", definition.getName()); } Collection<EventPayload> payload = definition.getPayload(); if (!payload.isEmpty()) { ArrayNode payloadNode = modelNode.putArray("payload"); for (EventPayload eventPayload : payload) { ObjectNode eventPayloadNode = payloadNode.addObject(); if (eventPayload.getName() != null) { eventPayloadNode.put("name", eventPayload.getName()); } if (eventPayload.getType() != null) { eventPayloadNode.put("type", eventPayload.getType()); } if (eventPayload.isHeader() && !eventPayload.isFullPayload()) {
eventPayloadNode.put("header", true); } if (eventPayload.isCorrelationParameter() && !eventPayload.isFullPayload()) { eventPayloadNode.put("correlationParameter", true); } if (eventPayload.isFullPayload()) { eventPayloadNode.put("isFullPayload", true); } if (eventPayload.isMetaParameter()) { eventPayloadNode.put("metaParameter", true); } } } try { return objectMapper.writeValueAsString(modelNode); } catch (Exception e) { throw new FlowableEventJsonException("Error writing event json", e); } } }
repos\flowable-engine-main\modules\flowable-event-registry-json-converter\src\main\java\org\flowable\eventregistry\json\converter\EventJsonConverter.java
1
请完成以下Java代码
public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public String toString() { return "Comment{" + "author='" + author + '\'' + ", message='" + message + '\'' + ", timestamp='" + timestamp + '\'' + '}'; } }
repos\spring-boot-master\webflux-thymeleaf-serversentevent\src\main\java\com\mkyong\reactive\model\Comment.java
1
请完成以下Java代码
public EntityInfo findTenantProfileInfoById(TenantId tenantId, UUID tenantProfileId) { return tenantProfileRepository.findTenantProfileInfoById(tenantProfileId); } @Override public PageData<TenantProfile> findTenantProfiles(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData( tenantProfileRepository.findTenantProfiles( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<EntityInfo> findTenantProfileInfos(TenantId tenantId, PageLink pageLink) { return DaoUtil.pageToPageData( tenantProfileRepository.findTenantProfileInfos( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public TenantProfile findDefaultTenantProfile(TenantId tenantId) { return DaoUtil.getData(tenantProfileRepository.findByDefaultTrue()); } @Override public EntityInfo findDefaultTenantProfileInfo(TenantId tenantId) { return tenantProfileRepository.findDefaultTenantProfileInfo(); }
@Override public List<TenantProfile> findTenantProfilesByIds(TenantId tenantId, UUID[] ids) { return DaoUtil.convertDataList(tenantProfileRepository.findByIdIn(Arrays.asList(ids))); } @Override public List<TenantProfileFields> findNextBatch(UUID id, int batchSize) { return tenantProfileRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.TENANT_PROFILE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\tenant\JpaTenantProfileDao.java
1
请完成以下Java代码
public static SparkplugMessageType parseMessageType(String type) throws ThingsboardException { for (SparkplugMessageType messageType : SparkplugMessageType.values()) { if (messageType.name().equals(type)) { return messageType; } } throw new ThingsboardException("Invalid message type: " + type, ThingsboardErrorCode.INVALID_ARGUMENTS); } public static String messageName(SparkplugMessageType type) { return STATE.equals(type) ? "sparkplugConnectionState" : type.name(); } public boolean isState() { return this.equals(STATE); } public boolean isDeath() { return this.equals(DDEATH) || this.equals(NDEATH); } public boolean isCommand() { return this.equals(DCMD) || this.equals(NCMD); } public boolean isData() { return this.equals(DDATA) || this.equals(NDATA); }
public boolean isBirth() { return this.equals(DBIRTH) || this.equals(NBIRTH); } public boolean isRecord() { return this.equals(DRECORD) || this.equals(NRECORD); } public boolean isSubscribe() { return isCommand() || isData() || isRecord(); } public boolean isNode() { return this.equals(NBIRTH) || this.equals(NCMD) || this.equals(NDATA) ||this.equals(NDEATH) || this.equals(NRECORD); } public boolean isDevice() { return this.equals(DBIRTH) || this.equals(DCMD) || this.equals(DDATA) ||this.equals(DDEATH) || this.equals(DRECORD); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugMessageType.java
1
请完成以下Java代码
public Set<Integer> getSelectionIds(final PInstanceId selectionId) { final Set<Integer> selection = selectionId2selection.get(selectionId); return selection != null ? selection : ImmutableSet.of(); } public void dumpSelections() { StringBuilder sb = new StringBuilder(); sb.append("=====================[ SELECTIONS ]============================================================"); for (final PInstanceId selectionId : selectionId2selection.keySet()) { sb.append("\n\t").append(selectionId).append(": ").append(selectionId2selection.get(selectionId)); } sb.append("\n"); System.out.println(sb);
} /** * @return new database restore point. */ public POJOLookupMapRestorePoint createRestorePoint() { return new POJOLookupMapRestorePoint(this); } @Override public void addImportInterceptor(String importTableName, IImportInterceptor listener) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOLookupMap.java
1
请完成以下Java代码
public class Main { public static void main(String... args) throws Exception { Server server = Server.builder() .endpoints(URI.create("http://localhost:8888")) .addService(BookManagementService.builder() .addCreateBookOperation(new CreateBookOperationImpl()) .addGetBookOperation(new GetBookOperationImpl()) .addListBooksOperation(new ListBooksOperationImpl()) .addRecommendBookOperation(new RecommendBookOperationImpl()) .build()) .build(); System.out.println("Starting server..."); server.start();
try { Thread.currentThread() .join(); } catch (InterruptedException e) { System.out.println("Stopping server..."); try { server.shutdown() .get(); } catch (Exception ex) { throw new RuntimeException(ex); } } } }
repos\tutorials-master\gradle-modules\gradle-customization\gradle-smithy\src\main\java\com\baeldung\smithy\books\server\Main.java
1
请完成以下Java代码
public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } /** Set Produktionsauftrag. @param PP_Order_ID Produktionsauftrag */ @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } /** Get Produktionsauftrag. @return Produktionsauftrag */ @Override public int getPP_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Menge.
@param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alternative.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class BaseChangeStateComponent extends BaseComponent { /** 是否终止 */ protected boolean isStop = false; /** 订单目标状态 */ protected OrderStateEnum targetOrderState; @Autowired private OrderDAO orderDAO; /** 状态改变前的前置处理 */ @Override protected void preHandle(OrderProcessContext orderProcessContext) { } /** 状态改变后的后置处理 */ @Override protected void afterHandle(OrderProcessContext orderProcessContext) { } /** * 将指定订单的状态更新成指定值 * @param orderProcessContext 订单受理上下文 * @param targetOrderState 订单目标状态 */ private void changeState(OrderProcessContext orderProcessContext, OrderStateEnum targetOrderState) { // 目标状态为空 checkParam(targetOrderState); // 获取订单ID String orderId = orderProcessContext.getOrderProcessReq().getOrderId(); // 更新订单状态 updateOrderState(orderId, targetOrderState); } /** * 更新订单的状态 * @param orderId 订单ID * @param targetOrderState 订单状态 */ private void updateOrderState(String orderId, OrderStateEnum targetOrderState) { // 构造OrderStateTimeEntity OrderStateTimeEntity orderStateTimeEntity = buildOrderStateTimeEntity(orderId, targetOrderState); // 删除该订单的该条状态 orderDAO.deleteOrderStateTime(orderStateTimeEntity); // 插入该订单的该条状态 orderDAO.insertOrderStateTime(orderStateTimeEntity); // 更新order表中的订单状态 OrdersEntity ordersEntity = new OrdersEntity(); ordersEntity.setId(orderId); ordersEntity.setOrderStateEnum(targetOrderState); orderDAO.updateOrder(ordersEntity); } /** * 构造用于更新订单状态的buildOrderStateTimeEntity * @param orderId 订单ID * @param targetOrderState 订单状态 * @return OrderStateTimeEntity */ private OrderStateTimeEntity buildOrderStateTimeEntity(String orderId, OrderStateEnum targetOrderState) {
OrderStateTimeEntity orderStateTimeEntity = new OrderStateTimeEntity(); orderStateTimeEntity.setOrderId(orderId); orderStateTimeEntity.setOrderStateEnum(targetOrderState); orderStateTimeEntity.setTime(new Timestamp(System.currentTimeMillis())); return orderStateTimeEntity; } private void checkParam(OrderStateEnum targetOrderState) { if (targetOrderState == null) { throw new CommonSysException(ExpCodeEnum.TARGETSTATE_NULL); } } @Override public void handle(OrderProcessContext orderProcessContext) { // 设置目标状态 setTargetOrderState(); // 前置处理 this.preHandle(orderProcessContext); if (this.isStop) { return; } // 改变状态 this.changeState(orderProcessContext, this.targetOrderState); if (this.isStop) { return; } // 后置处理 this.afterHandle(orderProcessContext); } public abstract void setTargetOrderState(); }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\changestate\BaseChangeStateComponent.java
2
请完成以下Java代码
public String getName() { return innerPlanItemInstance.getName(); } @Override public String getCaseInstanceId() { return innerPlanItemInstance.getCaseInstanceId(); } @Override public String getCaseDefinitionId() { return innerPlanItemInstance.getCaseDefinitionId(); } @Override public String getElementId() { return innerPlanItemInstance.getElementId(); } @Override public String getPlanItemDefinitionId() { return innerPlanItemInstance.getPlanItemDefinitionId(); } @Override public String getStageInstanceId() { return innerPlanItemInstance.getStageInstanceId();
} @Override public String getState() { return innerPlanItemInstance.getState(); } @Override public String toString() { return "IntentEventListenerInstanceImpl{" + "id='" + getId() + '\'' + ", name='" + getName() + '\'' + ", caseInstanceId='" + getCaseInstanceId() + '\'' + ", caseDefinitionId='" + getCaseDefinitionId() + '\'' + ", elementId='" + getElementId() + '\'' + ", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' + ", stageInstanceId='" + getStageInstanceId() + '\'' + '}'; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceImpl.java
1
请完成以下Java代码
public class CloudFoundryRouteServiceRoutePredicateFactory extends AbstractRoutePredicateFactory<Object> { /** * Forwarded URL header name. */ public static final String X_CF_FORWARDED_URL = "X-CF-Forwarded-Url"; /** * Proxy signature header name. */ public static final String X_CF_PROXY_SIGNATURE = "X-CF-Proxy-Signature"; /** * Proxy metadata header name. */ public static final String X_CF_PROXY_METADATA = "X-CF-Proxy-Metadata"; private final HeaderRoutePredicateFactory factory = new HeaderRoutePredicateFactory(); public CloudFoundryRouteServiceRoutePredicateFactory() {
super(Object.class); } @Override public Predicate<ServerWebExchange> apply(Object unused) { return headerPredicate(X_CF_FORWARDED_URL).and(headerPredicate(X_CF_PROXY_SIGNATURE)) .and(headerPredicate(X_CF_PROXY_METADATA)); } private Predicate<ServerWebExchange> headerPredicate(String header) { HeaderRoutePredicateFactory.Config config = factory.newConfig(); config.setHeader(header); config.setRegexp(".*"); return factory.apply(config); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\CloudFoundryRouteServiceRoutePredicateFactory.java
1
请完成以下Java代码
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID) { delegate.setC_BPartner_Location_ID(C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_Value_ID() { return delegate.getC_BPartner_Location_Value_ID(); } @Override public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID); } @Override public int getAD_User_ID() { return delegate.getAD_User_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) { delegate.setAD_User_ID(AD_User_ID); } @Override public String getBPartnerAddress() { return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(String address) { delegate.setBPartnerAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order from) {
setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
public boolean isDisplayed() { return displayed; } public void setDisplayed(final boolean displayed) { this.displayed = displayed; } @Override public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo()
{ return handlingUnitsInfo; } public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } @Override public I_PP_Order getPP_Order() { return ppOrder; } public void setPP_Order(I_PP_Order ppOrder) { this.ppOrder = ppOrder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLine.java
1
请完成以下Java代码
public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() {
return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationAttribute.java
1
请在Spring Boot框架中完成以下Java代码
public class MobileConfigRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, Optional<MobileConfig>> cache = CCache.<Integer, Optional<MobileConfig>>builder() .tableName(I_MobileConfiguration.Table_Name) .initialCapacity(1) .build(); @NonNull public Optional<MobileConfig> getConfig() { return cache.getOrLoad(0, this::retrieveConfig); } @NonNull private Optional<MobileConfig> retrieveConfig() { return retrieveRecord().map(MobileConfigRepository::ofRecord); } @NonNull private Optional<I_MobileConfiguration> retrieveRecord() { return queryBL.createQueryBuilder(I_MobileConfiguration.class) .addOnlyActiveRecordsFilter() .create() .firstOnlyOptional(I_MobileConfiguration.class); } public void save(@NonNull final MobileConfig mobileConfig)
{ final I_MobileConfiguration record = retrieveRecord().orElseGet(() -> InterfaceWrapperHelper.newInstance(I_MobileConfiguration.class)); updateRecord(record, mobileConfig); InterfaceWrapperHelper.saveRecord(record); } @NonNull private static MobileConfig ofRecord(@NonNull final I_MobileConfiguration mobileConfiguration) { return MobileConfig.builder() .defaultAuthMethod(MobileAuthMethod.ofCode(mobileConfiguration.getDefaultAuthenticationMethod())) .build(); } private static void updateRecord(@NonNull final I_MobileConfiguration record, @NonNull final MobileConfig from) { record.setDefaultAuthenticationMethod(from.getDefaultAuthMethod().getCode()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\MobileConfigRepository.java
2
请完成以下Java代码
static double inner_product(SparseVector vec1, SparseVector vec2) { Iterator<Map.Entry<Integer, Double>> it; SparseVector other; if (vec1.size() < vec2.size()) { it = vec1.entrySet().iterator(); other = vec2; } else { it = vec2.entrySet().iterator(); other = vec1; } double prod = 0; while (it.hasNext()) { Map.Entry<Integer, Double> entry = it.next(); prod += entry.getValue() * other.get(entry.getKey()); } return prod; } /** * Calculate the cosine value between vectors. */ double cosine(SparseVector vec1, SparseVector vec2) { double norm1 = vec1.norm(); double norm2 = vec2.norm(); double result = 0.0f; if (norm1 == 0 && norm2 == 0) { return result; } else { double prod = inner_product(vec1, vec2);
result = prod / (norm1 * norm2); return Double.isNaN(result) ? 0.0f : result; } } // /** // * Calculate the Jaccard coefficient value between vectors. // */ // double jaccard(const Vector &vec1, const Vector &vec2) //{ // double norm1 = vec1.norm(); // double norm2 = vec2.norm(); // double prod = inner_product(vec1, vec2); // double denom = norm1 + norm2 - prod; // double result = 0.0; // if (!denom) // { // return result; // } // else // { // result = prod / denom; // return isnan(result) ? 0.0 : result; // } //} }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\SparseVector.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getTime() { return getStartTime(); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return ( "HistoricActivityInstanceEntity[id=" + id + ", activityId=" + activityId + ", activityName=" + activityName + "]" ); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntityImpl.java
1
请完成以下Java代码
public List<ProcessDefinitionDto> getCalledProcessDefinitions(@Context UriInfo uriInfo) { ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(uriInfo.getQueryParameters()); return queryCalledProcessDefinitions(queryParameter); } @POST @Path("/called-process-definitions") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public List<ProcessDefinitionDto> queryCalledProcessDefinitions(ProcessDefinitionQueryDto queryParameter) { return getCommandExecutor().executeCommand(new QueryCalledProcessDefinitionsCmd(queryParameter)); } private void injectEngineConfig(ProcessDefinitionQueryDto parameter) { ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) getProcessEngine()).getProcessEngineConfiguration(); if (processEngineConfiguration.getHistoryLevel().equals(HistoryLevel.HISTORY_LEVEL_NONE)) { parameter.setHistoryEnabled(false); } parameter.initQueryVariableValues(processEngineConfiguration.getVariableSerializers(), processEngineConfiguration.getDatabaseType()); } protected void configureExecutionQuery(ProcessDefinitionQueryDto query) { configureAuthorizationCheck(query); configureTenantCheck(query);
addPermissionCheck(query, PROCESS_INSTANCE, "EXEC2.PROC_INST_ID_", READ); addPermissionCheck(query, PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE); } protected class QueryCalledProcessDefinitionsCmd implements Command<List<ProcessDefinitionDto>> { protected ProcessDefinitionQueryDto queryParameter; public QueryCalledProcessDefinitionsCmd(ProcessDefinitionQueryDto queryParameter) { this.queryParameter = queryParameter; } @Override public List<ProcessDefinitionDto> execute(CommandContext commandContext) { queryParameter.setParentProcessDefinitionId(id); injectEngineConfig(queryParameter); configureExecutionQuery(queryParameter); queryParameter.disableMaxResultsLimit(); return getQueryService().executeQuery("selectCalledProcessDefinitions", queryParameter); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\sub\resources\ProcessDefinitionResource.java
1
请完成以下Java代码
public void patchRow(final IEditableView.RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { throw new UnsupportedOperationException("ProductionSimulationRows are read-only!"); } @Override public Map<DocumentId, ProductionSimulationRow> getDocumentId2TopLevelRows() { return rowIds.stream() .map(rowsById::get) .collect(GuavaCollectors.toImmutableMapByKey(ProductionSimulationRow::getId)); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{ return DocumentIdsSelection.EMPTY; } @Override public void invalidateAll() { } @NonNull public ImmutableList<DocumentId> getRowIds() { return rowIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRows.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getMistakeCount() { return mistakeCount; } public void setMistakeCount(Integer mistakeCount) { this.mistakeCount = mistakeCount; } public Integer getUnhandleMistakeCount() { return unhandleMistakeCount; } public void setUnhandleMistakeCount(Integer unhandleMistakeCount) { this.unhandleMistakeCount = unhandleMistakeCount; } public Integer getTradeCount() { return tradeCount; } public void setTradeCount(Integer tradeCount) { this.tradeCount = tradeCount; } public Integer getBankTradeCount() { return bankTradeCount; } public void setBankTradeCount(Integer bankTradeCount) { this.bankTradeCount = bankTradeCount; } public BigDecimal getTradeAmount() { return tradeAmount; } public void setTradeAmount(BigDecimal tradeAmount) { this.tradeAmount = tradeAmount; } public BigDecimal getBankTradeAmount() { return bankTradeAmount; } public void setBankTradeAmount(BigDecimal bankTradeAmount) { this.bankTradeAmount = bankTradeAmount; } public BigDecimal getRefundAmount() { return refundAmount; } public void setRefundAmount(BigDecimal refundAmount) { this.refundAmount = refundAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getOrgCheckFilePath() { return orgCheckFilePath; }
public void setOrgCheckFilePath(String orgCheckFilePath) { this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim(); } public String getReleaseCheckFilePath() { return releaseCheckFilePath; } public void setReleaseCheckFilePath(String releaseCheckFilePath) { this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim(); } public String getReleaseStatus() { return releaseStatus; } public void setReleaseStatus(String releaseStatus) { this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim(); } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public String getCheckFailMsg() { return checkFailMsg; } public void setCheckFailMsg(String checkFailMsg) { this.checkFailMsg = checkFailMsg; } public String getBankErrMsg() { return bankErrMsg; } public void setBankErrMsg(String bankErrMsg) { this.bankErrMsg = bankErrMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
2
请完成以下Java代码
public static DocTimingType valueOf(final int timing) { final DocTimingType value = timingInt2type.get(timing); if (value == null) { throw new IllegalArgumentException("No enum constant found for timing=" + timing + " in " + timingInt2type); } return value; } private static final Map<Integer, DocTimingType> timingInt2type = Stream.of(values()).collect(GuavaCollectors.toImmutableMapByKey(DocTimingType::toInt)); public static DocTimingType forAction(final String docAction, final BeforeAfterType beforeAfterType) { Check.assumeNotEmpty(docAction, "docAction not null"); Check.assumeNotNull(beforeAfterType, "beforeAfterType not null"); // NOTE: no need to use an indexed map because this method is not used very often for (final DocTimingType timing : values()) { if (timing.matches(docAction, beforeAfterType)) { return timing;
} } throw new IllegalArgumentException("Unknown DocAction: " + docAction + ", " + beforeAfterType); } public boolean isVoid() { return this == BEFORE_VOID || this == AFTER_VOID; } public boolean isReverse() { return this == BEFORE_REVERSECORRECT || this == AFTER_REVERSECORRECT || this == BEFORE_REVERSEACCRUAL || this == AFTER_REVERSEACCRUAL; } public boolean isReactivate() { return this == BEFORE_REACTIVATE || this == AFTER_REACTIVATE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\DocTimingType.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Long id; @Column private String name; @OneToOne(fetch = FetchType.LAZY, mappedBy = "user") private Address address; public User() { } public User(String name) { this.name = name; } 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 Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\spring-data-rest-querydsl\src\main\java\com\baeldung\entity\User.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 uomSymbol property. * * @return * possible object is * {@link String } * */ public String getUOMSymbol() { return uomSymbol; } /** * Sets the value of the uomSymbol property. * * @param value * allowed object is * {@link String } * */ public void setUOMSymbol(String value) { this.uomSymbol = value;
} /** * Gets the value of the x12DE355 property. * * @return * possible object is * {@link String } * */ public String getX12DE355() { return x12DE355; } /** * Sets the value of the x12DE355 property. * * @param value * allowed object is * {@link String } * */ public void setX12DE355(String value) { this.x12DE355 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCUOMType.java
2
请在Spring Boot框架中完成以下Java代码
public void displayBookById() { Book book = bookRepositoryFetchModeJoin.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBookByIdViaJoinFetch() { Book book = bookRepositoryJoinFetch.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBookByIdViaEntityGraph() { Book book = bookRepositoryEntityGraph.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBooksCausingNPlus1() { List<Book> books = bookRepositoryFetchModeJoin.findAll(); // N+1 displayBooks(books); } public void displayBooksByAgeGt45CausingNPlus1() { List<Book> books = bookRepositoryFetchModeJoin.findAll(isPriceGt35()); // N+1 displayBooks(books); } public void displayBooksViaEntityGraph() { List<Book> books = bookRepositoryEntityGraph.findAll(); // LEFT JOIN displayBooks(books); } public void displayBooksByAgeGt45ViaEntityGraph() {
List<Book> books = bookRepositoryEntityGraph.findAll(isPriceGt35()); // LEFT JOIN displayBooks(books); } public void displayBooksViaJoinFetch() { List<Book> books = bookRepositoryJoinFetch.findAll(); // LEFT JOIN displayBooks(books); } private void displayBook(Book book) { System.out.println(book); System.out.println(book.getAuthor()); System.out.println(book.getAuthor().getPublisher() + "\n"); } private void displayBooks(List<Book> books) { for (Book book : books) { System.out.println(book); System.out.println(book.getAuthor()); System.out.println(book.getAuthor().getPublisher() + "\n"); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public class Product { @Id private Long id; private String name; private double price; public Product() { } public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; } 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 double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\contextvsunit\entity\Product.java
2
请完成以下Java代码
public Resource concatenatePDFs(@NonNull final ImmutableList<PdfDataProvider> pdfDataToConcatenate) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); concatenatePDFsToOutputStream(out, pdfDataToConcatenate); return new ByteArrayResource(out.toByteArray()); } private void concatenatePDFsToOutputStream( @NonNull final OutputStream outputStream, @NonNull final ImmutableList<PdfDataProvider> pdfDataToConcatenate) { final Document document = new Document(); try { final PdfCopy copyDestination = new PdfCopy(document, outputStream); document.open(); for (final PdfDataProvider pdfData : pdfDataToConcatenate) { appendPdfPages(copyDestination, pdfData); } document.close(); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e); } } private static void appendPdfPages(@NonNull final PdfCopy copyDestination, @NonNull final PdfDataProvider pdfData) throws IOException, BadPdfFormatException { final Resource data = pdfData.getPdfData(); final PdfReader pdfReader = new PdfReader(data.getInputStream()); for (int page = 0; page < pdfReader.getNumberOfPages(); )
{ copyDestination.addPage(copyDestination.getImportedPage(pdfReader, ++page)); } copyDestination.freeReader(pdfReader); pdfReader.close(); } @Value public static class PdfDataProvider { public static PdfDataProvider forData(@NonNull final Resource pdfData) { return new PdfDataProvider(pdfData); } Resource pdfData; private PdfDataProvider(@NonNull final Resource pdfData) { this.pdfData = pdfData; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ExecuteReportStrategyUtil.java
1
请完成以下Java代码
protected void createTenantSchema(String tenantId) { logger.info("creating/validating database schema for tenant {}", tenantId); tenantInfoHolder.setCurrentTenantId(tenantId); getCommandExecutor().execute(getSchemaCommandConfig(), new ExecuteSchemaOperationCommand(databaseSchemaUpdate)); tenantInfoHolder.clearCurrentTenantId(); } protected void createTenantAsyncJobExecutor(String tenantId) { ((TenantAwareAsyncExecutor) asyncExecutor).addTenantAsyncExecutor(tenantId, isAsyncExecutorActivate() && booted); } @Override public CommandInterceptor createTransactionInterceptor() { return null; } @Override protected void postProcessEngineInitialisation() { // empty here. will be done in registerTenant } @Override public Runnable getProcessEngineCloseRunnable() { return new Runnable() { @Override public void run() { for (String tenantId : tenantInfoHolder.getAllTenants()) {
tenantInfoHolder.setCurrentTenantId(tenantId); if (asyncExecutor != null) { commandExecutor.execute(new ClearProcessInstanceLockTimesCmd(asyncExecutor.getLockOwner())); } commandExecutor.execute(getProcessEngineCloseCommand()); tenantInfoHolder.clearCurrentTenantId(); } } }; } public Command<Void> getProcessEngineCloseCommand() { return new Command<>() { @Override public Void execute(CommandContext commandContext) { CommandContextUtil.getProcessEngineConfiguration(commandContext).getCommandExecutor().execute(new SchemaOperationProcessEngineClose()); return null; } }; } public TenantInfoHolder getTenantInfoHolder() { return tenantInfoHolder; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\multitenant\MultiSchemaMultiTenantProcessEngineConfiguration.java
1
请完成以下Java代码
public static DemandDetail forSupplyRequiredDescriptorOrNull(@Nullable final SupplyRequiredDescriptor supplyRequiredDescriptor) { return supplyRequiredDescriptor != null ? forSupplyRequiredDescriptor(supplyRequiredDescriptor) : null; } @NonNull public static DemandDetail forSupplyRequiredDescriptor(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { return DemandDetail.builder() .demandCandidateId(toUnspecifiedIfZero(supplyRequiredDescriptor.getDemandCandidateId())) .forecastId(toUnspecifiedIfZero(supplyRequiredDescriptor.getForecastId())) .forecastLineId(toUnspecifiedIfZero(supplyRequiredDescriptor.getForecastLineId())) .orderId(toUnspecifiedIfZero(supplyRequiredDescriptor.getOrderId())) .orderLineId(toUnspecifiedIfZero(supplyRequiredDescriptor.getOrderLineId())) .shipmentScheduleId(toUnspecifiedIfZero(supplyRequiredDescriptor.getShipmentScheduleId())) .subscriptionProgressId(toUnspecifiedIfZero(supplyRequiredDescriptor.getSubscriptionProgressId())) .qty(supplyRequiredDescriptor.getQtyToSupplyBD()) .build(); } public static DemandDetail forShipmentScheduleIdAndOrderLineId( final int shipmentScheduleId, final int orderLineId, final int orderId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .shipmentScheduleId(shipmentScheduleId) .orderLineId(orderLineId) .orderId(orderId) .qty(qty).build(); } @NonNull public static DemandDetail forShipmentLineId( final int inOutLineId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .inOutLineId(inOutLineId) .qty(qty) .build(); } public static DemandDetail forForecastLineId( final int forecastLineId, final int forecastId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .forecastLineId(forecastLineId) .forecastId(forecastId) .qty(qty).build(); } int forecastId; int forecastLineId;
int shipmentScheduleId; int orderId; int orderLineId; int subscriptionProgressId; int inOutLineId; BigDecimal qty; /** * Used when a new supply candidate is created, to link it to it's respective demand candidate; * When a demand detail is loaded from DB, this field is always <= 0. */ int demandCandidateId; /** * dev-note: it's about an {@link de.metas.material.event.MaterialEvent} traceId, currently used when posting SupplyRequiredEvents */ @With @Nullable String traceId; @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.SHIPMENT; } public static DemandDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail) { return businessCaseDetail instanceof DemandDetail ? cast(businessCaseDetail) : null; } public static DemandDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (DemandDetail)businessCaseDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DemandDetail.java
1
请完成以下Java代码
protected void initializeCommandWithVariables(CaseExecutionCommandBuilder commandBuilder, Map<String, TriggerVariableValueDto> variables, String transition) { for(String variableName : variables.keySet()) { try { TriggerVariableValueDto variableValue = variables.get(variableName); if (variableValue.isLocal()) { commandBuilder.setVariableLocal(variableName, variableValue.toTypedValue(engine, objectMapper)); } else { commandBuilder.setVariable(variableName, variableValue.toTypedValue(engine, objectMapper)); } } catch (RestException e) { String errorMessage = String.format("Cannot %s case instance %s due to invalid variable %s: %s", transition, caseInstanceId, variableName, e.getMessage()); throw new RestException(e.getStatus(), e, errorMessage); } } }
protected void initializeCommandWithDeletions(CaseExecutionCommandBuilder commandBuilder, List<VariableNameDto> deletions, String transition) { for (VariableNameDto variableName : deletions) { if (variableName.isLocal()) { commandBuilder.removeVariableLocal(variableName.getName()); } else { commandBuilder.removeVariable(variableName.getName()); } } } public VariableResource getVariablesResource() { return new CaseExecutionVariablesResource(engine, caseInstanceId, objectMapper); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\CaseInstanceResourceImpl.java
1
请完成以下Java代码
public Decision newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); questionChild = sequenceBuilder.element(Question.class) .build(); allowedAnswersChild = sequenceBuilder.element(AllowedAnswers.class) .build(); variableChild = sequenceBuilder.element(Variable.class) .build(); informationRequirementCollection = sequenceBuilder.elementCollection(InformationRequirement.class) .build(); knowledgeRequirementCollection = sequenceBuilder.elementCollection(KnowledgeRequirement.class) .build(); authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class) .build(); supportedObjectiveChildElementCollection = sequenceBuilder.elementCollection(SupportedObjectiveReference.class) .build(); impactedPerformanceIndicatorRefCollection = sequenceBuilder.elementCollection(ImpactedPerformanceIndicatorReference.class) .uriElementReferenceCollection(PerformanceIndicator.class) .build();
decisionMakerRefCollection = sequenceBuilder.elementCollection(DecisionMakerReference.class) .uriElementReferenceCollection(OrganizationUnit.class) .build(); decisionOwnerRefCollection = sequenceBuilder.elementCollection(DecisionOwnerReference.class) .uriElementReferenceCollection(OrganizationUnit.class) .build(); usingProcessCollection = sequenceBuilder.elementCollection(UsingProcessReference.class) .build(); usingTaskCollection = sequenceBuilder.elementCollection(UsingTaskReference.class) .build(); expressionChild = sequenceBuilder.element(Expression.class) .build(); // camunda extensions camundaHistoryTimeToLiveAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE) .namespace(CAMUNDA_NS) .build(); camundaVersionTag = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VERSION_TAG) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionImpl.java
1
请完成以下Java代码
public class POSPaymentExternalId { @NonNull private final String value; private POSPaymentExternalId(@NonNull final String value) { final String valueNorm = normalizeValue(value); if (valueNorm == null) { throw new AdempiereException("Invalid external ID: `" + value + "`"); } this.value = valueNorm; } @Nullable private static String normalizeValue(@Nullable final String value) { return StringUtils.trimBlankToNull(value); }
@JsonCreator public static POSPaymentExternalId ofString(@NonNull final String value) { return new POSPaymentExternalId(value); } @Override @Deprecated public String toString() {return value;} @JsonValue public String getAsString() {return value;} public static boolean equals(@Nullable final POSPaymentExternalId id1, @Nullable final POSPaymentExternalId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentExternalId.java
1
请完成以下Java代码
public class CompleteCaseInstanceOperation extends AbstractDeleteCaseInstanceOperation { public CompleteCaseInstanceOperation(CommandContext commandContext, String caseInstanceId) { super(commandContext, caseInstanceId); } public CompleteCaseInstanceOperation(CommandContext commandContext, CaseInstanceEntity caseInstanceEntity) { super(commandContext, caseInstanceEntity); } @Override public String getNewState() { return CaseInstanceState.COMPLETED; } @Override public void changeStateForChildPlanItemInstance(PlanItemInstanceEntity planItemInstanceEntity) { // terminate all child plan items not yet in an end state of the case itself (same way as with a stage for instance) // if they would be completed, the history will contain completed plan item instances although they never "truly" completed // specially important for cases supporting reactivation // if the plan item implements the specific behavior interface for ending, invoke it, otherwise use the default one which is terminate, regardless, // if the case got completed or terminated Object behavior = planItemInstanceEntity.getPlanItem().getBehavior(); if (behavior instanceof OnParentEndDependantActivityBehavior) { // if the specific behavior is implemented, invoke it ((OnParentEndDependantActivityBehavior) behavior).onParentEnd(commandContext, planItemInstanceEntity, PlanItemTransition.COMPLETE, null); } else { // use default behavior, if the interface is not implemented CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(planItemInstanceEntity, null, null); } } /** * Overwritten in order to send a case end / completion event through the case engine dispatcher. */ @Override protected void invokePostLifecycleListeners() { super.invokePostLifecycleListeners();
CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher() .dispatchEvent(FlowableCmmnEventBuilder.createCaseEndedEvent(caseInstanceEntity, CaseInstanceState.COMPLETED), EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } @Override public String getDeleteReason() { return "cmmn-state-transition-complete-case"; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("[Complete case instance] case instance "); strb.append(caseInstanceEntity != null ? caseInstanceEntity.getId() : caseInstanceEntityId); return strb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\CompleteCaseInstanceOperation.java
1
请完成以下Java代码
public final CurrentCost getCurrentCost(final CostSegmentAndElement costSegmentAndElement) { return currentCostsRepo.getOrCreate(costSegmentAndElement); } public final void saveCurrentCost(final CurrentCost currentCost) { currentCostsRepo.save(currentCost); } public CostAmount convertToAcctSchemaCurrency( final CostAmount amt, final CostDetailCreateRequest request) { final AcctSchemaId acctSchemaId = request.getAcctSchemaId(); return convertToAcctSchemaCurrency( amt, () -> getCurrencyConversionContext(request), acctSchemaId); } public CostAmount convertToAcctSchemaCurrency( @NonNull final CostAmount amt, @NonNull final Supplier<CurrencyConversionContext> conversionCtxSupplier, @NonNull final AcctSchemaId acctSchemaId) { final AcctSchema acctSchema = getAcctSchemaById(acctSchemaId); final CurrencyId acctCurrencyId = acctSchema.getCurrencyId(); if (CurrencyId.equals(amt.getCurrencyId(), acctCurrencyId)) { return amt; } final CurrencyConversionContext conversionCtx = conversionCtxSupplier.get() .withPrecision(acctSchema.getCosting().getCostingPrecision());
final CurrencyConversionResult result = convert( conversionCtx, amt.toMoney(), acctCurrencyId); return CostAmount.of(result.getAmount(), acctCurrencyId, result.getSourceAmount(), result.getSourceCurrencyId()); } @NonNull public CurrencyConversionResult convert( final CurrencyConversionContext conversionCtx, final Money price, final CurrencyId acctCurrencyId) { return currencyBL.convert(conversionCtx, price, acctCurrencyId); } private CurrencyConversionContext getCurrencyConversionContext(final CostDetailCreateRequest request) { final CurrencyConversionContext currencyConversionContext = request.getCurrencyConversionContext(); return CoalesceUtil.coalesceSuppliersNotNull( () -> currencyConversionContext, () -> currencyBL.createCurrencyConversionContext( request.getDate(), (CurrencyConversionTypeId)null, request.getClientId(), request.getOrgId())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostingMethodHandlerUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class GetUserResponse { @XmlElement(name = "return") protected User _return; /** * 获取return属性的值。 * * @return * possible object is * {@link User } * */ public User getReturn() { return _return;
} /** * 设置return属性的值。 * * @param value * allowed object is * {@link User } * */ public void setReturn(User value) { this._return = value; } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\GetUserResponse.java
2
请完成以下Java代码
public static String convert(String sentence) { assert sentence != null; char[] result = new char[sentence.length()]; convert(sentence, result); return new String(result); } public static void convert(String charArray, char[] result) { for (int i = 0; i < charArray.length(); i++) { result[i] = CONVERT[charArray.charAt(i)]; } } /** * 正规化一些字符(原地正规化) * @param charArray 字符 */ public static void normalization(char[] charArray) { assert charArray != null; for (int i = 0; i < charArray.length; i++) { charArray[i] = CONVERT[charArray[i]]; } }
public static void normalize(Sentence sentence) { for (IWord word : sentence) { if (word instanceof CompoundWord) { for (Word w : ((CompoundWord) word).innerList) { w.value = convert(w.value); } } else word.setValue(word.getValue()); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\other\CharTable.java
1
请在Spring Boot框架中完成以下Java代码
public class IdmEngineConfigurator extends AbstractEngineConfigurator<IdmEngine> { protected IdmEngineConfiguration idmEngineConfiguration; @Override public int getPriority() { return EngineConfigurationConstants.PRIORITY_ENGINE_IDM; } @Override protected List<EngineDeployer> getCustomDeployers() { return null; } @Override protected String getMybatisCfgPath() { return IdmEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE; } @Override public void configure(AbstractEngineConfiguration engineConfiguration) { if (idmEngineConfiguration == null) { idmEngineConfiguration = new StandaloneIdmEngineConfiguration(); } initialiseCommonProperties(engineConfiguration, idmEngineConfiguration); initEngine(); initServiceConfigurations(engineConfiguration, idmEngineConfiguration); } @Override protected IdmEngine buildEngine() { return idmEngineConfiguration.buildEngine(); } @Override protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER; } @Override protected List<Class<? extends Entity>> getEntityDeletionOrder() { return EntityDependencyOrder.DELETE_ORDER; } public IdmEngineConfiguration getIdmEngineConfiguration() { return idmEngineConfiguration; } public IdmEngineConfigurator setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) { this.idmEngineConfiguration = idmEngineConfiguration; return this; } }
repos\flowable-engine-main\modules\flowable-idm-engine-configurator\src\main\java\org\flowable\idm\engine\configurator\IdmEngineConfigurator.java
2
请在Spring Boot框架中完成以下Java代码
public class DmnManagementServiceImpl extends CommonEngineServiceImpl<DmnEngineConfiguration> implements DmnManagementService { public DmnManagementServiceImpl(DmnEngineConfiguration dmnEngineConfiguration) { super(dmnEngineConfiguration); } @Override public Map<String, Long> getTableCount() { return commandExecutor.execute(new GetTableCountCmd(configuration.getEngineCfgKey())); } @Override public String getTableName(Class<?> entityClass) { return commandExecutor.execute(new GetTableNameCmd(entityClass)); } @Override public TableMetaData getTableMetaData(String tableName) { return commandExecutor.execute(new GetTableMetaDataCmd(tableName, configuration.getEngineCfgKey())); }
@Override public TablePageQuery createTablePageQuery() { return new TablePageQueryImpl(commandExecutor, configuration); } public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution)); } @Override public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) { return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager()); } @Override public LockManager getLockManager(String lockName) { return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey()); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnManagementServiceImpl.java
2
请完成以下Java代码
public ProcessInstanceMigrationDocumentBuilder addEnableActivityMappings(List<EnableActivityMapping> enableActivityMappings) { this.enableActivityMappings.addAll(enableActivityMappings); return this; } @Override public ProcessInstanceMigrationDocumentBuilder addEnableActivityMapping(EnableActivityMapping enableActivityMapping) { this.enableActivityMappings.add(enableActivityMapping); return this; } @Override public ProcessInstanceMigrationDocumentBuilder addProcessInstanceVariable(String variableName, Object variableValue) { this.processInstanceVariables.put(variableName, variableValue); return this; } @Override public ProcessInstanceMigrationDocumentBuilder addProcessInstanceVariables(Map<String, Object> processInstanceVariables) { this.processInstanceVariables.putAll(processInstanceVariables); return this; } @Override public ProcessInstanceMigrationDocument build() { if (migrateToProcessDefinitionId == null) { if (migrateToProcessDefinitionKey == null) { throw new FlowableException("Process definition key cannot be null"); } if (migrateToProcessDefinitionVersion != null && migrateToProcessDefinitionVersion < 0) { throw new FlowableException("Process definition version must be a positive number"); } } ProcessInstanceMigrationDocumentImpl document = new ProcessInstanceMigrationDocumentImpl(); document.setMigrateToProcessDefinitionId(migrateToProcessDefinitionId); document.setMigrateToProcessDefinition(migrateToProcessDefinitionKey, migrateToProcessDefinitionVersion, migrateToProcessDefinitionTenantId); if (preUpgradeScript != null) { document.setPreUpgradeScript(preUpgradeScript); } if (preUpgradeJavaDelegate != null) { document.setPreUpgradeJavaDelegate(preUpgradeJavaDelegate);
} if (preUpgradeJavaDelegateExpression != null) { document.setPreUpgradeJavaDelegateExpression(preUpgradeJavaDelegateExpression); } if (postUpgradeScript != null) { document.setPostUpgradeScript(postUpgradeScript); } if (postUpgradeJavaDelegate != null) { document.setPostUpgradeJavaDelegate(postUpgradeJavaDelegate); } if (postUpgradeJavaDelegateExpression != null) { document.setPostUpgradeJavaDelegateExpression(postUpgradeJavaDelegateExpression); } document.setActivityMigrationMappings(activityMigrationMappings); document.setEnableActivityMappings(enableActivityMappings); document.setProcessInstanceVariables(processInstanceVariables); return document; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\migration\ProcessInstanceMigrationDocumentBuilderImpl.java
1
请完成以下Spring Boot application配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml spring.datasource.one.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.two.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUn
icode=true&characterEncoding=utf-8&useSSL=true spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.driver-class-name=com.mysql.cj.jdbc.Driver
repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-multi-mybatis-xml\src\main\resources\application.properties
2
请完成以下Java代码
public void dispatchEvent(FlowableEvent event) { commandExecutor.execute(new DispatchEventCommand(event)); } @Override public CaseInstanceStartEventSubscriptionBuilder createCaseInstanceStartEventSubscriptionBuilder() { return new CaseInstanceStartEventSubscriptionBuilderImpl(this); } @Override public CaseInstanceStartEventSubscriptionModificationBuilder createCaseInstanceStartEventSubscriptionModificationBuilder() { return new CaseInstanceStartEventSubscriptionModificationBuilderImpl(this); } @Override
public CaseInstanceStartEventSubscriptionDeletionBuilder createCaseInstanceStartEventSubscriptionDeletionBuilder() { return new CaseInstanceStartEventSubscriptionDeletionBuilderImpl(this); } public EventSubscription registerCaseInstanceStartEventSubscription(CaseInstanceStartEventSubscriptionBuilderImpl builder) { return commandExecutor.execute(new RegisterCaseInstanceStartEventSubscriptionCmd(builder)); } public void migrateCaseInstanceStartEventSubscriptionsToCaseDefinitionVersion(CaseInstanceStartEventSubscriptionModificationBuilderImpl builder) { commandExecutor.execute(new ModifyCaseInstanceStartEventSubscriptionCmd(builder)); } public void deleteCaseInstanceStartEventSubscriptions(CaseInstanceStartEventSubscriptionDeletionBuilderImpl builder) { commandExecutor.execute(new DeleteCaseInstanceStartEventSubscriptionCmd(builder)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnRuntimeServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAge() { return age; } public void setAge(String age) {
this.age = age; } public String getEyesColor() { return eyesColor; } public void setEyesColor(String eyesColor) { this.eyesColor = eyesColor; } public String getHairColor() { return hairColor; } public void setHairColor(String hairColor) { this.hairColor = hairColor; } }
repos\tutorials-master\spring-boot-modules\spring-boot-groovy\src\main\java\com\baeldung\groovyconfig\JavaPersonBean.java
2
请完成以下Java代码
public void setUpdate_Status_ID (int Update_Status_ID) { if (Update_Status_ID < 1) set_Value (COLUMNNAME_Update_Status_ID, null); else set_Value (COLUMNNAME_Update_Status_ID, Integer.valueOf(Update_Status_ID)); } /** Get Update Status. @return Automatically change the status after entry from web */ public int getUpdate_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Update_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key.
@param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Status.java
1
请完成以下Java代码
protected final SourceDirectory getOrCreateSourceDirectory(String name) { return this.sourceDirectories.computeIfAbsent(name, (key) -> new SourceDirectory(name)); } /** * Return all {@link SourceDirectory SourceDirectories} that have been added to the * collection. * @return a collection of {@link SourceDirectory} items */ public Collection<SourceDirectory> getSourceDirectories() { return Collections.unmodifiableCollection(this.sourceDirectories.values()); } /** * Return the size of the collection. * @return the size of the collection */ public int size() { return this.filesByName.size(); } @Override public @Nullable ClassLoaderFile getFile(@Nullable String name) { return this.filesByName.get(name); } /** * Returns a set of all file entries across all source directories for efficient * iteration. * @return a set of all file entries * @since 4.0.0 */ public Set<Entry<String, ClassLoaderFile>> getFileEntries() { return Collections.unmodifiableSet(this.filesByName.entrySet()); } /** * An individual source directory that is being managed by the collection. */ public static class SourceDirectory implements Serializable { @Serial private static final long serialVersionUID = 1; private final String name;
private final Map<String, ClassLoaderFile> files = new LinkedHashMap<>(); SourceDirectory(String name) { this.name = name; } public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() { return this.files.entrySet(); } protected final void add(String name, ClassLoaderFile file) { this.files.put(name, file); } protected final void remove(String name) { this.files.remove(name); } protected final @Nullable ClassLoaderFile get(String name) { return this.files.get(name); } /** * Return the name of the source directory. * @return the name of the source directory */ public String getName() { return this.name; } /** * Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are * contained in this source directory. * @return the files contained in the source directory */ public Collection<ClassLoaderFile> getFiles() { return Collections.unmodifiableCollection(this.files.values()); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java
1
请完成以下Java代码
public static @Nullable ResourcePrefix from(@Nullable String prefix) { if (StringUtils.hasText(prefix)) { prefix = prefix.trim().toLowerCase(); for (ResourcePrefix resourcePrefix : values()) { if (resourcePrefix.toString().equals(prefix)) { return resourcePrefix; } } } return null; } private final String prefix; /** * Constructs a new instance of {@link ResourcePrefix} initialized with the named {@link String prefix}. * * @param prefix {@link String name} of the prefix. * @throws IllegalArgumentException if the {@link String prefix} is not specified. */ ResourcePrefix(String prefix) { Assert.hasText(prefix, "Resource prefix must be specified"); this.prefix = prefix; } /** * Gets the network protocol that this {@link ResourcePrefix} represents. * * @return the network protocol that this {@link ResourcePrefix} represents. */ public String getProtocol() { StringBuilder buffer = new StringBuilder(); for (char character : this.prefix.toCharArray()) { if (Character.isAlphabetic(character)) { buffer.append(character); }
} return buffer.toString(); } /** * Gets the {@link String pattern} or template used to construct a {@link java.net.URL} prefix * from this {@link ResourcePrefix}. * * @return the {@link String pattern} or template used to construct a {@link java.net.URL} prefix * from this {@link ResourcePrefix}. * @see #toUrlPrefix() */ protected String getUrlPrefixPattern() { return this.equals(CLASSPATH_URL_PREFIX) ? "%s" : "%1$s%2$s%2$s"; } @Override public String toString() { return this.prefix; } /** * Gets the {@link ResourcePrefix} as a prefix use in a {@link java.net.URL}. * * @return the {@link java.net.URL} prefix. * @see #getUrlPrefixPattern() */ public String toUrlPrefix() { return String.format(getUrlPrefixPattern(), toString(), RESOURCE_PATH_SEPARATOR); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\ResourcePrefix.java
1
请完成以下Java代码
public ListEntry getListEntry() { return this.parent; } } private class ListEntry { final T value; final ListWeakReference weakValue; final boolean isWeak; /** * String representation of "value" (only if isWeak). * * NOTE: this variable is filled only if {@link WeakList#DEBUG} flag is set. */ final String valueStr; public ListEntry(final T value, final boolean isWeak) { if (isWeak) { this.value = null; this.weakValue = new ListWeakReference(value, this); this.isWeak = true; this.valueStr = DEBUG ? String.valueOf(value) : null; } else { this.value = value; this.weakValue = null; this.isWeak = false; this.valueStr = null; } } private boolean isAvailable() { if (isWeak) { return weakValue.get() != null; } else { return true; } } public T get() { if (isWeak) { return weakValue.get(); } else { return value; } } /** * Always compare by identity.
* * @return true if it's the same instance. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } return false; } @Override public int hashCode() { // NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning" return super.hashCode(); } @Override public String toString() { if (!isAvailable()) { return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>"; } else { return String.valueOf(this.get()); } } } /** * Gets internal lock used by this weak list. * * NOTE: use it only if you know what are you doing. * * @return internal lock used by this weak list. */ public final ReentrantLock getReentrantLock() { return lock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<JsonExternalReferenceLookupRequest> buildESRLookupRequest( @NonNull final List<Order> orders, @NonNull final Exchange exchange, @NonNull final PharmacyApi pharmacyApi, @NonNull final DoctorApi doctorApi) { final Map<String, Object> externalBPId2Api = new HashMap<>(); orders.forEach(order -> { if (!StringUtils.isEmpty(order.getDoctorId())) { externalBPId2Api.put(order.getDoctorId(), doctorApi); } if (!StringUtils.isEmpty(order.getPharmacyId())) { externalBPId2Api.put(order.getPharmacyId(), pharmacyApi); } }); if (externalBPId2Api.isEmpty()) { return Optional.empty(); } exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_EXTERNAL_BP_IDENTIFIER_TO_API, externalBPId2Api); final JsonExternalReferenceLookupRequest.JsonExternalReferenceLookupRequestBuilder jsonExternalReferenceLookupRequest =
JsonExternalReferenceLookupRequest.builder() .systemName(JsonExternalSystemName.of(GetPatientsRouteConstants.ALBERTA_SYSTEM_NAME)); externalBPId2Api.keySet().stream() .map(this::getBPartnerLookupItem) .forEach(jsonExternalReferenceLookupRequest::item); return Optional.of(jsonExternalReferenceLookupRequest.build()); } @NonNull private JsonExternalReferenceLookupItem getBPartnerLookupItem(@NonNull final String externalId) { return JsonExternalReferenceLookupItem.builder() .type(GetPatientsRouteConstants.ESR_TYPE_BPARTNER) .id(externalId) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\ExternalReferenceLookupProcessor.java
2
请完成以下Java代码
public class ReadOnlyMapELResolver extends ELResolver { protected Map<Object, Object> wrappedMap; public ReadOnlyMapELResolver(Map<Object, Object> map) { this.wrappedMap = map; } @Override public Object getValue(ELContext context, Object base, Object property) { if (base == null) { if (wrappedMap.containsKey(property)) { context.setPropertyResolved(true); return wrappedMap.get(property); } } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null) { if (wrappedMap.containsKey(property)) { throw new FlowableException("Cannot set value of '" + property + "', it's readonly!"); } } } @Override public Class<?> getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Class<?> getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\ReadOnlyMapELResolver.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtTokenService { private final JwtEncoder jwtEncoder; public JwtTokenService(JwtEncoder jwtEncoder) { this.jwtEncoder = jwtEncoder; } public String generateToken(Authentication authentication) { var scope = authentication .getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(" "));
var claims = JwtClaimsSet.builder() .issuer("self") .issuedAt(Instant.now()) .expiresAt(Instant.now().plus(90, ChronoUnit.MINUTES)) .subject(authentication.getName()) .claim("scope", scope) .build(); return this.jwtEncoder .encode(JwtEncoderParameters.from(claims)) .getTokenValue(); } }
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\jwt\JwtTokenService.java
2
请完成以下Java代码
public void setValidationDate(XMLGregorianCalendar value) { this.validationDate = value; } /** * Gets the value of the validationId property. * * @return * possible object is * {@link String } * */ public String getValidationId() { return validationId; } /** * Sets the value of the validationId property. * * @param value * allowed object is * {@link String } * */ public void setValidationId(String value) { this.validationId = value; } /** * Gets the value of the validationServer property. * * @return * possible object is * {@link String } * */ public String getValidationServer() {
return validationServer; } /** * Sets the value of the validationServer property. * * @param value * allowed object is * {@link String } * */ public void setValidationServer(String value) { this.validationServer = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PatientAddressType.java
1
请完成以下Java代码
public void writeCharacters(String text) throws XMLStreamException { writer.writeCharacters(text); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { writer.writeCharacters(text, start, len); } public String getPrefix(String uri) throws XMLStreamException { return writer.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { writer.setPrefix(prefix, uri); } public void setDefaultNamespace(String uri) throws XMLStreamException {
writer.setDefaultNamespace(uri); } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { writer.setNamespaceContext(context); } public NamespaceContext getNamespaceContext() { return writer.getNamespaceContext(); } public Object getProperty(String name) throws IllegalArgumentException { return writer.getProperty(name); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\DelegatingXMLStreamWriter.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductController { public RouterFunction<ServerResponse> productListing(ProductService ps) { return route().GET("/product", req -> ok().body(ps.findAll())) .build(); } public RouterFunction<ServerResponse> productSearch(ProductService ps) { return route().nest(RequestPredicates.path("/product"), builder -> builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name")))) .GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id")))))) .onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) .status(HttpStatus.NOT_FOUND) .build()) .build(); } public RouterFunction<ServerResponse> adminFunctions(ProductService ps) { return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class)))) .filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build())
.onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) .status(HttpStatus.BAD_REQUEST) .build()) .build(); } public RouterFunction<ServerResponse> remainingProductRoutes(ProductService ps) { return route().add(productSearch(ps)) .add(adminFunctions(ps)) .build(); } private boolean authenticate(ServerRequest req) { return Boolean.TRUE; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\ctrl\ProductController.java
2
请完成以下Java代码
public void setM_Inventory(org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } /** Set Inventur. @param M_Inventory_ID Parameters for a Physical Inventory */ @Override public void setM_Inventory_ID (int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID)); } /** Get Inventur. @return Parameters for a Physical Inventory */ @Override public int getM_Inventory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutConfirm.java
1
请完成以下Java代码
protected String doIt() throws Exception { final File file = new File(fileName); if (!file.exists()) { throw new AdempiereException("@FileNotFound@"); } final File[] migrationFiles; if (file.isDirectory()) { migrationFiles = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml");
} }); } else { migrationFiles = new File[] { file }; } for (final File migrationFile : migrationFiles) { final XMLLoader loader = new XMLLoader(migrationFile.getAbsolutePath()); loader.load(get_TrxName()); } return "Import complete"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\process\MigrationFromXML.java
1
请在Spring Boot框架中完成以下Java代码
public class ManageSchedulerQueueConfiguration implements IEventBusQueueConfiguration { public static final Topic EVENTBUS_TOPIC = Topic.distributed("de.metas.externalsystem.rabbitmq.request.ManageSchedulerRequest"); static final String QUEUE_NAME_SPEL = "#{metasfreshManageSchedulerQueue.name}"; private static final String QUEUE_BEAN_NAME = "metasfreshManageSchedulerQueue"; private static final String EXCHANGE_NAME_PREFIX = "metasfresh-scheduler-events"; @Value(RabbitMQEventBusConfiguration.APPLICATION_NAME_SPEL) private String appName; @Bean(QUEUE_BEAN_NAME) public AnonymousQueue schedulerQueue() { final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy(EVENTBUS_TOPIC.getName() + "." + appName + "-"); return new AnonymousQueue(eventQueueNamingStrategy); } @Bean public DirectExchange schedulerExchange() { return new DirectExchange(EXCHANGE_NAME_PREFIX); } @Bean public Binding schedulerBinding() { return BindingBuilder.bind(schedulerQueue()) .to(schedulerExchange()).with(EXCHANGE_NAME_PREFIX); } @Override public String getQueueName() {
return schedulerQueue().getName(); } @Override public Optional<String> getTopicName() { return Optional.of(EVENTBUS_TOPIC.getName()); } @Override public String getExchangeName() { return schedulerExchange().getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\manage_scheduler\ManageSchedulerQueueConfiguration.java
2
请完成以下Java代码
public void setQtyCUsPerTU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerTU_InInvoiceUOM) { set_Value (COLUMNNAME_QtyCUsPerTU_InInvoiceUOM, QtyCUsPerTU_InInvoiceUOM); } @Override public BigDecimal getQtyCUsPerTU_InInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU_InInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity) { set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity); } @Override public BigDecimal getQtyItemCapacity()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final int QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public int getQtyTU() { return get_ValueAsInt(COLUMNNAME_QtyTU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack_Item.java
1
请完成以下Java代码
public Map<String, List<TaskListener>> getTaskListeners() { return taskListeners; } public Map<String, List<TaskListener>> getBuiltinTaskListeners() { return builtinTaskListeners; } public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) { this.taskListeners = taskListeners; } public List<TaskListener> getTaskListenersForEvent(String eventName) { return taskListeners.get(eventName); } public List<TaskListener> getBuiltinTaskListenersForEvent(String eventName) { return builtinTaskListeners.get(eventName); } public List<TaskListener> getAllTaskListenersForEvent(String eventName) { return allTaskListeners.get(eventName); } public TaskListener getTimeoutTaskListener(String timeoutId) { return timeoutTaskListeners.get(timeoutId); } public void addTaskListener(String eventName, TaskListener taskListener) { CollectionUtil.addToMapOfLists(taskListeners, eventName, taskListener); // re-calculate combined map to ensure order of listener execution populateAllTaskListeners(); } public void addBuiltInTaskListener(String eventName, TaskListener taskListener) { CollectionUtil.addToMapOfLists(builtinTaskListeners, eventName, taskListener); // re-calculate combined map to ensure order of listener execution populateAllTaskListeners(); } public void addTimeoutTaskListener(String timeoutId, TaskListener taskListener) { timeoutTaskListeners.put(timeoutId, taskListener); } public FormDefinition getFormDefinition() { return formDefinition; } public void setFormDefinition(FormDefinition formDefinition) { this.formDefinition = formDefinition; } public Expression getFormKey() {
return formDefinition.getFormKey(); } public void setFormKey(Expression formKey) { this.formDefinition.setFormKey(formKey); } public Expression getCamundaFormDefinitionKey() { return formDefinition.getCamundaFormDefinitionKey(); } public String getCamundaFormDefinitionBinding() { return formDefinition.getCamundaFormDefinitionBinding(); } public Expression getCamundaFormDefinitionVersion() { return formDefinition.getCamundaFormDefinitionVersion(); } // helper methods /////////////////////////////////////////////////////////// protected void populateAllTaskListeners() { // reset allTaskListeners to build it from zero allTaskListeners = new HashMap<>(); // ensure builtinTaskListeners are executed before regular taskListeners CollectionUtil.mergeMapsOfLists(allTaskListeners, builtinTaskListeners); CollectionUtil.mergeMapsOfLists(allTaskListeners, taskListeners); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDefinition.java
1
请完成以下Java代码
protected boolean acceptDocument(final Object model) { return docOutboundConfigService.retrieveConfigForModel(model) != null; } @Override public void createDocOutbound(@NonNull final Object model) { enqueueModelForWorkpackageProcessor(model, DocOutboundWorkpackageProcessor.class); } @Override public void voidDocOutbound(@NonNull final Object model) { enqueueModelForWorkpackageProcessor(model, ProcessPrintingQueueWorkpackageProcessor.class); } private void enqueueModelForWorkpackageProcessor( @NonNull final Object model, @NonNull final Class<? extends IWorkpackageProcessor> packageProcessorClass) {
final Properties ctx = InterfaceWrapperHelper.getCtx(model); final I_C_Async_Batch asyncBatch = asyncBatchBL.getAsyncBatchId(model) .map(asyncBatchBL::getAsyncBatchById) .orElse(null); workPackageQueueFactory .getQueueForEnqueuing(ctx, packageProcessorClass) .newWorkPackage() .bindToThreadInheritedTrx() .addElement(model) .setC_Async_Batch(asyncBatch) .setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null)) .buildAndEnqueue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\AbstractDocOutboundProducer.java
1
请完成以下Java代码
public java.lang.String getShipperRouteCodeName() { return get_ValueAsString(COLUMNNAME_ShipperRouteCodeName); } @Override public void setShortDescription (final @Nullable java.lang.String ShortDescription) { set_Value (COLUMNNAME_ShortDescription, ShortDescription); } @Override public java.lang.String getShortDescription() { return get_ValueAsString(COLUMNNAME_ShortDescription); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } @Override public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle()
{ return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } @Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请在Spring Boot框架中完成以下Java代码
public String getIncotermCode() { return incotermCode; } /** * Sets the value of the incotermCode property. * * @param value * allowed object is * {@link String } * */ public void setIncotermCode(String value) { this.incotermCode = value; } /** * Gets the value of the incotermText property. * * @return * possible object is * {@link String } * */ public String getIncotermText() { return incotermText; } /** * Sets the value of the incotermText property. * * @param value * allowed object is * {@link String } * */
public void setIncotermText(String value) { this.incotermText = value; } /** * Gets the value of the incotermLocation property. * * @return * possible object is * {@link String } * */ public String getIncotermLocation() { return incotermLocation; } /** * Sets the value of the incotermLocation property. * * @param value * allowed object is * {@link String } * */ public void setIncotermLocation(String value) { this.incotermLocation = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\IncotermType.java
2
请完成以下Java代码
public void setMSV3_ErrorCode (java.lang.String MSV3_ErrorCode) { set_Value (COLUMNNAME_MSV3_ErrorCode, MSV3_ErrorCode); } /** Get ErrorCode. @return ErrorCode */ @Override public java.lang.String getMSV3_ErrorCode () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_ErrorCode); } /** Set MSV3_FaultInfo. @param MSV3_FaultInfo_ID MSV3_FaultInfo */ @Override public void setMSV3_FaultInfo_ID (int MSV3_FaultInfo_ID) { if (MSV3_FaultInfo_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_FaultInfo_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_FaultInfo_ID, Integer.valueOf(MSV3_FaultInfo_ID)); } /** Get MSV3_FaultInfo. @return MSV3_FaultInfo */ @Override public int getMSV3_FaultInfo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_FaultInfo_ID); if (ii == null) return 0; return ii.intValue(); } /** * MSV3_FaultInfoType AD_Reference_ID=540827 * Reference name: MSV3_FaultInfoType */ public static final int MSV3_FAULTINFOTYPE_AD_Reference_ID=540827; /** AuthorizationFaultInfo = AuthorizationFaultInfo */ public static final String MSV3_FAULTINFOTYPE_AuthorizationFaultInfo = "AuthorizationFaultInfo"; /** DenialOfServiceFault = DenialOfServiceFault */ public static final String MSV3_FAULTINFOTYPE_DenialOfServiceFault = "DenialOfServiceFault"; /** LieferscheinOderBarcodeUnbekanntFaultInfo = LieferscheinOderBarcodeUnbekanntFaultInfo */ public static final String MSV3_FAULTINFOTYPE_LieferscheinOderBarcodeUnbekanntFaultInfo = "LieferscheinOderBarcodeUnbekanntFaultInfo"; /** ServerFaultInfo = ServerFaultInfo */
public static final String MSV3_FAULTINFOTYPE_ServerFaultInfo = "ServerFaultInfo"; /** ValidationFaultInfo = ValidationFaultInfo */ public static final String MSV3_FAULTINFOTYPE_ValidationFaultInfo = "ValidationFaultInfo"; /** Set FaultInfoType. @param MSV3_FaultInfoType FaultInfoType */ @Override public void setMSV3_FaultInfoType (java.lang.String MSV3_FaultInfoType) { set_Value (COLUMNNAME_MSV3_FaultInfoType, MSV3_FaultInfoType); } /** Get FaultInfoType. @return FaultInfoType */ @Override public java.lang.String getMSV3_FaultInfoType () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_FaultInfoType); } /** Set TechnischerFehlertext. @param MSV3_TechnischerFehlertext TechnischerFehlertext */ @Override public void setMSV3_TechnischerFehlertext (java.lang.String MSV3_TechnischerFehlertext) { set_Value (COLUMNNAME_MSV3_TechnischerFehlertext, MSV3_TechnischerFehlertext); } /** Get TechnischerFehlertext. @return TechnischerFehlertext */ @Override public java.lang.String getMSV3_TechnischerFehlertext () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_TechnischerFehlertext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_FaultInfo.java
1
请完成以下Java代码
public int getAPI_Response_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID); } @Override public void setBody (final @Nullable java.lang.String Body) { set_Value (COLUMNNAME_Body, Body); } @Override public java.lang.String getBody() { return get_ValueAsString(COLUMNNAME_Body); } @Override public void setHttpCode (final @Nullable java.lang.String HttpCode) { set_Value (COLUMNNAME_HttpCode, HttpCode); } @Override public java.lang.String getHttpCode() { return get_ValueAsString(COLUMNNAME_HttpCode); } @Override public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders) { set_Value (COLUMNNAME_HttpHeaders, HttpHeaders); } @Override
public java.lang.String getHttpHeaders() { return get_ValueAsString(COLUMNNAME_HttpHeaders); } @Override public void setTime (final @Nullable java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java
1
请完成以下Java代码
public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @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_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price)
{ set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderLine_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public String event02() { try { int result = 1 / 0; } catch (Throwable e) { Cat.logError(e); // Cat.logError("custom-message", e); } return "success"; } /** * 监控模型 Event 的示例 03 */ @GetMapping("/event-03") public String event03() { try { int result = 1 / 0; } catch (Throwable e) { Cat.logErrorWithCategory("custom-category", e); // Cat.logErrorWithCategory("custom-category", "custom-message", e); } return "success"; } /** * 监控模型 Metric 示例 01 */
@GetMapping("/metric-01") public String metric01() { Cat.logMetricForCount("visit.count", 1); return "success"; } /** * 监控模型 Metric 示例 02 */ @GetMapping("/metric-02") public String metric02() { Cat.logMetricForDuration("visit.duration", 10L); return "success"; } }
repos\SpringBoot-Labs-master\lab-61\lab-61-demo\src\main\java\cn\iocoder\springboot\lab61\catdemo\controller\DemoController.java
2
请在Spring Boot框架中完成以下Java代码
public class AttributeListValue { @NonNull AttributeValueId id; @NonNull AttributeId attributeId; @Nullable String value; @NonNull String name; @Nullable String description; @NonNull AttributeListValueTrxRestriction availableForTrx; boolean active; boolean nullFieldValue; public int getValueAsInt() { try { return Integer.valueOf(value); }
catch (Exception ex) { throw new AdempiereException("Failed converting value '" + value + "' to int") .appendParametersToMessage() .setParameter("AttributeListValue", this); } } public ITranslatableString getNameTrl() { return TranslatableStrings.anyLanguage(getName()); } public boolean isMatchingSOTrx(@Nullable final SOTrx soTrx) { return availableForTrx.isMatchingSOTrx(soTrx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeListValue.java
2
请完成以下Java代码
public int getValueAsInteger(final int defaultValueIfNull) { if (value == null) { return defaultValueIfNull; } else if (value instanceof Number) { return ((Number)value).intValue(); } else { return Integer.parseInt(value.toString()); } } public List<Integer> getValueAsIntegersList() { if (value == null) { return ImmutableList.of(); } if (value instanceof List<?>) { @SuppressWarnings("unchecked") final List<Integer> intList = (List<Integer>)value; return intList; } else if (value instanceof String) { return ImmutableList.copyOf(DocumentIdsSelection.ofCommaSeparatedString(value.toString()).toIntSet()); } else { throw new AdempiereException("Cannot convert value to int list").setParameter("event", this); } } public <ET extends Enum<ET>> ET getValueAsEnum(final Class<ET> enumType)
{ if (value == null) { return null; } if (enumType.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") final ET valueConv = (ET)value; return valueConv; } else if (value instanceof String) { return Enum.valueOf(enumType, value.toString()); } else { throw new AdempiereException("Cannot convert value " + value + " to " + enumType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONPatchEvent.java
1
请完成以下Java代码
private Optional<CostAmount> computeComponentsCostPrice(@NonNull final CostElementId costElementId) { final Optional<CostAmount> componentsTotalAmt = getLines() .stream() .filter(BOMLine::isInboundBOMCosts) .map(bomLine -> bomLine.getCostAmountOrNull(costElementId)) .filter(Objects::nonNull) .reduce(CostAmount::add); return componentsTotalAmt.map(amt -> amt.divide(qty, precision)); } @Nullable private CostAmount distributeToCoProductBOMLines( @Nullable final CostAmount bomCostPrice, @NonNull final CostElementId costElementId) { CostAmount bomCostPriceWithoutCoProducts = bomCostPrice; for (final BOMLine bomLine : getLines()) { if (!bomLine.isCoProduct()) { continue; } if (bomCostPrice != null && !bomCostPrice.isZero()) { final Percent costAllocationPerc = bomLine.getCoProductCostDistributionPercent(); final CostAmount coProductCostPrice = bomCostPrice.multiply(costAllocationPerc, precision); bomLine.setComponentsCostPrice(coProductCostPrice, costElementId); bomCostPriceWithoutCoProducts = bomCostPriceWithoutCoProducts.subtract(coProductCostPrice); } else { bomLine.clearComponentsCostPrice(costElementId); } } return bomCostPriceWithoutCoProducts; } Stream<BOMCostPrice> streamCostPrices() { final Stream<BOMCostPrice> linesCostPrices = getLines().stream().map(BOMLine::getCostPrice); return Stream.concat(Stream.of(getCostPrice()), linesCostPrices); } private ImmutableSet<CostElementId> getCostElementIds()
{ return streamCostPrices() .flatMap(BOMCostPrice::streamCostElementIds) .distinct() .collect(ImmutableSet.toImmutableSet()); } <T extends RepoIdAware> Set<T> getCostIds(@NonNull final Class<T> idType) { return streamCostPrices() .flatMap(bomCostPrice -> bomCostPrice.streamIds(idType)) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public Set<ProductId> getProductIds() { final ImmutableSet.Builder<ProductId> productIds = ImmutableSet.builder(); productIds.add(getProductId()); getLines().forEach(bomLine -> productIds.add(bomLine.getComponentId())); return productIds.build(); } public ImmutableList<BOMCostElementPrice> getElementPrices() { return getCostPrice().getElementPrices(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOM.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } @Transactional public Page<Author> fetchPageOfAuthorsWithBooksByGenre(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name")); Page<Long> pageOfIds = authorRepository.fetchPageOfIdsByGenre("Anthology", pageable); List<Author> listOfAuthors = authorRepository.fetchWithBooksJoinFetch(pageOfIds.getContent()); Page<Author> pageOfAuthors = new PageImpl(listOfAuthors, pageable, pageOfIds.getTotalElements()); return pageOfAuthors; } @Transactional public Slice<Author> fetchSliceOfAuthorsWithBooksByGenre(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name")); Slice<Long> pageOfIds = authorRepository.fetchSliceOfIdsByGenre("Anthology", pageable); List<Author> listOfAuthors = authorRepository.fetchWithBooksJoinFetch(pageOfIds.getContent()); Slice<Author> sliceOfAuthors = new SliceImpl(listOfAuthors, pageable, pageOfIds.hasNext()); return sliceOfAuthors; } @Transactional public List<Author> fetchListOfAuthorsWithBooksByGenre(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name")); List<Long> listOfIds = authorRepository.fetchListOfIdsByGenre("Anthology", pageable); List<Author> listOfAuthors = authorRepository.fetchWithBooksJoinFetch(listOfIds); return listOfAuthors; } @Transactional public Page<Author> fetchPageOfAuthorsWithBooksByGenreEntityGraph(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name")); Page<Long> pageOfIds = authorRepository.fetchPageOfIdsByGenre("Anthology", pageable); List<Author> listOfAuthors = authorRepository.fetchWithBooksEntityGraph(pageOfIds.getContent());
Page<Author> pageOfAuthors = new PageImpl(listOfAuthors, pageable, pageOfIds.getTotalElements()); return pageOfAuthors; } @Transactional public Page<Author> fetchPageOfAuthorsWithBooksByGenreTuple(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name")); List<Tuple> tuples = authorRepository.fetchTupleOfIdsByGenre("Anthology", pageable); List<Long> listOfIds = new ArrayList<>(tuples.size()); for(Tuple tuple: tuples) { listOfIds.add(((BigInteger) tuple.get("id")).longValue()); } List<Author> listOfAuthors = authorRepository.fetchWithBooksJoinFetch(listOfIds); Page<Author> pageOfAuthors = new PageImpl(listOfAuthors, pageable, ((BigInteger) tuples.get(0).get("total")).longValue()); return pageOfAuthors; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHHH000104\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { doHandle(thrownException, data, consumer, container, invokeListener); } @Override public <K, V> ConsumerRecords<K, V> handleBatchAndReturnRemaining(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { return handle(thrownException, data, consumer, container, invokeListener); } @Override public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { if (thrownException instanceof SerializationException) { throw new IllegalStateException("This error handler cannot process 'SerializationException's directly; " + "please consider configuring an 'ErrorHandlingDeserializer' in the value and/or key "
+ "deserializer", thrownException); } else { throw new IllegalStateException("This error handler cannot process '" + thrownException.getClass().getName() + "'s; no record information is available", thrownException); } } @Override public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { getFallbackBatchHandler().onPartitionsAssigned(consumer, partitions, publishPause); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\DefaultErrorHandler.java
1
请完成以下Java代码
public VariableMap getAllVariablesTyped() { return getAllVariablesTyped(true); } public VariableMap getAllVariablesTyped(boolean deserializeObjectValues) { VariableMap variables = Variables.createVariables(); receivedVariableMap.forEach((variableName, variableValue) -> { TypedValue typedValue = getVariableTyped(variableName, deserializeObjectValues); variables.putValueTyped(variableName, typedValue); }); return variables; } @JsonIgnore @Override public <T extends TypedValue> T getVariableTyped(String variableName) { return getVariableTyped(variableName, true); } @SuppressWarnings({ "rawtypes", "unchecked" }) @JsonIgnore @Override public <T extends TypedValue> T getVariableTyped(String variableName, boolean deserializeObjectValues) { TypedValue typedValue = null; VariableValue variableValue = receivedVariableMap.get(variableName); if (variableValue != null) { typedValue = variableValue.getTypedValue(deserializeObjectValues); } return (T) typedValue; } public Map<String, String> getExtensionProperties() { return extensionProperties == null ? Collections.emptyMap() : extensionProperties; } public void setExtensionProperties(Map<String, String> extensionProperties) { this.extensionProperties = extensionProperties; } @JsonIgnore @Override public String getExtensionProperty(String propertyKey) { if(extensionProperties != null) { return extensionProperties.get(propertyKey); } return null; }
@Override public String toString() { return "ExternalTaskImpl [" + "activityId=" + activityId + ", " + "activityInstanceId=" + activityInstanceId + ", " + "businessKey=" + businessKey + ", " + "errorDetails=" + errorDetails + ", " + "errorMessage=" + errorMessage + ", " + "executionId=" + executionId + ", " + "id=" + id + ", " + formatTimeField("lockExpirationTime", lockExpirationTime) + ", " + formatTimeField("createTime", createTime) + ", " + "priority=" + priority + ", " + "processDefinitionId=" + processDefinitionId + ", " + "processDefinitionKey=" + processDefinitionKey + ", " + "processDefinitionVersionTag=" + processDefinitionVersionTag + ", " + "processInstanceId=" + processInstanceId + ", " + "receivedVariableMap=" + receivedVariableMap + ", " + "retries=" + retries + ", " + "tenantId=" + tenantId + ", " + "topicName=" + topicName + ", " + "variables=" + variables + ", " + "workerId=" + workerId + "]"; } protected String formatTimeField(String timeField, Date time) { return timeField + "=" + (time == null ? null : DateFormat.getDateTimeInstance().format(time)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskImpl.java
1
请完成以下Java代码
public class FunctionDefinitionImpl extends ExpressionImpl implements FunctionDefinition { protected static ChildElementCollection<FormalParameter> formalParameterCollection; protected static ChildElement<Expression> expressionChild; public FunctionDefinitionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Collection<FormalParameter> getFormalParameters() { return formalParameterCollection.get(this); } public Expression getExpression() { return expressionChild.getChild(this); } public void setExpression(Expression expression) { expressionChild.setChild(this, expression); }
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(FunctionDefinition.class, DMN_ELEMENT_FUNCTION_DEFINITION) .namespaceUri(LATEST_DMN_NS) .extendsType(Expression.class) .instanceProvider(new ModelTypeInstanceProvider<FunctionDefinition>() { public FunctionDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new FunctionDefinitionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); formalParameterCollection = sequenceBuilder.elementCollection(FormalParameter.class) .build(); expressionChild = sequenceBuilder.element(Expression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\FunctionDefinitionImpl.java
1
请完成以下Java代码
private DocumentPath getRootDocumentPath() { Check.assumeNotNull(_rootDocumentPath, "Parameter rootDocumentPath is not null"); return _rootDocumentPath; } public Builder setQuickInputDescriptor(final QuickInputDescriptor quickInputDescriptor) { _quickInputDescriptor = quickInputDescriptor; return this; } private QuickInputDescriptor getQuickInputDescriptor() { Check.assumeNotNull(_quickInputDescriptor, "Parameter quickInputDescriptor is not null"); return _quickInputDescriptor; }
private DetailId getTargetDetailId() { final DetailId targetDetailId = getQuickInputDescriptor().getDetailId(); Check.assumeNotNull(targetDetailId, "Parameter targetDetailId is not null"); return targetDetailId; } private Document buildQuickInputDocument() { return Document.builder(getQuickInputDescriptor().getEntityDescriptor()) .initializeAsNewDocument(nextQuickInputDocumentId::getAndIncrement, VERSION_DEFAULT); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInput.java
1
请完成以下Java代码
public Optional<AdMessageId> getIdByAdMessage(final AdMessageKey adMessage) { return Optional.ofNullable(getByAdMessage(adMessage)).map(Message::getAdMessageId); } @Nullable public Message getByAdMessage(@NonNull final String adMessage) { return getByAdMessage(AdMessageKey.of(adMessage)); } @Nullable public Message getByAdMessage(@NonNull final AdMessageKey adMessage) { return byAdMessage.get(adMessage); } public Stream<Message> stream() {return byAdMessage.values().stream();} public Map<String, String> toStringMap(final String adLanguage, final String prefix, boolean removePrefix) { final Function<Message, String> keyFunction; if (removePrefix) { final int beginIndex = prefix.length(); keyFunction = message -> message.getAdMessage().toAD_Message().substring(beginIndex); } else { keyFunction = message -> message.getAdMessage().toAD_Message();
} return stream() .filter(message -> message.getAdMessage().startsWith(prefix)) .collect(ImmutableMap.toImmutableMap(keyFunction, message -> message.getMsgText(adLanguage))); } public Optional<Message> getById(@NonNull final AdMessageId adMessageId) { return Optional.ofNullable(byId.get(adMessageId)); } public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return getById(adMessageId).map(Message::getAdMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessagesMap.java
1