instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions( @NonNull final WFProcessId wfProcessId, @NonNull final WFActivityId wfActivityId) { final WFProcess wfProcess = getWorkflowBasedMobileApplication(wfProcessId.getApplicationId()).getWFProcessById(wfProcessId); final WFActivity wfActivity = wfProcess.getActivityById(wfActivityId); return wfActivityHandlersRegistry .getFeature(wfActivity.getWfActivityType(), SetScannedBarcodeSupport.class) .getScannedBarcodeSuggestions(GetScannedBarcodeSuggestionsRequest.builder() .wfProcess(wfProcess) .build()); } public WFProcess setUserConfirmation( @NonNull final UserId invokerId, @NonNull final WFProcessId wfProcessId, @NonNull final WFActivityId wfActivityId) { return processWFActivity( invokerId, wfProcessId, wfActivityId, this::setUserConfirmation0); } private WFProcess setUserConfirmation0( @NonNull final WFProcess wfProcess, @NonNull final WFActivity wfActivity) { return wfActivityHandlersRegistry .getFeature(wfActivity.getWfActivityType(), UserConfirmationSupport.class) .userConfirmed(UserConfirmationRequest.builder() .wfProcess(wfProcess) .wfActivity(wfActivity) .build()); } private WFProcess processWFActivity( @NonNull final UserId invokerId, @NonNull final WFProcessId wfProcessId, @NonNull final WFActivityId wfActivityId, @NonNull final BiFunction<WFProcess, WFActivity, WFProcess> processor) { return changeWFProcessById( wfProcessId, wfProcess -> {
wfProcess.assertHasAccess(invokerId); final WFActivity wfActivity = wfProcess.getActivityById(wfActivityId); WFProcess wfProcessChanged = processor.apply(wfProcess, wfActivity); if (!Objects.equals(wfProcess, wfProcessChanged)) { wfProcessChanged = withUpdatedActivityStatuses(wfProcessChanged); } return wfProcessChanged; }); } private WFProcess withUpdatedActivityStatuses(@NonNull final WFProcess wfProcess) { WFProcess wfProcessChanged = wfProcess; for (final WFActivity wfActivity : wfProcess.getActivities()) { final WFActivityStatus newActivityStatus = wfActivityHandlersRegistry .getHandler(wfActivity.getWfActivityType()) .computeActivityState(wfProcessChanged, wfActivity); wfProcessChanged = wfProcessChanged.withChangedActivityStatus(wfActivity.getId(), newActivityStatus); } return wfProcessChanged; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\service\WorkflowRestAPIService.java
2
请完成以下Java代码
public class VariableEqualsExpressionFunction extends AbstractFlowableVariableExpressionFunction { public VariableEqualsExpressionFunction() { super(Arrays.asList("equals", "eq"), "equals"); } public static boolean equals(VariableContainer variableContainer, String variableName, Object comparedValue) { Object variableValue = getVariableValue(variableContainer, variableName); if (comparedValue != null && variableValue != null) { // Numbers are not necessarily of the expected type due to coming from JUEL, // (eg. variable can be an Integer but JUEL passes a Long). // As such, a specific check for the supported Number variable types of Flowable is done. if (valuesAreNumbers(comparedValue, variableValue)) { if (variableValue instanceof Long) { return ((Number) variableValue).longValue() == ((Number) comparedValue).longValue(); } else if (variableValue instanceof Integer) { return ((Number) variableValue).intValue() == ((Number) comparedValue).intValue(); } else if (variableValue instanceof Double) {
return ((Number) variableValue).doubleValue() == ((Number) comparedValue).doubleValue(); } else if (variableValue instanceof Float) { return ((Number) variableValue).floatValue() == ((Number) comparedValue).floatValue(); } else if (variableValue instanceof Short) { return ((Number) variableValue).shortValue() == ((Number) comparedValue).shortValue(); } // Other subtypes possible (e.g. BigDecimal, AtomicInteger, etc.), will fall back to default comparison } } return defaultEquals(comparedValue, variableValue); } protected static boolean defaultEquals(Object variableValue, Object actualValue) { return Objects.equals(actualValue, variableValue); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\VariableEqualsExpressionFunction.java
1
请完成以下Java代码
protected void processHandlePost(CoapExchange exchange) { log.debug("processHandlePost [{}]", exchange); } /** * Override the default behavior so that requests to sub resources (typically /{name}/{token}) are handled by * /name resource. */ @Override public Resource getChild(String name) { return this; } private String getTokenFromRequest(Request request) { return (request.getSourceContext() != null ? request.getSourceContext().getPeerAddress().getAddress().getHostAddress() : "null") + ":" + (request.getSourceContext() != null ? request.getSourceContext().getPeerAddress().getPort() : -1) + ":" + request.getTokenString(); } public class CoapResourceObserver implements ResourceObserver { @Override public void changedName(String old) { } @Override public void changedPath(String old) { } @Override public void addedChild(Resource child) { } @Override public void removedChild(Resource child) { } @Override public void addedObserveRelation(ObserveRelation relation) { } @Override public void removedObserveRelation(ObserveRelation relation) { }
} private void sendOtaData(CoapExchange exchange) { String idStr = exchange.getRequestOptions().getUriPath().get(exchange.getRequestOptions().getUriPath().size() - 1 ); UUID currentId = UUID.fromString(idStr); Response response = new Response(CoAP.ResponseCode.CONTENT); byte[] otaData = this.getOtaData(currentId); if (otaData != null && otaData.length > 0) { log.debug("Read ota data (length): [{}]", otaData.length); response.setPayload(otaData); if (exchange.getRequestOptions().getBlock2() != null) { int szx = exchange.getRequestOptions().getBlock2().getSzx(); int chunkSize = exchange.getRequestOptions().getBlock2().getSize(); boolean lastFlag = otaData.length <= chunkSize; response.getOptions().setBlock2(szx, lastFlag, 0); log.trace("With block2 Send currentId: [{}], length: [{}], chunkSize [{}], szx [{}], moreFlag [{}]", currentId, otaData.length, chunkSize, szx, lastFlag); } else { log.trace("With block1 Send currentId: [{}], length: [{}], ", currentId, otaData.length); } exchange.respond(response); } else { log.trace("Ota packaged currentId: [{}] is not found.", currentId); } } private byte[] getOtaData(UUID currentId) { return otaPackageDataCache.get(currentId.toString()); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mTransportCoapResource.java
1
请在Spring Boot框架中完成以下Java代码
public String index(Model model) { Map<String, Object> dashboardMap = xxlJobService.dashboardInfo(); model.addAllAttributes(dashboardMap); return "index"; } @RequestMapping("/chartInfo") @ResponseBody public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) { ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate); return chartInfo; } @RequestMapping("/toLogin") @PermissionLimit(limit=false) public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) { if (loginService.ifLogin(request, response) != null) { modelAndView.setView(new RedirectView("/",true,false)); return modelAndView; } return new ModelAndView("login"); } @RequestMapping(value="login", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){ boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false; return loginService.login(request, response, userName, password, ifRem); }
@RequestMapping(value="logout", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ return loginService.logout(request, response); } @RequestMapping("/help") public String help() { /*if (!PermissionInterceptor.ifLogin(request)) { return "redirect:/toLogin"; }*/ return "help"; } @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\IndexController.java
2
请完成以下Spring Boot application配置
#this property file will have to be loaded explicitly as this is not a Spring Boot project # Gmail SMTP spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=username spring.mail.password=password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=false # Amazon SES SMTP #spring.mail.host=email-smtp.us-west-2.amazonaws.com #spring.mail.username=username #spring.mail.password=password #spring.mail.properties.mail.transport.protocol=smtp #spring.mail.properties.mail.smtp.port=25 #spring.mail.properties.mail.smtp.auth=true #spring.mail.properties.mail.smtp.starttls.enable=true #spring.mail.prop
erties.mail.smtp.starttls.required=true # path to attachment file attachment.invoice=path_to_file # # Mail templates # # Templates directory inside main/resources or absolute filesystem path spring.mail.templates.path=mail-templates #spring.mail.templates.path=/path/to/templates
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> { private final OidcUserService oidcUserService = new OidcUserService(); private final DefaultOAuth2UserService defaultOAuth2UserService = new DefaultOAuth2UserService(); @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { if (isOidcProvider(userRequest.getClientRegistration())) { // 尝试获取 OIDC ID Token OidcIdToken idToken = extractOidcIdToken(userRequest); OidcUserRequest oidcUserRequest = new OidcUserRequest( userRequest.getClientRegistration(), userRequest.getAccessToken(), idToken); return oidcUserService.loadUser(oidcUserRequest); } else { return defaultOAuth2UserService.loadUser(userRequest); } } private boolean isOidcProvider(ClientRegistration clientRegistration) { return clientRegistration.getProviderDetails() .getConfigurationMetadata() .containsKey("userinfo_endpoint"); }
private OidcIdToken extractOidcIdToken(OAuth2UserRequest userRequest) { // 从 userRequest 中获取 OIDC ID Token,这里假设它已经包含在 access token response 的附加参数中 // 如果不存在,则需要处理这个情况,可能是返回 null 或抛出异常 Map<String, Object> additionalParameters = userRequest.getAdditionalParameters(); Object idTokenObj = additionalParameters.get("id_token"); if (idTokenObj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> idTokenClaims = (Map<String, Object>) idTokenObj; return new OidcIdToken(userRequest.getAccessToken().getTokenValue(), userRequest.getAccessToken().getIssuedAt(), userRequest.getAccessToken().getExpiresAt(), idTokenClaims); } throw new OAuth2AuthenticationException(new OAuth2Error("invalid_id_token"), "Invalid or missing ID token"); } }
repos\springboot-demo-master\keycloak\src\main\java\com\et\service\CustomOAuth2UserService.java
2
请完成以下Java代码
public Builder setTrxName(@Nullable final String trxName) { this.trxName = trxName; return this; } @Nullable public String getTrxName() { return trxName; } /** * @param editable True, if tree can be modified * - includes inactive and empty summary nodes */ public Builder setEditable(final boolean editable) { this.editable = editable; return this; } public boolean isEditable() { return editable; } /** * @param clientTree the tree is displayed on the java client (not on web) */ public Builder setClientTree(final boolean clientTree) { this.clientTree = clientTree; return this; } public boolean isClientTree() { return clientTree;
} public Builder setAllNodes(final boolean allNodes) { this.allNodes = allNodes; return this; } public boolean isAllNodes() { return allNodes; } public Builder setLanguage(final String adLanguage) { this.adLanguage = adLanguage; return this; } private String getAD_Language() { if (adLanguage == null) { return Env.getADLanguageOrBaseLanguage(getCtx()); } return adLanguage; } } } // MTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree.java
1
请完成以下Java代码
static void validate () { String sql = "SELECT AD_Table_ID, TableName FROM AD_Table WHERE IsView='N' ORDER BY TableName"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); rs = pstmt.executeQuery (); while (rs.next ()) { validate (rs.getInt(1), rs.getString(2)); } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } // validate /** * Validate all tables for AD_Table/Record_ID relationships * @param AD_Table_ID table */ static void validate (int AD_Table_ID) { MTable table = new MTable(Env.getCtx(), AD_Table_ID, null); if (table.isView()) {
log.warn("Ignored - View " + table.getTableName()); } else { validate (table.getAD_Table_ID(), table.getTableName()); } } // validate /** * Validate Table for Table/Record * @param AD_Table_ID table * @param TableName Name */ static private void validate (int AD_Table_ID, String TableName) { for (int i = 0; i < s_cascades.length; i++) { final StringBuilder sql = new StringBuilder("DELETE FROM ") .append(s_cascadeNames[i]) .append(" WHERE AD_Table_ID=").append(AD_Table_ID) .append(" AND Record_ID NOT IN (SELECT ") .append(TableName).append("_ID FROM ").append(TableName).append(")"); int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), null); if (no > 0) { log.info(s_cascadeNames[i] + " (" + AD_Table_ID + "/" + TableName + ") Invalid #" + no); } } } // validate } // PO_Record
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO_Record.java
1
请完成以下Java代码
public final String setTrxName(final String trxName) { final String trxNameOld = _trxName; _trxName = trxName; return trxNameOld; } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { return getWrapper(model).isOldValues(); } public Evaluatee2 asEvaluatee() { return new Evaluatee2() { @Override public String get_ValueAsString(final String variableName) { if (!has_Variable(variableName)) { return ""; } final Object value = POJOWrapper.this.getValuesMap().get(variableName); return value == null ? "" : value.toString(); } @Override public boolean has_Variable(final String variableName) { return POJOWrapper.this.hasColumnName(variableName); } @Override public String get_ValueOldAsString(final String variableName) {
throw new UnsupportedOperationException("not implemented"); } }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; } POJOModelInternalAccessor _modelInternalAccessor = null; public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderReturnReasonService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询退货原因") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrderReturnReason>> list(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<OmsOrderReturnReason> reasonList = orderReturnReasonService.list(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(reasonList)); } @ApiOperation("获取单个退货原因详情信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderReturnReason> getItem(@PathVariable Long id) { OmsOrderReturnReason reason = orderReturnReasonService.getItem(id);
return CommonResult.success(reason); } @ApiOperation("修改退货原因启用状态") @RequestMapping(value = "/update/status", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@RequestParam(value = "status") Integer status, @RequestParam("ids") List<Long> ids) { int count = orderReturnReasonService.updateStatus(ids, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderReturnReasonController.java
2
请完成以下Java代码
public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Long getStartDateMilliseconds() { return startDateMilliseconds; } public Long getEndDateMilliseconds() { return endDateMilliseconds; } public String getName() { return name; } public String getReporter() { return reporter; } public Long getInterval() { if (interval == null) { return DEFAULT_SELECT_INTERVAL; } return interval; } @Override public int getMaxResults() { if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) { return DEFAULT_LIMIT_SELECT_INTERVAL; }
return super.getMaxResults(); } protected class MetricsQueryIntervalCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectInterval(metricsQuery); } } protected class MetricsQuerySumCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectSum(metricsQuery); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
1
请完成以下Java代码
public void setVariableLocal(String variableName, Object value, boolean skipJavaSerializationFormatCheck) { TypedValue typedValue = Variables.untypedValue(value); setVariableLocal(variableName, typedValue, getSourceActivityVariableScope(), skipJavaSerializationFormatCheck); } @Override public void setVariableLocal(String variableName, Object value) { setVariableLocal(variableName, value, false); } @Override public void removeVariable(String variableName) { removeVariable(variableName, getSourceActivityVariableScope()); } protected void removeVariable(String variableName, AbstractVariableScope sourceActivityExecution) { if (getVariableStore().containsKey(variableName)) { removeVariableLocal(variableName, sourceActivityExecution); return; } AbstractVariableScope parentVariableScope = getParentVariableScope(); if (parentVariableScope!=null) { if (sourceActivityExecution==null) { parentVariableScope.removeVariable(variableName); } else { parentVariableScope.removeVariable(variableName, sourceActivityExecution); } } } @Override public void removeVariableLocal(String variableName) { removeVariableLocal(variableName, getSourceActivityVariableScope()); } protected AbstractVariableScope getSourceActivityVariableScope() { return this; } protected void removeVariableLocal(String variableName, AbstractVariableScope sourceActivityExecution) { if (getVariableStore().containsKey(variableName)) { CoreVariableInstance variableInstance = getVariableStore().getVariable(variableName);
invokeVariableLifecycleListenersDelete(variableInstance, sourceActivityExecution); getVariableStore().removeVariable(variableName); } } public ELContext getCachedElContext() { return cachedElContext; } public void setCachedElContext(ELContext cachedElContext) { this.cachedElContext = cachedElContext; } @Override public void dispatchEvent(VariableEvent variableEvent) { // default implementation does nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\AbstractVariableScope.java
1
请完成以下Java代码
public class MobileAppEntity extends BaseSqlEntity<MobileApp> { @Column(name = TENANT_ID_COLUMN) private UUID tenantId; @Column(name = ModelConstants.MOBILE_APP_PKG_NAME_PROPERTY) private String pkgName; @Column(name = ModelConstants.MOBILE_APP_TITLE_PROPERTY) private String title; @Column(name = ModelConstants.MOBILE_APP_APP_SECRET_PROPERTY) private String appSecret; @Enumerated(EnumType.STRING) @Column(name = ModelConstants.MOBILE_APP_PLATFORM_TYPE_PROPERTY) private PlatformType platformType; @Enumerated(EnumType.STRING) @Column(name = ModelConstants.MOBILE_APP_STATUS_PROPERTY) private MobileAppStatus status; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.MOBILE_APP_VERSION_INFO_PROPERTY) private JsonNode versionInfo; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.MOBILE_APP_STORE_INFO_PROPERTY) private JsonNode storeInfo; public MobileAppEntity() { super(); }
public MobileAppEntity(MobileApp mobile) { super(mobile); if (mobile.getTenantId() != null) { this.tenantId = mobile.getTenantId().getId(); } this.pkgName = mobile.getPkgName(); this.title = mobile.getTitle(); this.appSecret = mobile.getAppSecret(); this.platformType = mobile.getPlatformType(); this.status = mobile.getStatus(); this.versionInfo = toJson(mobile.getVersionInfo()); this.storeInfo = toJson(mobile.getStoreInfo()); } @Override public MobileApp toData() { MobileApp mobile = new MobileApp(); mobile.setId(new MobileAppId(id)); if (tenantId != null) { mobile.setTenantId(TenantId.fromUUID(tenantId)); } mobile.setCreatedTime(createdTime); mobile.setPkgName(pkgName); mobile.setTitle(title); mobile.setAppSecret(appSecret); mobile.setPlatformType(platformType); mobile.setStatus(status); mobile.setVersionInfo(versionInfo != null ? fromJson(versionInfo, MobileAppVersionInfo.class) : MOBILE_APP_VERSION_INFO_EMPTY_OBJECT); mobile.setStoreInfo(storeInfo != null ? fromJson(storeInfo, StoreInfo.class) : MOBILE_APP_STORE_INFO_EMPTY_OBJECT); return mobile; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\MobileAppEntity.java
1
请完成以下Java代码
public final AggregationKey buildAggregationKey(final I_C_Invoice_Candidate ic) { final InvoiceCandidateHeaderAggregationId headerAggregationIdOverride = InvoiceCandidateHeaderAggregationId.ofRepoIdOrNull(ic.getC_Invoice_Candidate_HeaderAggregation_Override_ID()); if (headerAggregationIdOverride != null && X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header.equals(aggregationUsageLevel)) { //An override is set, use the already calculated header aggregation key return new AggregationKey(ic.getHeaderAggregationKey()); } final IAggregationKeyBuilder<I_C_Invoice_Candidate> icAggregationKeyBuilder = getDelegate(ic); if (icAggregationKeyBuilder == null) { return AggregationKey.NULL; } return icAggregationKeyBuilder.buildAggregationKey(ic); } /** * Finds the actual {@link IAggregationKeyBuilder} to be used, based on invoice candidate's settings. * * @param ic * @return actual {@link IAggregationKeyBuilder} to be used */ protected IAggregationKeyBuilder<I_C_Invoice_Candidate> getDelegate(final I_C_Invoice_Candidate ic) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner bpartner = bpartnerDAO.getById(ic.getBill_BPartner_ID(), I_C_BPartner.class); if (bpartner == null) { return null; } final Properties ctx = InterfaceWrapperHelper.getCtx(ic); final OrderId prepayOrderId = OrderId.ofRepoIdOrNull(ic.getC_Order_ID()); if (prepayOrderId != null && Services.get(IOrderBL.class).isPrepay(prepayOrderId) && X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header.equals(aggregationUsageLevel)) { return invoiceAggregationFactory.getPrepayOrderAggregationKeyBuilder(ctx);
} final boolean isSOTrx = ic.isSOTrx(); return invoiceAggregationFactory.getAggregationKeyBuilder(ctx, bpartner, isSOTrx, aggregationUsageLevel); } @Override public final boolean isSame(final I_C_Invoice_Candidate ic1, final I_C_Invoice_Candidate ic2) { final AggregationKey aggregationKey1 = buildAggregationKey(ic1); if (aggregationKey1 == null) { return false; } final AggregationKey aggregationKey2 = buildAggregationKey(ic2); if (aggregationKey2 == null) { return false; } final boolean same = Objects.equals(aggregationKey1, aggregationKey2); return same; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ForwardingICAggregationKeyBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringCloudSQS { private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQS.class); static final String QUEUE_NAME = "spring-cloud-test-queue"; /* * CountDownLatch is added to wait for messages * during integration test */ CountDownLatch countDownLatch; public void setCountDownLatch(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; }
@Autowired QueueMessagingTemplate queueMessagingTemplate; @SqsListener(QUEUE_NAME) public void receiveMessage(String message, @Header("SenderId") String senderId) { logger.info("Received message: {}, having SenderId: {}", message, senderId); if (countDownLatch != null) { countDownLatch.countDown(); } } public void send(String queueName, Object message) { queueMessagingTemplate.convertAndSend(queueName, message); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\sqs\SpringCloudSQS.java
2
请完成以下Java代码
final public I_M_Replenish uppdateReplenish(@NonNull final I_I_Replenish importRecord) { final I_M_Replenish replenish = importRecord.getM_Replenish(); setReplenishmenttValueFields(importRecord, replenish); return replenish; } private void setReplenishmenttValueFields(@NonNull final I_I_Replenish importRecord, @NonNull final I_M_Replenish replenish) { // mandatory fields replenish.setAD_Org_ID(importRecord.getAD_Org_ID()); replenish.setM_Product_ID(importRecord.getM_Product_ID()); replenish.setM_Warehouse_ID(importRecord.getM_Warehouse_ID()); replenish.setLevel_Max(importRecord.getLevel_Max()); replenish.setLevel_Min(importRecord.getLevel_Min()); replenish.setReplenishType(importRecord.getReplenishType()); replenish.setTimeToMarket(importRecord.getTimeToMarket()); // optional fields
if (importRecord.getM_Locator_ID() > 0) { replenish.setM_Locator_ID(importRecord.getM_Locator_ID()); } if (importRecord.getC_Period_ID() > 0) { replenish.setC_Period_ID(importRecord.getC_Period_ID()); replenish.setC_Calendar_ID(getCalendar(importRecord.getC_Period())); } } private int getCalendar(final I_C_Period period) { return period.getC_Year().getC_Calendar_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishImportHelper.java
1
请完成以下Java代码
public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Product_Category_Matching_ID (final int M_Product_Category_Matching_ID) { if (M_Product_Category_Matching_ID < 1) set_Value (COLUMNNAME_M_Product_Category_Matching_ID, null); else set_Value (COLUMNNAME_M_Product_Category_Matching_ID, M_Product_Category_Matching_ID); } @Override public int getM_Product_Category_Matching_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_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 setQtyPerDelivery (final BigDecimal QtyPerDelivery) { set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery); } @Override public BigDecimal getQtyPerDelivery() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java
1
请完成以下Java代码
public String getFillValue() { return "#585858"; } @Override public String getStrokeValue() { return "none"; } @Override public String getStrokeWidth() { return "1"; } @Override public String getDValue() { return " m0 1.5 l0 13 l17 0 l0 -13 z M1.5 3 L6 7.5 L1.5 12 z M3.5 3 L13.5 3 L8.5 8 z m12 0 l0 9 l-4.5 -4.5 z M7 8.5 L8.5 10 L10 8.5 L14.5 13 L2.5 13 z"; } public void drawIcon( final int imageX, final int imageY, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 1) + "," + (imageY - 2) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); pathTag.setAttributeNS(null, "stroke-widthh", this.getStrokeWidth()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag); } @Override public String getAnchorValue() {
return null; } @Override public String getStyleValue() { return null; } @Override public Integer getWidth() { return 17; } @Override public Integer getHeight() { return 13; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\MessageIconType.java
1
请在Spring Boot框架中完成以下Java代码
private Map<String, DataSource> dataSourceMap() { Map<String, DataSource> dataSourceMap = new HashMap<>(16); // 配置第一个数据源 HikariDataSource ds0 = new HikariDataSource(); ds0.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds0.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds0.setUsername("root"); ds0.setPassword("root"); // 配置第二个数据源 HikariDataSource ds1 = new HikariDataSource(); ds1.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds1.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo-2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); ds1.setUsername("root");
ds1.setPassword("root"); dataSourceMap.put("ds0", ds0); dataSourceMap.put("ds1", ds1); return dataSourceMap; } /** * 自定义主键生成器 */ private KeyGenerator customKeyGenerator() { return new CustomSnowflakeKeyGenerator(snowflake); } }
repos\spring-boot-demo-master\demo-sharding-jdbc\src\main\java\com\xkcoding\sharding\jdbc\config\DataSourceShardingConfig.java
2
请完成以下Java代码
private void writePreamble(PrintWriter writer) { DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); writer.println(dateFormat.format(LocalDateTime.now())); RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); writer.printf("Full thread dump %s (%s %s):%n", runtime.getVmName(), runtime.getVmVersion(), System.getProperty("java.vm.info")); writer.println(); } private void writeThread(PrintWriter writer, ThreadInfo info) { writer.printf("\"%s\" - Thread t@%d%n", info.getThreadName(), info.getThreadId()); writer.printf(" %s: %s%n", Thread.State.class.getCanonicalName(), info.getThreadState()); writeStackTrace(writer, info, info.getLockedMonitors()); writer.println(); writeLockedOwnableSynchronizers(writer, info); writer.println(); } private void writeStackTrace(PrintWriter writer, ThreadInfo info, MonitorInfo[] lockedMonitors) { int depth = 0; for (StackTraceElement element : info.getStackTrace()) { writeStackTraceElement(writer, element, info, lockedMonitorsForDepth(lockedMonitors, depth), depth == 0); depth++; } } private List<MonitorInfo> lockedMonitorsForDepth(MonitorInfo[] lockedMonitors, int depth) { return Stream.of(lockedMonitors).filter((candidate) -> candidate.getLockedStackDepth() == depth).toList(); } private void writeStackTraceElement(PrintWriter writer, StackTraceElement element, ThreadInfo info, List<MonitorInfo> lockedMonitors, boolean firstElement) { writer.printf("\tat %s%n", element.toString()); LockInfo lockInfo = info.getLockInfo(); if (firstElement && lockInfo != null) { if (element.getClassName().equals(Object.class.getName()) && element.getMethodName().equals("wait")) { writer.printf("\t- waiting on %s%n", format(lockInfo)); } else { String lockOwner = info.getLockOwnerName(); if (lockOwner != null) { writer.printf("\t- waiting to lock %s owned by \"%s\" t@%d%n", format(lockInfo), lockOwner, info.getLockOwnerId()); } else { writer.printf("\t- parking to wait for %s%n", format(lockInfo)); } } } writeMonitors(writer, lockedMonitors);
} private String format(LockInfo lockInfo) { return String.format("<%x> (a %s)", lockInfo.getIdentityHashCode(), lockInfo.getClassName()); } private void writeMonitors(PrintWriter writer, List<MonitorInfo> lockedMonitorsAtCurrentDepth) { for (MonitorInfo lockedMonitor : lockedMonitorsAtCurrentDepth) { writer.printf("\t- locked %s%n", format(lockedMonitor)); } } private void writeLockedOwnableSynchronizers(PrintWriter writer, ThreadInfo info) { writer.println(" Locked ownable synchronizers:"); LockInfo[] lockedSynchronizers = info.getLockedSynchronizers(); if (lockedSynchronizers == null || lockedSynchronizers.length == 0) { writer.println("\t- None"); } else { for (LockInfo lockedSynchronizer : lockedSynchronizers) { writer.printf("\t- Locked %s%n", format(lockedSynchronizer)); } } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\PlainTextThreadDumpFormatter.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public void setRoot(String root) { this.root = root; } /** * Username (DN) of the "manager" user identity (i.e. "uid=admin,ou=system") which * will be used to authenticate to an LDAP server. If omitted, anonymous access will * be used. * @param managerDn the username (DN) of the "manager" user identity used to * authenticate to a LDAP server. */ public void setManagerDn(String managerDn) { this.managerDn = managerDn; } /** * The password for the manager DN. This is required if the * {@link #setManagerDn(String)} is specified. * @param managerPassword password for the manager DN */ public void setManagerPassword(String managerPassword) { this.managerPassword = managerPassword; } @Override public DefaultSpringSecurityContextSource getObject() throws Exception { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } this.container = getContainer(); this.port = this.container.getPort(); DefaultSpringSecurityContextSource contextSourceFromProviderUrl = new DefaultSpringSecurityContextSource( "ldap://127.0.0.1:" + this.port + "/" + this.root); if (this.managerDn != null) { contextSourceFromProviderUrl.setUserDn(this.managerDn); if (this.managerPassword == null) { throw new IllegalStateException("managerPassword is required if managerDn is supplied"); } contextSourceFromProviderUrl.setPassword(this.managerPassword); } contextSourceFromProviderUrl.afterPropertiesSet(); return contextSourceFromProviderUrl; } @Override public Class<?> getObjectType() { return DefaultSpringSecurityContextSource.class; }
@Override public void destroy() { if (this.container instanceof Lifecycle) { ((Lifecycle) this.container).stop(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } private EmbeddedLdapServerContainer getContainer() { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif); unboundIdContainer.setApplicationContext(this.context); unboundIdContainer.setPort(getEmbeddedServerPort()); unboundIdContainer.afterPropertiesSet(); return unboundIdContainer; } private int getEmbeddedServerPort() { if (this.port == null) { this.port = getDefaultEmbeddedServerPort(); } return this.port; } private int getDefaultEmbeddedServerPort() { try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) { return serverSocket.getLocalPort(); } catch (IOException ex) { return RANDOM_PORT; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java
2
请完成以下Java代码
private String getCookieDomain(HttpServletRequest request) { String domain = oAuth2Properties.getWebClientConfiguration().getCookieDomain(); if (domain != null) { return domain; } // if not explicitly defined, use top-level domain domain = request.getServerName().toLowerCase(); // strip off leading www. if (domain.startsWith("www.")) { domain = domain.substring(4); } // if it isn't an IP address if (!isIPv4Address(domain) && !isIPv6Address(domain)) { // strip off private subdomains, leaving public TLD only String suffix = suffixMatcher.getDomainRoot(domain); if (suffix != null && !suffix.equals(domain)) { // preserve leading dot return "." + suffix; } } // no top-level domain, stick with default domain
return null; } /** * Strip our token cookies from the array. * * @param cookies the cookies we receive as input. * @return the new cookie array without our tokens. */ Cookie[] stripCookies(Cookie[] cookies) { CookieCollection cc = new CookieCollection(cookies); if (cc.removeAll(COOKIE_NAMES)) { return cc.toArray(); } return cookies; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\OAuth2CookieHelper.java
1
请完成以下Java代码
public final <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz) { final ILockCommand lockCommand = new LockCommand(this) .setOwner(LockOwner.NONE); final ImmutableList.Builder<T> lockedModelsCollector = ImmutableList.builder(); final List<T> models = query.list(clazz); if (models == null || models.isEmpty()) { return ImmutableList.of(); } for (final T model : models) { final TableRecordReference record = TableRecordReference.of(model); if (lockRecord(lockCommand, record)) { lockedModelsCollector.add(model); } } final ImmutableList<T> lockedModels = lockedModelsCollector.build(); if (lockedModels.size() != models.size()) {
logger.warn("*** retrieveAndLockMultipleRecords: not all retrieved records could be locked! expectedLockedSize: {}, actualLockedSize: {}" , models.size(), lockedModels.size()); } return lockedModels; } public <T> IQuery<T> addNotLockedClause(final IQuery<T> query) { return retrieveNotLockedQuery(query); } /** * @return <code>true</code> if the given <code>allowAdditionalLocks</code> is <code>FOR_DIFFERENT_OWNERS</code>. */ protected static boolean isAllowMultipleOwners(final AllowAdditionalLocks allowAdditionalLocks) { return allowAdditionalLocks == AllowAdditionalLocks.FOR_DIFFERENT_OWNERS; } protected abstract <T> IQuery<T> retrieveNotLockedQuery(IQuery<T> query); protected abstract String getLockedWhereClauseAllowNullLock(@NonNull final Class<?> modelClass, @NonNull final String joinColumnNameFQ, @Nullable final LockOwner lockOwner); }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\AbstractLockDatabase.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDecisionLogic(DmnDecisionLogic decisionLogic) { this.decisionLogic = decisionLogic; } public DmnDecisionLogic getDecisionLogic() { return decisionLogic; } public void setRequiredDecision(List<DmnDecision> requiredDecision) { this.requiredDecision = requiredDecision;
} @Override public Collection<DmnDecision> getRequiredDecisions() { return requiredDecision; } @Override public boolean isDecisionTable() { return decisionLogic != null && decisionLogic instanceof DmnDecisionTableImpl; } @Override public String toString() { return "DmnDecisionTableImpl{" + " key= "+ key + ", name= "+ name + ", requiredDecision=" + requiredDecision + ", decisionLogic=" + decisionLogic + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionImpl.java
1
请完成以下Java代码
public static List<EventSubscriptionEntity> collectCompensateEventSubscriptionsForActivity(ActivityExecution execution, String activityRef) { final List<EventSubscriptionEntity> eventSubscriptions = collectCompensateEventSubscriptionsForScope(execution); final String subscriptionActivityId = getSubscriptionActivityId(execution, activityRef); List<EventSubscriptionEntity> eventSubscriptionsForActivity = new ArrayList<EventSubscriptionEntity>(); for (EventSubscriptionEntity subscription : eventSubscriptions) { if (subscriptionActivityId.equals(subscription.getActivityId())) { eventSubscriptionsForActivity.add(subscription); } } return eventSubscriptionsForActivity; } public static ExecutionEntity getCompensatingExecution(EventSubscriptionEntity eventSubscription) { String configuration = eventSubscription.getConfiguration(); if (configuration != null) { return Context.getCommandContext().getExecutionManager().findExecutionById(configuration); } else { return null; } } private static String getSubscriptionActivityId(ActivityExecution execution, String activityRef) { ActivityImpl activityToCompensate = ((ExecutionEntity) execution).getProcessDefinition().findActivity(activityRef);
if (activityToCompensate.isMultiInstance()) { ActivityImpl flowScope = (ActivityImpl) activityToCompensate.getFlowScope(); return flowScope.getActivityId(); } else { ActivityImpl compensationHandler = activityToCompensate.findCompensationHandler(); if (compensationHandler != null) { return compensationHandler.getActivityId(); } else { // if activityRef = subprocess and subprocess has no compensation handler return activityRef; } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\CompensationUtil.java
1
请完成以下Java代码
public BigDecimal getSelectionColumnSeqNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override public int getSpanX() { return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请完成以下Java代码
private void assertNotOverDelivery() { Quantity qtyToDeliver = qtyToDeliverTarget; final Quantity qtyPickedPlanned = packingDAO.retrieveQtyPickedPlanned(shipmentScheduleId).orElse(null); if (qtyPickedPlanned != null) { qtyToDeliver = qtyToDeliver.subtract(qtyPickedPlanned); } if (qtyToPack.compareTo(qtyToDeliver) > 0) { throw new AdempiereException("@" + PickingConfigRepository.MSG_WEBUI_Picking_OverdeliveryNotAllowed + "@") .appendParametersToMessage() .setParameter("qtyToDeliverTarget", qtyToDeliverTarget) .setParameter("qtyPickedPlanned", qtyPickedPlanned) .setParameter("qtyToPack", qtyToPack); } } private void validateSourceHUs(@NonNull final List<HuId> sourceHUIds) { for (final HuId sourceHuId : sourceHUIds) { if (!handlingUnitsBL.isHUHierarchyCleared(sourceHuId)) { throw new AdempiereException("Non 'Cleared' HUs cannot be picked!") .appendParametersToMessage() .setParameter("M_HU_ID", sourceHuId); } } } private void assertNotAggregatingCUsToDiffOrders()
{ final OrderId pickingForOrderId = OrderId.ofRepoIdOrNull(shipmentSchedule.getC_Order_ID()); if (pickingForOrderId == null) { throw new AdempiereException("When isForbidAggCUsForDifferentOrders='Y' the pickingForOrderId must be known!") .appendParametersToMessage() .setParameter("ShipmentScheduleId", shipmentSchedule.getM_ShipmentSchedule_ID()); } final I_M_HU hu = handlingUnitsDAO.getById(packToHuId); final boolean isLoadingUnit = handlingUnitsBL.isLoadingUnit(hu); if (isLoadingUnit) { throw new AdempiereException("packToHuId cannot be an LU, as picking to unknown TU is not allowed when isForbidAggCUsForDifferentOrders='Y'"); } final ImmutableMap<HuId, ImmutableSet<OrderId>> huId2OpenPickingOrderIds = pickingCandidateService .getOpenPickingOrderIdsByHuId(ImmutableSet.of(packToHuId)); final boolean thereAreOpenPickingOrdersForHU = CollectionUtils.isNotEmpty(huId2OpenPickingOrderIds.get(packToHuId)); final boolean noneOfThePickingOrdersMatchesTheCurrentOrder = !huId2OpenPickingOrderIds.get(packToHuId).contains(pickingForOrderId); if (thereAreOpenPickingOrdersForHU && noneOfThePickingOrdersMatchesTheCurrentOrder) { throw new AdempiereException("Cannot pick to an HU with an open picking candidate pointing to a different order!") .appendParametersToMessage() .setParameter("shipmentScheduleId", shipmentSchedule.getM_ShipmentSchedule_ID()) .setParameter("huId", packToHuId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\AddQtyToHUCommand.java
1
请完成以下Java代码
public void addStorageRecord(final IStorageRecord storageRecord) { Check.assumeNotNull(storageRecord, "storageRecord not null"); // TODO: validate if applies final BigDecimal storageQty = storageRecord.getQtyOnHand(); qty = qty.add(storageQty); } public String getSummary() { return "@M_Locator_ID@:" + locator.getValue() + " - " + (rawMaterialsWarehouse == null ? "?" : rawMaterialsWarehouse.getName()) + ", @M_Product_ID@:" + attributeSetInstanceAware.getM_Product().getName() + ", @Qty@:" + qty + " " + uom.getUOMSymbol(); } public boolean isValid() { loadIfNeeded(); return notValidReasons.isEmpty(); } public String getNotValidReasons() { return StringUtils.toString(notValidReasons, "; "); } public IAttributeSetInstanceAware getM_Product() { return attributeSetInstanceAware; } public I_C_UOM getC_UOM() { return uom; } public BigDecimal getQty() { return qty; } public Timestamp getDateOrdered() { return dateOrdered; } /** * @return locator where Quantity currently is */ public I_M_Locator getM_Locator() { return locator; } public DistributionNetworkLine getDD_NetworkDistributionLine() { loadIfNeeded(); return networkLine; }
public ResourceId getRawMaterialsPlantId() { loadIfNeeded(); return rawMaterialsPlantId; } public I_M_Warehouse getRawMaterialsWarehouse() { loadIfNeeded(); return rawMaterialsWarehouse; } public I_M_Locator getRawMaterialsLocator() { loadIfNeeded(); return rawMaterialsLocator; } public OrgId getOrgId() { loadIfNeeded(); return orgId; } public BPartnerLocationId getOrgBPLocationId() { loadIfNeeded(); return orgBPLocationId; } public UserId getPlannerId() { loadIfNeeded(); return productPlanning == null ? null : productPlanning.getPlannerId(); } public WarehouseId getInTransitWarehouseId() { loadIfNeeded(); return inTransitWarehouseId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\RawMaterialsReturnDDOrderLineCandidate.java
1
请完成以下Java代码
private int retrieveRecordId(@NonNull final TableAndLookupKey key) { final POInfo poInfo = POInfo.getPOInfo(key.getAdTableId()); final String lookupKey = key.getLookupKey(); int recordId = retrieveRecordIdByExternalId(poInfo, lookupKey); if (recordId < 0) { recordId = retrieveRecordIdByValue(poInfo, lookupKey); } if (recordId < 0) { throw new AdempiereException("@NotFound@ @Record_ID@: " + key); } return recordId; } private int retrieveRecordIdByExternalId(@NonNull final POInfo poInfo, @NonNull final String externalId) { if (!poInfo.hasColumnName(COLUMNNAME_ExternalId)) { return -1; } final String tableName = poInfo.getTableName(); final String keyColumnName = poInfo.getKeyColumnName(); if (keyColumnName == null) { throw new AdempiereException("No key column found: " + tableName); } final String sql = "SELECT " + keyColumnName + " FROM " + tableName + " WHERE " + I_I_DataEntry_Record.COLUMNNAME_ExternalId + "=?" + " ORDER BY " + keyColumnName; final int recordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, externalId); return recordId; } private int retrieveRecordIdByValue(@NonNull final POInfo poInfo, @NonNull final String value) { if (!poInfo.hasColumnName(COLUMNNAME_Value)) { return -1; } final String tableName = poInfo.getTableName(); final String keyColumnName = poInfo.getKeyColumnName(); if (keyColumnName == null) { throw new AdempiereException("No key column found: " + tableName); }
final String sql = "SELECT " + keyColumnName + " FROM " + tableName + " WHERE " + COLUMNNAME_Value + "=?" + " ORDER BY " + keyColumnName; final int recordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, value); return recordId; } @Value private static class TableAndLookupKey { @NonNull AdTableId adTableId; @NonNull String lookupKey; private TableAndLookupKey( @NonNull final AdTableId adTableId, @NonNull final String lookupKey) { Check.assumeNotEmpty(lookupKey, "lookupKey is not empty"); this.adTableId = adTableId; this.lookupKey = lookupKey.trim(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\RecordIdLookup.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceCandidateId implements RepoIdAware { public static InvoiceCandidateId cast(@Nullable final RepoIdAware repoIdAware) { return (InvoiceCandidateId)repoIdAware; } @JsonCreator public static InvoiceCandidateId ofRepoId(final int repoId) { return new InvoiceCandidateId(repoId); } public static InvoiceCandidateId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; }
int repoId; private InvoiceCandidateId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Invoice_Candidate_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(final InvoiceCandidateId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\InvoiceCandidateId.java
2
请完成以下Java代码
private void processLinkRequestForHU(@NonNull final I_M_HU hu, @NonNull final MTLinkRequest request) { final I_M_Material_Tracking materialTracking = request.getMaterialTrackingRecord(); // // update the HU itself { final IHUMaterialTrackingBL huMaterialTrackingBL = Services.get(IHUMaterialTrackingBL.class); huMaterialTrackingBL.updateHUAttributeRecursive(hu, materialTracking, null); // update all HUs, no matter which state } // // check if the HU is assigned to a PP_Order and also update that PP_Order's material tracking reference { final ILoggable loggable = Loggables.get(); final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class); final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class); final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final IHUPPOrderMaterialTrackingBL huPPOrderMaterialTrackingBL = Services.get(IHUPPOrderMaterialTrackingBL.class); final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(Env.getCtx(), ClientAndOrgId.ofClientAndOrg(hu.getAD_Client_ID(), hu.getAD_Org_ID())); final I_M_Material_Tracking previousMaterialTrackingRecord = huPPOrderMaterialTrackingBL.extractMaterialTrackingIfAny(huContext, hu); final MTLinkRequestBuilder requestBuilder = request .toBuilder() .ifModelAlreadyLinked(IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS); if (previousMaterialTrackingRecord != null) {
requestBuilder.previousMaterialTrackingId(previousMaterialTrackingRecord.getM_Material_Tracking_ID()); } final List<I_PP_Cost_Collector> costCollectors = huAssignmentDAO.retrieveModelsForHU(hu, I_PP_Cost_Collector.class); final Map<Integer, I_PP_Order> id2pporder = new HashMap<>(); for (final I_PP_Cost_Collector costCollector : costCollectors) { if (costCollector.getPP_Order_ID() <= 0) { continue; // this might never be the case but I'm not well versed with such stuff } id2pporder.put(costCollector.getPP_Order_ID(), costCollector.getPP_Order()); } for (final I_PP_Order ppOrder : id2pporder.values()) { materialTrackingBL.linkModelToMaterialTracking(requestBuilder.model(ppOrder).build()); final String msg = "Updated M_Material_Tracking_Ref for PP_Order " + ppOrder + " of M_HU " + hu; logger.debug(msg); loggable.addLog(msg); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\HUDocumentLineLineMaterialTrackingListener.java
1
请完成以下Java代码
public final class CompositeCalloutProvider implements ICalloutProvider { /** * Compose given providers. * * @param provider1 * @param provider2 * @return composed provider / provider1 / provider2 / {@link NullCalloutProvider}; never returns null */ public static ICalloutProvider compose(@Nullable final ICalloutProvider provider1, @Nullable final ICalloutProvider provider2) { if (NullCalloutProvider.isNull(provider1)) { return NullCalloutProvider.isNull(provider2) ? NullCalloutProvider.instance : provider2; } if (provider1 instanceof CompositeCalloutProvider) { return ((CompositeCalloutProvider)provider1).compose(provider2); } if(NullCalloutProvider.isNull(provider2)) { // at this point, we assume provider1 is not null return provider1; } // Avoid duplicates // (at this point we assume both providers are not null) if(provider1.equals(provider2)) { return provider1; } return new CompositeCalloutProvider(ImmutableList.of(provider1, provider2)); } private final ImmutableList<ICalloutProvider> providers; private CompositeCalloutProvider(final ImmutableList<ICalloutProvider> providers) { super(); this.providers = providers; } @Override public String toString() { return MoreObjects.toStringHelper("composite") .addValue(providers) .toString(); } public List<ICalloutProvider> getProvidersList() { return providers; }
/** * Compose this provider with the given one and returns a new instance which will contain the given one too. * * @param provider * @return new composite containing the given provider too */ private CompositeCalloutProvider compose(final ICalloutProvider provider) { if (NullCalloutProvider.isNull(provider)) { return this; } if (providers.contains(provider)) { return this; } final ImmutableList<ICalloutProvider> providersList = ImmutableList.<ICalloutProvider> builder() .addAll(providers) .add(provider) .build(); return new CompositeCalloutProvider(providersList); } @Override public TableCalloutsMap getCallouts(final Properties ctx, final String tableName) { final TableCalloutsMap.Builder resultBuilder = TableCalloutsMap.builder(); for (final ICalloutProvider provider : providers) { final TableCalloutsMap callouts = provider.getCallouts(ctx, tableName); resultBuilder.putAll(callouts); } return resultBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\CompositeCalloutProvider.java
1
请完成以下Spring Boot application配置
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/javastack username: root password: 12345
678 jpa: hibernate: ddl-auto: update show-sql: true
repos\spring-boot-best-practice-master\spring-boot-jpa\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class TodosController { private static final String DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_VALUE; private final TodosService service; // Mapping zwischen den Schichten private final TodoDtoMapper mapper; @GetMapping(value = {"/name"},produces = DEFAULT_MEDIA_TYPE) public List<String> findAllName(){ return List.of("Hello", "World"); } @GetMapping(produces = DEFAULT_MEDIA_TYPE) public Collection<TodoResponseDto> findAll() { return service.findAll().stream() .map(mapper::map) .collect(Collectors.toList()); } @GetMapping(value = "/{id}", produces = DEFAULT_MEDIA_TYPE) public TodoResponseDto findById( @PathVariable("id") final Long id ) { // Action return service.findById(id) // .map(mapper::map) // map to dto .orElseThrow(NotFoundException::new); } @PostMapping(consumes = DEFAULT_MEDIA_TYPE) public ResponseEntity<TodoResponseDto> create(final @Valid @RequestBody TodoRequestDto item) { // Action final var todo = mapper.map(item, null); final var newTodo = service.create(todo); final var result = mapper.map(newTodo); // Response final URI locationHeader = linkTo(methodOn(TodosController.class).findById(result.getId())).toUri(); // HATEOAS return ResponseEntity.created(locationHeader).body(result);
} @PutMapping(value = "{id}", consumes = DEFAULT_MEDIA_TYPE) @ResponseStatus(NO_CONTENT) public void update( @PathVariable("id") final Long id, @Valid @RequestBody final TodoRequestDto item ) { service.update(mapper.map(item, id)); } @DeleteMapping("/{id}") @ResponseStatus(NO_CONTENT) public void delete( @PathVariable("id") final Long id ) { service.delete(id); } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\sample\boundary\TodosController.java
2
请完成以下Java代码
public @Nullable URL findResource(String name) { return null; } @Override public Enumeration<URL> findResources(String name) throws IOException { return Collections.emptyEnumeration(); } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) { Class<?> result = findExistingLoadedClass(name); result = (result != null) ? result : doLoadClass(name); if (result == null) { throw new ClassNotFoundException(name); } return resolveIfNecessary(result, resolve); } } private @Nullable Class<?> findExistingLoadedClass(String name) { Class<?> resultClass = findLoadedClass0(name); resultClass = (resultClass != null || JreCompat.isGraalAvailable()) ? resultClass : findLoadedClass(name); return resultClass; } private @Nullable Class<?> doLoadClass(String name) { if ((this.delegate || filter(name, true))) { Class<?> result = loadFromParent(name); return (result != null) ? result : findClassIgnoringNotFound(name); } Class<?> result = findClassIgnoringNotFound(name); return (result != null) ? result : loadFromParent(name); } private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) { if (resolve) { resolveClass(resultClass); } return (resultClass); } @Override protected void addURL(URL url) { // Ignore URLs added by the Tomcat 8 implementation (see gh-919)
if (logger.isTraceEnabled()) { logger.trace("Ignoring request to add " + url + " to the tomcat classloader"); } } private @Nullable Class<?> loadFromParent(String name) { if (this.parent == null) { return null; } try { return Class.forName(name, false, this.parent); } catch (ClassNotFoundException ex) { return null; } } private @Nullable Class<?> findClassIgnoringNotFound(String name) { try { return findClass(name); } catch (ClassNotFoundException ex) { return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java
1
请完成以下Java代码
public int getM_LotCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lot. @param M_Lot_ID Product Lot Definition */ public void setM_Lot_ID (int M_Lot_ID) { if (M_Lot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Lot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Lot_ID, Integer.valueOf(M_Lot_ID)); } /** Get Lot. @return Product Lot Definition */ public int getM_Lot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Lot_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_Product_ID())); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Lot.java
1
请完成以下Java代码
private void listAvailableProcesses() { Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10)); logger.info("> Available Process definitions: " + processDefinitionPage.getTotalItems()); for (ProcessDefinition pd : processDefinitionPage.getContent()) { logger.info("\t > Process definition: " + pd); } } @Bean("Movies.getMovieDesc") public Connector getMovieDesc() { return getConnector(); } @Bean("MoviesWithUUIDs.getMovieDesc") public Connector getMovieDescUUIDs() { return getConnector(); } private Connector getConnector() { return integrationContext -> { Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
logger.info(">>inbound: " + inBoundVariables); integrationContext.addOutBoundVariable( "movieDescription", "The Lord of the Rings is an epic high fantasy novel written by English author and scholar J. R. R. Tolkien" ); return integrationContext; }; } @Bean public VariableEventListener<VariableCreatedEvent> variableCreatedEventListener() { return variableCreatedEvent -> variableCreatedEvents.add(variableCreatedEvent); } @Bean public ProcessRuntimeEventListener<ProcessCompletedEvent> processCompletedEventListener() { return processCompletedEvent -> processCompletedEvents.add(processCompletedEvent); } }
repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplication.java
1
请完成以下Java代码
public boolean add(T t) { getDomElement().appendChild(t.getDomElement()); return true; } public boolean remove(Object o) { ModelUtil.ensureInstanceOf(o, BpmnModelElementInstance.class); return getDomElement().removeChild(((BpmnModelElementInstance) o).getDomElement()); } public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!contains(o)) { return false; } } return true; } public boolean addAll(Collection<? extends T> c) { for (T element : c) { add(element); } return true; } public boolean removeAll(Collection<?> c) { boolean result = false; for (Object o : c) {
result |= remove(o); } return result; } public boolean retainAll(Collection<?> c) { throw new UnsupportedModelOperationException("retainAll()", "not implemented"); } public void clear() { DomElement domElement = getDomElement(); List<DomElement> childElements = domElement.getChildElements(); for (DomElement childElement : childElements) { domElement.removeChild(childElement); } } }; } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaListImpl.java
1
请完成以下Java代码
public HistoricBatchQuery createHistoricBatchQuery() { return new HistoricBatchQueryImpl(commandExecutor); } public void deleteHistoricBatch(String batchId) { commandExecutor.execute(new DeleteHistoricBatchCmd(batchId)); } @Override public HistoricDecisionInstanceStatisticsQuery createHistoricDecisionInstanceStatisticsQuery(String decisionRequirementsDefinitionId) { return new HistoricDecisionInstanceStatisticsQueryImpl(decisionRequirementsDefinitionId, commandExecutor); } @Override public HistoricExternalTaskLogQuery createHistoricExternalTaskLogQuery() { return new HistoricExternalTaskLogQueryImpl(commandExecutor); } @Override public String getHistoricExternalTaskLogErrorDetails(String historicExternalTaskLogId) { return commandExecutor.execute(new GetHistoricExternalTaskLogErrorDetailsCmd(historicExternalTaskLogId)); } public SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder setRemovalTimeToHistoricProcessInstances() { return new SetRemovalTimeToHistoricProcessInstancesBuilderImpl(commandExecutor);
} public SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder setRemovalTimeToHistoricDecisionInstances() { return new SetRemovalTimeToHistoricDecisionInstancesBuilderImpl(commandExecutor); } public SetRemovalTimeSelectModeForHistoricBatchesBuilder setRemovalTimeToHistoricBatches() { return new SetRemovalTimeToHistoricBatchesBuilderImpl(commandExecutor); } public void setAnnotationForOperationLogById(String operationId, String annotation) { commandExecutor.execute(new SetAnnotationForOperationLog(operationId, annotation)); } public void clearAnnotationForOperationLogById(String operationId) { commandExecutor.execute(new SetAnnotationForOperationLog(operationId, null)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryServiceImpl.java
1
请完成以下Java代码
public UserOperationLogQuery afterTimestamp(Date after) { this.timestampAfter = after; return this; } public UserOperationLogQuery beforeTimestamp(Date before) { this.timestampBefore = before; return this; } public UserOperationLogQuery orderByTimestamp() { return orderBy(OperationLogQueryProperty.TIMESTAMP); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet;
} public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请完成以下Java代码
private static String getNameSpaceURI(@NonNull final XMLStreamReader reader) throws XMLStreamException { while (reader.hasNext()) { int event = reader.next(); if (XMLStreamConstants.START_ELEMENT == event && reader.getNamespaceCount() > 0) { for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) { final String nsId = reader.getNamespaceURI(nsIndex); if (nsId.startsWith("urn:iso:std:iso:20022:tech:xsd")) { return nsId; } } } } return null; } @Override public ESRStatement importData() { XMLStreamReader xsr = null; try { final XMLInputFactory xif = XMLInputFactory.newInstance(); xsr = xif.createXMLStreamReader(input); // https://github.com/metasfresh/metasfresh/issues/1903 // use a delegate to make sure that the unmarshaller won't refuse camt.054.001.04 and amt.054.001.05 final MultiVersionStreamReaderDelegate mxsr = new MultiVersionStreamReaderDelegate(xsr); if (isVersion2Schema(getNameSpaceURI(mxsr))) { return importCamt54v02(mxsr); } else { return importCamt54v06(mxsr); } } catch (final XMLStreamException e) { throw AdempiereException.wrapIfNeeded(e); } finally { closeXmlReaderAndInputStream(xsr); } } private ESRStatement importCamt54v02(final MultiVersionStreamReaderDelegate mxsr) { final BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = ESRDataImporterCamt54v02.loadXML(mxsr); if (bkToCstmrDbtCdtNtfctn.getGrpHdr() != null && bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf() != null) { Loggables.withLogger(logger, Level.INFO).addLog("The given input is a test file: bkToCstmrDbtCdtNtfctn/grpHdr/addtlInf={}", bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf()); } return ESRDataImporterCamt54v02.builder() .bankAccountCurrencyCode(bankAccountCurrencyCode) .adLanguage(adLanguage)
.build() .createESRStatement(bkToCstmrDbtCdtNtfctn); } private ESRStatement importCamt54v06(final MultiVersionStreamReaderDelegate mxsr) { final BankToCustomerDebitCreditNotificationV06 bkToCstmrDbtCdtNtfctn = ESRDataImporterCamt54v06.loadXML(mxsr); if (bkToCstmrDbtCdtNtfctn.getGrpHdr() != null && bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf() != null) { Loggables.withLogger(logger, Level.INFO).addLog("The given input is a test file: bkToCstmrDbtCdtNtfctn/grpHdr/addtlInf={}", bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf()); } return ESRDataImporterCamt54v06.builder() .bankAccountCurrencyCode(bankAccountCurrencyCode) .adLanguage(adLanguage) .build() .createESRStatement(bkToCstmrDbtCdtNtfctn); } private void closeXmlReaderAndInputStream(@Nullable final XMLStreamReader xsr) { try { if (xsr != null) { xsr.close(); } input.close(); } catch (XMLStreamException | IOException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\camt54\ESRDataImporterCamt54.java
1
请完成以下Java代码
public BigDecimal getBenchmarkValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_BenchmarkValue); if (bd == null) return Env.ZERO; return bd; } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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 Benchmark Data. @param PA_BenchmarkData_ID Performance Benchmark Data Point */ public void setPA_BenchmarkData_ID (int PA_BenchmarkData_ID) { if (PA_BenchmarkData_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, Integer.valueOf(PA_BenchmarkData_ID)); } /** Get Benchmark Data. @return Performance Benchmark Data Point
*/ public int getPA_BenchmarkData_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_BenchmarkData_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Benchmark getPA_Benchmark() throws RuntimeException { return (I_PA_Benchmark)MTable.get(getCtx(), I_PA_Benchmark.Table_Name) .getPO(getPA_Benchmark_ID(), get_TrxName()); } /** Set Benchmark. @param PA_Benchmark_ID Performance Benchmark */ public void setPA_Benchmark_ID (int PA_Benchmark_ID) { if (PA_Benchmark_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID)); } /** Get Benchmark. @return Performance Benchmark */ public int getPA_Benchmark_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_BenchmarkData.java
1
请完成以下Java代码
public void setDetailHtml(String detailHtml) { this.detailHtml = detailHtml; } public String getDetailMobileHtml() { return detailMobileHtml; } public void setDetailMobileHtml(String detailMobileHtml) { this.detailMobileHtml = detailMobileHtml; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", brandId=").append(brandId); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", feightTemplateId=").append(feightTemplateId); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", pic=").append(pic); sb.append(", productSn=").append(productSn); sb.append(", deleteStatus=").append(deleteStatus); sb.append(", publishStatus=").append(publishStatus); sb.append(", newStatus=").append(newStatus); sb.append(", recommandStatus=").append(recommandStatus); sb.append(", verifyStatus=").append(verifyStatus); sb.append(", sort=").append(sort); sb.append(", sale=").append(sale); sb.append(", price=").append(price); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", giftGrowth=").append(giftGrowth); sb.append(", giftPoint=").append(giftPoint); sb.append(", usePointLimit=").append(usePointLimit); sb.append(", subTitle=").append(subTitle); sb.append(", originalPrice=").append(originalPrice); sb.append(", stock=").append(stock); sb.append(", lowStock=").append(lowStock); sb.append(", unit=").append(unit); sb.append(", weight=").append(weight);
sb.append(", previewStatus=").append(previewStatus); sb.append(", serviceIds=").append(serviceIds); sb.append(", keywords=").append(keywords); sb.append(", note=").append(note); sb.append(", albumPics=").append(albumPics); sb.append(", detailTitle=").append(detailTitle); sb.append(", promotionStartTime=").append(promotionStartTime); sb.append(", promotionEndTime=").append(promotionEndTime); sb.append(", promotionPerLimit=").append(promotionPerLimit); sb.append(", promotionType=").append(promotionType); sb.append(", brandName=").append(brandName); sb.append(", productCategoryName=").append(productCategoryName); sb.append(", description=").append(description); sb.append(", detailDesc=").append(detailDesc); sb.append(", detailHtml=").append(detailHtml); sb.append(", detailMobileHtml=").append(detailMobileHtml); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProduct.java
1
请完成以下Java代码
public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return !locked; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return enabled; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; }
public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } // public Boolean getEnabled() { // return enabled; // } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
repos\springboot-demo-master\security\src\main\java\com\et\security\entity\User.java
1
请完成以下Java代码
public String getUsername() { return username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getWechatId() { return wechatId; } public void setWechatId(String wechatId) { this.wechatId = wechatId; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill;
} public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public Integer getLoginCount() { return loginCount; } public void setLoginCount(Integer loginCount) { this.loginCount = loginCount; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } @Override public String toString() { return "User{" + "id=" + id + ", cnname=" + cnname + ", username=" + username + ", password=" + password + ", email=" + email + ", telephone=" + telephone + ", mobilePhone=" + mobilePhone + ", wechatId=" + wechatId + ", skill=" + skill + ", departmentId=" + departmentId + ", loginCount=" + loginCount + '}'; } }
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\User.java
1
请完成以下Java代码
public class BalanceType12 { @XmlElement(name = "CdOrPrtry", required = true) protected BalanceType5Choice cdOrPrtry; @XmlElement(name = "SubTp") protected BalanceSubType1Choice subTp; /** * Gets the value of the cdOrPrtry property. * * @return * possible object is * {@link BalanceType5Choice } * */ public BalanceType5Choice getCdOrPrtry() { return cdOrPrtry; } /** * Sets the value of the cdOrPrtry property. * * @param value * allowed object is * {@link BalanceType5Choice } * */ public void setCdOrPrtry(BalanceType5Choice value) { this.cdOrPrtry = value; }
/** * Gets the value of the subTp property. * * @return * possible object is * {@link BalanceSubType1Choice } * */ public BalanceSubType1Choice getSubTp() { return subTp; } /** * Sets the value of the subTp property. * * @param value * allowed object is * {@link BalanceSubType1Choice } * */ public void setSubTp(BalanceSubType1Choice value) { this.subTp = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BalanceType12.java
1
请在Spring Boot框架中完成以下Java代码
private String getButtonUri(MicrosoftTeamsDeliveryMethodNotificationTemplate processedTemplate, NotificationProcessingContext ctx) throws JsonProcessingException { var button = processedTemplate.getButton(); if (button != null && button.isEnabled()) { String uri; if (button.getLinkType() == LinkType.DASHBOARD) { String state = null; if (button.isSetEntityIdInState() || StringUtils.isNotEmpty(button.getDashboardState())) { ObjectNode stateObject = JacksonUtil.newObjectNode(); if (button.isSetEntityIdInState()) { stateObject.putObject("params") .set("entityId", Optional.ofNullable(ctx.getRequest().getInfo()) .map(NotificationInfo::getStateEntityId) .map(JacksonUtil::valueToTree) .orElse(null)); } else { stateObject.putObject("params"); } if (StringUtils.isNotEmpty(button.getDashboardState())) { stateObject.put("id", button.getDashboardState()); } state = Base64.encodeBase64String(JacksonUtil.OBJECT_MAPPER.writeValueAsBytes(List.of(stateObject))); } String baseUrl = systemSecurityService.getBaseUrl(ctx.getTenantId(), null, null); if (StringUtils.isEmpty(baseUrl)) { throw new IllegalStateException("Failed to determine base url to construct dashboard link"); } uri = baseUrl + "/dashboards/" + button.getDashboardId();
if (state != null) { uri += "?state=" + state; } } else { uri = button.getLink(); } return uri; } return null; } @Override public void check(TenantId tenantId) throws Exception { } @Override public NotificationDeliveryMethod getDeliveryMethod() { return NotificationDeliveryMethod.MICROSOFT_TEAMS; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\MicrosoftTeamsNotificationChannel.java
2
请完成以下Java代码
public class ComparableComparator<T extends Comparable> implements Comparator<T> { private static final transient ComparableComparator<Comparable> instanceNullsFirst = new ComparableComparator<Comparable>(true); private static final transient ComparableComparator<Comparable> instanceNullsLast = new ComparableComparator<Comparable>(false); /** * Default Nulls First option. * * NOTE: for backward compatibility we set it to "true". */ private static final boolean NULLSFIRST_DEFAULT = true; public static <T extends Comparable> ComparableComparator<T> getInstance() { return getInstance(NULLSFIRST_DEFAULT); } public static <T extends Comparable> ComparableComparator<T> getInstance(final boolean nullsFirst) { @SuppressWarnings("unchecked") final ComparableComparator<T> cmp = (ComparableComparator<T>)(nullsFirst ? instanceNullsFirst : instanceNullsLast); return cmp; } public static <T extends Comparable> ComparableComparator<T> getInstance(Class<T> clazz) { return getInstance(NULLSFIRST_DEFAULT); } public static <T extends Comparable> ComparableComparator<T> getInstance(final Class<T> clazz, final boolean nullsFirst) { return getInstance(nullsFirst); } private final boolean nullsFirst; public ComparableComparator() { this(NULLSFIRST_DEFAULT); } public ComparableComparator(final boolean nullsFirst) { this.nullsFirst = nullsFirst; } @Override
public int compare(T o1, T o2) { if (o1 == o2) { return 0; } if (o1 == null) { return nullsFirst ? -1 : +1; } if (o2 == null) { return nullsFirst ? +1 : -1; } @SuppressWarnings("unchecked") final int cmp = o1.compareTo(o2); return cmp; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\ComparableComparator.java
1
请完成以下Java代码
public int getAD_JavaClass_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_JavaClass_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.javaclasses.model.I_AD_JavaClass_Type getAD_JavaClass_Type() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_JavaClass_Type_ID, de.metas.javaclasses.model.I_AD_JavaClass_Type.class); } @Override public void setAD_JavaClass_Type(de.metas.javaclasses.model.I_AD_JavaClass_Type AD_JavaClass_Type) { set_ValueFromPO(COLUMNNAME_AD_JavaClass_Type_ID, de.metas.javaclasses.model.I_AD_JavaClass_Type.class, AD_JavaClass_Type); } /** Set Java Class Type. @param AD_JavaClass_Type_ID Java Class Type */ @Override public void setAD_JavaClass_Type_ID (int AD_JavaClass_Type_ID) { if (AD_JavaClass_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_JavaClass_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_JavaClass_Type_ID, Integer.valueOf(AD_JavaClass_Type_ID)); } /** Get Java Class Type. @return Java Class Type */ @Override public int getAD_JavaClass_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_JavaClass_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java-Klasse. @param Classname Java-Klasse */ @Override public void setClassname (java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () {
return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Interface. @param IsInterface Interface */ @Override public void setIsInterface (boolean IsInterface) { set_Value (COLUMNNAME_IsInterface, Boolean.valueOf(IsInterface)); } /** Get Interface. @return Interface */ @Override public boolean isInterface () { Object oo = get_Value(COLUMNNAME_IsInterface); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass.java
1
请在Spring Boot框架中完成以下Java代码
public class DestinationDetails { @Nullable @JsonProperty("tcpConnectionDetails") TCPConnectionDetails tcpConnectionDetails; /** * If not null, then don't send the resulting PLU-file to a Leich+Melh machine, but store it on disk. */ @Nullable @JsonProperty("pluFileServerFolder") String pluFileServerFolder; private DestinationDetails( @Nullable final TCPConnectionDetails tcpConnectionDetails, @Nullable final String pluFileServerFolder) { Check.errorIf(tcpConnectionDetails == null && Check.isBlank(pluFileServerFolder), "At least one of tcpConnectionDetails and pluFileServerFolder needs to be specified"); this.tcpConnectionDetails = tcpConnectionDetails; this.pluFileServerFolder = pluFileServerFolder; } @NonNull public TCPConnectionDetails getConnectionDetailsNotNull()
{ return Check.assumeNotNull(tcpConnectionDetails, "tcpConnectionDetails are expected to be non-null"); } @NonNull public String getPluFileServerFolderNotBlank() { return Check.assumeNotEmpty(pluFileServerFolder, "pluFileServerFolder is expected to be not blank"); } public boolean isStoreFileOnDisk() { return Check.isNotBlank(pluFileServerFolder); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\DestinationDetails.java
2
请完成以下Java代码
public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(Integer processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue());
} } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getDocumentNo() { return purchaseInvoicePayableDoc.getDocumentNo(); } @Override public TableRecordReference getReference() { return purchaseInvoicePayableDoc.getReference(); } @Override public Money getAmountToAllocateInitial() { return purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getPayAmt().negate(); } @Override public Money getAmountToAllocate() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().negate(); } @Override public void addAllocatedAmt(final Money allocatedAmtToAdd) { purchaseInvoicePayableDoc.addAllocatedAmounts(AllocationAmounts.ofPayAmt(allocatedAmtToAdd.negate())); } /** * Check only the payAmt as that's the only value we are allocating. see {@link PurchaseInvoiceAsInboundPaymentDocumentWrapper#addAllocatedAmt(Money)} */ @Override public boolean isFullyAllocated() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().isZero(); } /** * Computes projected over under amt taking into account discount. * * @implNote for purchase invoices used as inbound payment, the discount needs to be subtracted from the open amount. */ @Override public Money calculateProjectedOverUnderAmt(final Money amountToAllocate) { final Money discountAmt = purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getDiscountAmt(); final Money openAmtWithDiscount = purchaseInvoicePayableDoc.getOpenAmtInitial().subtract(discountAmt); final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(purchaseInvoicePayableDoc.getTotalAllocatedAmount()); final Money adjustedAmountToAllocate = amountToAllocate.negate(); return remainingOpenAmtWithDiscount.subtract(adjustedAmountToAllocate); } @Override public boolean canPay(@NonNull final PayableDocument payable) { // A purchase invoice can compensate only on a sales invoice
if (payable.getType() != PayableDocumentType.Invoice) { return false; } if (!payable.getSoTrx().isSales()) { return false; } // if currency differs, do not allow payment return CurrencyId.equals(payable.getCurrencyId(), purchaseInvoicePayableDoc.getCurrencyId()); } @Override public CurrencyId getCurrencyId() { return purchaseInvoicePayableDoc.getCurrencyId(); } @Override public LocalDate getDate() { return purchaseInvoicePayableDoc.getDate(); } @Override public PaymentCurrencyContext getPaymentCurrencyContext() { return PaymentCurrencyContext.builder() .paymentCurrencyId(purchaseInvoicePayableDoc.getCurrencyId()) .currencyConversionTypeId(purchaseInvoicePayableDoc.getCurrencyConversionTypeId()) .build(); } @Override public Money getPaymentDiscountAmt() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getDiscountAmt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PurchaseInvoiceAsInboundPaymentDocumentWrapper.java
2
请完成以下Java代码
void transform(List<Action> actions, List<Integer> classes) { classes.clear(); for (int i = 0; i < actions.size(); ++i) { classes.add(transform(actions.get(i))); } } /** * 转换动作为动作id * @param act 动作 * @return 动作类型的依存关系id */ int transform(Action act) { int deprel = 0; int[] deprel_inference = new int[]{deprel}; if (ActionUtils.is_shift(act)) { return 0; } else if (ActionUtils.is_left_arc(act, deprel_inference)) { deprel = deprel_inference[0]; return 1 + deprel; } else if (ActionUtils.is_right_arc(act, deprel_inference)) { deprel = deprel_inference[0]; return L + 1 + deprel; } else { System.err.printf("unknown transition in transform(Action): %d-%d", act.name(), act.rel()); } return -1; }
/** * 转换动作id为动作 * @param act 动作类型的依存关系id * @return 动作 */ Action transform(int act) { if (act == 0) { return ActionFactory.make_shift(); } else if (act < 1 + L) { return ActionFactory.make_left_arc(act - 1); } else if (act < 1 + 2 * L) { return ActionFactory.make_right_arc(act - 1 - L); } else { System.err.printf("unknown transition in transform(int): %d", act); } return new Action(); } int number_of_transitions() { return L * 2 + 1; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\TransitionSystem.java
1
请在Spring Boot框架中完成以下Java代码
public class LookupValuesPage { public static final LookupValuesPage EMPTY = builder() .totalRows(OptionalInt.of(0)) .firstRow(-1) .values(LookupValuesList.EMPTY) .hasMoreResults(OptionalBoolean.FALSE) .build(); @NonNull @Builder.Default @With OptionalInt totalRows = OptionalInt.empty(); int firstRow; @NonNull LookupValuesList values; @NonNull @Builder.Default @With OptionalBoolean hasMoreResults = OptionalBoolean.UNKNOWN; public static LookupValuesPage ofValuesAndHasMoreFlag(@NonNull final List<LookupValue> values, boolean hasMoreRecords) { return ofValuesAndHasMoreFlag(LookupValuesList.fromCollection(values), hasMoreRecords); } public static LookupValuesPage ofValuesAndHasMoreFlag(@NonNull final LookupValuesList values, boolean hasMoreRecords) { return builder() .totalRows(OptionalInt.empty()) // N/A .firstRow(-1) // N/A .values(values) .hasMoreResults(OptionalBoolean.ofBoolean(hasMoreRecords)) .build(); } public static LookupValuesPage allValues(@NonNull final LookupValuesList values) { return builder()
.totalRows(OptionalInt.of(values.size())) // N/A .firstRow(0) // N/A .values(values) .hasMoreResults(OptionalBoolean.FALSE) .build(); } public static LookupValuesPage ofNullable(@Nullable final LookupValue lookupValue) { if (lookupValue == null) { return EMPTY; } return allValues(LookupValuesList.fromNullable(lookupValue)); } public <T> T transform(@NonNull final Function<LookupValuesPage, T> transformation) { return transformation.apply(this); } public boolean isEmpty() { return values.isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValuesPage.java
2
请完成以下Java代码
public class Weightables { public static final AttributeCode ATTR_WeightGross = AttributeCode.ofString("WeightGross"); public static final AttributeCode ATTR_WeightNet = AttributeCode.ofString("WeightNet"); public static final AttributeCode ATTR_WeightTare = AttributeCode.ofString("WeightTare"); public static final AttributeCode ATTR_WeightTareAdjust = AttributeCode.ofString("WeightTareAdjust"); /** * Boolean property which if set, it will allow user to change weights but ONLY on VHU level * <p> * task http://dewiki908/mediawiki/index.php/08270_Wareneingang_POS_multiple_lines_in_1_TU_%28107035315495%29 */ public static final String PROPERTY_WeightableOnlyIfVHU = IWeightable.class.getName() + ".WeightableOnlyIfVHU"; public IWeightable wrap(@NonNull final IAttributeStorage attributeStorage) { return new AttributeStorageWeightableWrapper(attributeStorage); } public PlainWeightable plainOf(@NonNull final IAttributeStorage attributeStorage) { return PlainWeightable.copyOf(wrap(attributeStorage)); } public static void updateWeightNet(@NonNull final IWeightable weightable) { // NOTE: we calculate WeightGross, no matter if our HU is allowed to be weighted by user // final boolean weightUOMFriendly = weightable.isWeightable(); final BigDecimal weightTare = weightable.getWeightTareTotal(); final BigDecimal weightGross = weightable.getWeightGross(); final BigDecimal weightNet = weightGross.subtract(weightTare); final BigDecimal weightNetActual; //
// If Gross < Tare, we need to propagate the net value with the initial container's Tare value re-added (+) to preserve the real mathematical values if (weightNet.signum() >= 0) { weightNetActual = weightNet; // propagate net value below normally weightable.setWeightNet(weightNetActual); } else { weightNetActual = weightNet.add(weightable.getWeightTareInitial()); // only subtract seed value (the container's weight) weightable.setWeightNet(weightNetActual); weightable.setWeightNetNoPropagate(weightNet); // directly set the correct value we're expecting } } public static boolean isWeightableAttribute(@NonNull final AttributeCode attributeCode) { return Weightables.ATTR_WeightGross.equals(attributeCode) || Weightables.ATTR_WeightNet.equals(attributeCode) || Weightables.ATTR_WeightTare.equals(attributeCode) || Weightables.ATTR_WeightTareAdjust.equals(attributeCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\Weightables.java
1
请完成以下Java代码
public void update(List<GatewayMetadata> metricsData, long serverReceiveTs) { updateLock.lock(); try { metricsData.forEach(data -> { connectors.computeIfAbsent(data.connector(), k -> new ConnectorMetricsState()).update(data, serverReceiveTs); }); } finally { updateLock.unlock(); } } public Map<String, ConnectorMetricsResult> getStateResult() { Map<String, ConnectorMetricsResult> result = new HashMap<>(); updateLock.lock(); try { connectors.forEach((name, state) -> result.put(name, state.getResult())); connectors.clear(); } finally { updateLock.unlock(); } return result; } public boolean isEmpty() { return connectors.isEmpty(); } private static class ConnectorMetricsState { private final AtomicInteger count; private final AtomicLong gwLatencySum; private final AtomicLong transportLatencySum; private volatile long minGwLatency; private volatile long maxGwLatency; private volatile long minTransportLatency; private volatile long maxTransportLatency; private ConnectorMetricsState() { this.count = new AtomicInteger(0); this.gwLatencySum = new AtomicLong(0); this.transportLatencySum = new AtomicLong(0); } private void update(GatewayMetadata metricsData, long serverReceiveTs) { long gwLatency = metricsData.publishedTs() - metricsData.receivedTs(); long transportLatency = serverReceiveTs - metricsData.publishedTs(); count.incrementAndGet(); gwLatencySum.addAndGet(gwLatency); transportLatencySum.addAndGet(transportLatency); if (minGwLatency == 0 || minGwLatency > gwLatency) { minGwLatency = gwLatency; }
if (maxGwLatency < gwLatency) { maxGwLatency = gwLatency; } if (minTransportLatency == 0 || minTransportLatency > transportLatency) { minTransportLatency = transportLatency; } if (maxTransportLatency < transportLatency) { maxTransportLatency = transportLatency; } } private ConnectorMetricsResult getResult() { long count = this.count.get(); long avgGwLatency = gwLatencySum.get() / count; long avgTransportLatency = transportLatencySum.get() / count; return new ConnectorMetricsResult(avgGwLatency, minGwLatency, maxGwLatency, avgTransportLatency, minTransportLatency, maxTransportLatency); } } public record ConnectorMetricsResult(long avgGwLatency, long minGwLatency, long maxGwLatency, long avgTransportLatency, long minTransportLatency, long maxTransportLatency) { } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\gateway\metrics\GatewayMetricsState.java
1
请在Spring Boot框架中完成以下Java代码
public void delete(DeadLetterJobEntity jobEntity) { super.delete(jobEntity); deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // If the job used to be a history job, the configuration contains the id of the byte array containing the history json // (because deadletter jobs don't have an advanced configuration column) if (HistoryJobEntity.HISTORY_JOB_TYPE.equals(jobEntity.getJobType()) && jobEntity.getJobHandlerConfiguration() != null) { // To avoid duplicating the byteArrayEntityManager lookup, a (fake) ByteArrayRef is created. new ByteArrayRef(jobEntity.getJobHandlerConfiguration(), serviceConfiguration.getCommandExecutor()).delete(serviceConfiguration.getEngineName()); } if (getServiceConfiguration().getInternalJobManager() != null) { getServiceConfiguration().getInternalJobManager().handleJobDelete(jobEntity); } // Send event if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent( FlowableEngineEventType.ENTITY_DELETED, jobEntity), engineType); } } protected DeadLetterJobEntity createDeadLetterJob(AbstractRuntimeJobEntity job) { DeadLetterJobEntity newJobEntity = create(); newJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration()); newJobEntity.setCustomValues(job.getCustomValues());
newJobEntity.setJobHandlerType(job.getJobHandlerType()); newJobEntity.setExclusive(job.isExclusive()); newJobEntity.setRepeat(job.getRepeat()); newJobEntity.setRetries(job.getRetries()); newJobEntity.setEndDate(job.getEndDate()); newJobEntity.setExecutionId(job.getExecutionId()); newJobEntity.setProcessInstanceId(job.getProcessInstanceId()); newJobEntity.setProcessDefinitionId(job.getProcessDefinitionId()); newJobEntity.setScopeId(job.getScopeId()); newJobEntity.setSubScopeId(job.getSubScopeId()); newJobEntity.setScopeType(job.getScopeType()); newJobEntity.setScopeDefinitionId(job.getScopeDefinitionId()); // Inherit tenant newJobEntity.setTenantId(job.getTenantId()); newJobEntity.setJobType(job.getJobType()); return newJobEntity; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\DeadLetterJobEntityManagerImpl.java
2
请完成以下Java代码
public void print(String string) { write(string.toCharArray(), 0, string.length()); } /** * Write the specified text and append a new line. * @param string the content to write */ public void println(String string) { write(string.toCharArray(), 0, string.length()); println(); } /** * Write a new line. */ public void println() { String separator = System.lineSeparator(); try { this.out.write(separator.toCharArray(), 0, separator.length()); } catch (IOException ex) { throw new IllegalStateException(ex); } this.prependIndent = true; } /** * Increase the indentation level and execute the {@link Runnable}. Decrease the * indentation level on completion. * @param runnable the code to execute withing an extra indentation level */ public void indented(Runnable runnable) { indent(); runnable.run(); outdent(); } /** * Increase the indentation level. */ private void indent() { this.level++; refreshIndent(); } /** * Decrease the indentation level. */ private void outdent() { this.level--; refreshIndent(); }
private void refreshIndent() { this.indent = this.indentStrategy.apply(this.level); } @Override public void write(char[] chars, int offset, int length) { try { if (this.prependIndent) { this.out.write(this.indent.toCharArray(), 0, this.indent.length()); this.prependIndent = false; } this.out.write(chars, offset, length); } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public void flush() throws IOException { this.out.flush(); } @Override public void close() throws IOException { this.out.close(); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriter.java
1
请完成以下Spring Boot application配置
server: port: 8091 servlet: session: timeout: 30M context-path: /boss spring: application: name: roncoo-pay-web-boss mvc: view: prefix: /jsp/ suffix: .jsp mybatis: m
apper-locations: classpath:mybatis/mapper/*/*.xml logging: config: classpath:logback.xml
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class Flowable { /** * This is the component that you'll use in your Spring Integration {@link org.springframework.integration.dsl.IntegrationFlow}. */ public static FlowableInboundGateway inboundGateway(ProcessEngine processEngine, String... varsToPreserve) { return new FlowableInboundGateway(processEngine, varsToPreserve); } /** * This is the bean to expose and then reference from your Flowable BPMN flow in an expression. */ public static IntegrationActivityBehavior inboundGatewayActivityBehavior(FlowableInboundGateway gateway) { return new IntegrationActivityBehavior(gateway, null, null); } /**
* Any message that enters this {@link org.springframework.messaging.MessageHandler} containing a {@code executionId} parameter will trigger a * {@link org.flowable.engine.RuntimeService#signal(String)}. */ public static MessageHandler signallingMessageHandler(final ProcessEngine processEngine) { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { String executionId = message.getHeaders().containsKey("executionId") ? (String) message.getHeaders().get("executionId") : (String) null; if (null != executionId) processEngine.getRuntimeService().trigger(executionId); } }; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\integration\Flowable.java
2
请完成以下Java代码
public final class EmptyIterator implements Iterator<Object> { private static final EmptyIterator instance = new EmptyIterator(); @SuppressWarnings("unchecked") public static <E> Iterator<E> getInstance() { return (Iterator<E>)instance; } private EmptyIterator() { super(); } @Override public boolean hasNext()
{ return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\EmptyIterator.java
1
请完成以下Java代码
protected boolean isUpdateNeeded() { boolean propertyTablePresent = isTablePresent(IDM_PROPERTY_TABLE); if (!propertyTablePresent) { return isIdmGroupTablePresent(); } return true; } public boolean isIdmGroupTablePresent() { return isTablePresent("ACT_ID_GROUP"); } @Override public void schemaCheckVersion() { try { String dbVersion = getSchemaVersion(); if (!IdmEngine.VERSION.equals(dbVersion)) { throw new FlowableWrongDbException(IdmEngine.VERSION, dbVersion); } String errorMessage = null; if (!isTablePresent(IDM_PROPERTY_TABLE)) { errorMessage = addMissingComponent(errorMessage, "engine"); } if (errorMessage != null) { throw new FlowableException("Flowable IDM database problem: " + errorMessage); } } catch (Exception e) { if (isMissingTablesException(e)) { throw new FlowableException( "no flowable tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in flowable.cfg.xml for automatic schema creation", e); } else {
if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new FlowableException("couldn't get db schema version", e); } } } logger.debug("flowable idm db schema check successful"); } protected String addMissingComponent(String missingComponents, String component) { if (missingComponents == null) { return "Tables missing for component(s) " + component; } return missingComponents + ", " + component; } @Override public String getContext() { return SCHEMA_COMPONENT; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\db\IdmDbSchemaManager.java
1
请在Spring Boot框架中完成以下Java代码
public Path migrate(Path warFile) { Path resolvedWarFile = requireObject(warFile, (Path path) -> Objects.nonNull(path) && Files.exists(path), "The Path to the WAR file [%s] must not be null and exist", warFile); String warFileName = resolvedWarFile.getFileName().toString(); String migratedWarFileName = String.format(MIGRATED_FILENAME_PATTERN, warFileName); File migratedWarFile = new File(resolvedWarFile.getParent().toFile(), migratedWarFileName); if (!migratedWarFile.isFile()) { try { migratedWarFile.createNewFile(); Migration migration = new Migration(); migration.setSource(resolvedWarFile.toFile()); migration.setDestination(migratedWarFile); migration.setEESpecProfile(EESpecProfile.EE); migration.execute(); } catch (IOException cause) { throw new JavaEEJakartaEEMigrationException( String.format("Failed to migrate Java EE WAR file [%s] to Jakarta EE", warFile), cause); } } return migratedWarFile.toPath(); } protected static class JavaEEJakartaEEMigrationException extends RuntimeException {
public JavaEEJakartaEEMigrationException() { } public JavaEEJakartaEEMigrationException(String message) { super(message); } public JavaEEJakartaEEMigrationException(Throwable cause) { super(cause); } public JavaEEJakartaEEMigrationException(String message, Throwable cause) { super(message, cause); } } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-jetty11\src\main\java\org\springframework\geode\cache\service\support\JakartaEEMigrationService.java
2
请完成以下Java代码
private GeoLocationDocumentQuery createGeoLocationQuery(final I_C_Location location) { final CountryId countryId = CountryId.ofRepoId(location.getC_Country_ID()); final ITranslatableString countryName = countriesRepo.getCountryNameById(countryId); return GeoLocationDocumentQuery.builder() .country(IntegerLookupValue.of(countryId, countryName)) .address1(location.getAddress1()) .city(location.getCity()) .postal(location.getPostal()) .distanceInKm(distanceInKm) .visitorsAddress(visitorsAddress) .build(); } private I_C_Location getSelectedLocationOrFirstAvailable() { final Set<Integer> bpLocationIds = getSelectedIncludedRecordIds(I_C_BPartner_Location.class);
if (!bpLocationIds.isEmpty()) { // retrieve the selected location final LocationId locationId = bpartnersRepo.getBPartnerLocationAndCaptureIdInTrx(BPartnerLocationId.ofRepoId(getRecord_ID(), bpLocationIds.iterator().next())).getLocationCaptureId(); return locationsRepo.getById(locationId); } else { // retrieve the first bpartner location available final List<I_C_BPartner_Location> partnerLocations = bpartnersRepo.retrieveBPartnerLocations(BPartnerId.ofRepoId(getRecord_ID())); if (!partnerLocations.isEmpty()) { return locationsRepo.getById(LocationId.ofRepoId(partnerLocations.get(0).getC_Location_ID())); } } throw new AdempiereException("@NotFound@ @C_Location_ID@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\location\geocoding\process\C_BPartner_Window_AreaSearchProcess.java
1
请完成以下Java代码
public class CommonUtil { /** * 从request中获得参数Map,并返回可读的Map. * * @param request the request * @return the parameter map */ public static Map<String, Object> getParameterMap(HttpServletRequest request) { // 参数Map Map<String, String[]> properties = request.getParameterMap(); //返回值Map Map<String, Object> returnMap = new HashMap<String, Object>(); Set<String> keySet = properties.keySet(); for(String key: keySet){ String[] values = properties.get(key); String value = ""; if(values != null && (values.length==1&&StringUtils.isNotBlank(values[0]))?true:false){
for(int i=0;i<values.length;i++){ if(values[i] != null && !"".equals(values[i])){ // value = new String(values[i].getBytes("ISO-8859-1"),"UTF-8") + ","; value += values[i] + ","; } } if(value != null && !"".equals(value)){ value = value.substring(0, value.length()-1); } if(key.equals("keywords")){//关键字特殊查询字符转义 value = value.replace("_", "\\_").replace("%", "\\%"); } returnMap.put(key, value); } } return returnMap; } }
repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\util\CommonUtil.java
1
请完成以下Java代码
public BigDecimal getQM_QtyDeliveredAvg() { return ppOrderBOMLine.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrderBOMLine; } @Override public String getVariantGroup() { return ppOrderBOMLine.getVariantGroup(); } @Override public BOMComponentType getComponentType() { return BOMComponentType.ofCode(ppOrderBOMLine.getComponentType()); }
@Override public IHandlingUnitsInfo getHandlingUnitsInfo() { if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrderBOMLine); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { return mainComponentProduct; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderBOMLineProductionMaterial.java
1
请完成以下Java代码
public class CatchingThrowable { class CapacityException extends Exception { CapacityException(String message) { super(message); } } class StorageAPI { public void addIDsToStorage(int capacity, Set<String> storage) throws CapacityException { if (capacity < 1) { throw new CapacityException("Capacity of less than 1 is not allowed"); } int count = 0; while (count < capacity) { storage.add(UUID.randomUUID().toString()); count++;
} } // other methods go here ... } public void add(StorageAPI api, int capacity, Set<String> storage) { try { api.addIDsToStorage(capacity, storage); } catch (Throwable throwable) { // do something here } } }
repos\tutorials-master\core-java-modules\core-java-exceptions-2\src\main\java\com\baeldung\exceptions\CatchingThrowable.java
1
请完成以下Spring Boot application配置
spring: cloud: azure: compatibility-verifier: enabled: false keyvault: secret: property-sources[0]: name: key-vault-property-source-1 endpoint: https://spring-cloud-azure.vault.azure.net/ property-source-enabled: true endpoint: https://spring-cloud-azure.vault.azure.net/ azure: keyvault
: vaultUrl: myVaultUrl tenantId: myTenantId clientId: myClientId clientSecret: myClientSecret database: secret: value: ${my-database-secret}
repos\tutorials-master\spring-cloud-modules\spring-cloud-azure\src\main\resources\application.yaml
2
请完成以下Java代码
private boolean isReadonly(@NonNull final Document document) { return readonlyDocuments.computeIfAbsent(document.getDocumentPath(), documentPath -> !DocumentPermissionsHelper.canEdit(document, permissions)); } public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator() { DocumentFieldLogicExpressionResultRevaluator logicExpressionRevaluator = this.logicExpressionRevaluator; if (logicExpressionRevaluator == null) { logicExpressionRevaluator = this.logicExpressionRevaluator = DocumentFieldLogicExpressionResultRevaluator.using(permissions); } return logicExpressionRevaluator; } public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document) { final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions()); Boolean allowWindowEdit = null; Boolean allowDocumentEdit = null; for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); ) { final DocumentStandardAction action = it.next(); if (action.isDocumentWriteAccessRequired()) { if (allowDocumentEdit == null) { allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions); } if (!allowDocumentEdit) { it.remove(); continue; }
} if (action.isWindowWriteAccessRequired()) { if (allowWindowEdit == null) { final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor(); final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow() ? entityDescriptor.getWindowId().toAdWindowId() : null; allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess(); } if (!allowWindowEdit) { it.remove(); //noinspection UnnecessaryContinue continue; } } } return ImmutableSet.copyOf(standardActions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java
1
请完成以下Java代码
public String getEanParty() { return eanParty; } /** * Sets the value of the eanParty property. * * @param value * allowed object is * {@link String } * */ public void setEanParty(String value) { this.eanParty = value; } /** * Gets the value of the zsr property. * * @return * possible object is * {@link String } * */ public String getZsr() { return zsr; } /** * Sets the value of the zsr property. * * @param value * allowed object is * {@link String } * */ public void setZsr(String value) { this.zsr = value; } /** * Gets the value of the specialty property. * * @return * possible object is * {@link String } * */ public String getSpecialty() {
return specialty; } /** * Sets the value of the specialty property. * * @param value * allowed object is * {@link String } * */ public void setSpecialty(String value) { this.specialty = value; } /** * Gets the value of the uidNumber property. * * @return * possible object is * {@link String } * */ public String getUidNumber() { return uidNumber; } /** * Sets the value of the uidNumber property. * * @param value * allowed object is * {@link String } * */ public void setUidNumber(String value) { this.uidNumber = 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\BillerAddressType.java
1
请完成以下Java代码
public void setPP_Order_BOMLine(final org.eevolution.model.I_PP_Order_BOMLine PP_Order_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Order_BOMLine_ID, org.eevolution.model.I_PP_Order_BOMLine.class, PP_Order_BOMLine); } @Override public void setPP_Order_BOMLine_ID (final int PP_Order_BOMLine_ID) { if (PP_Order_BOMLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_BOMLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_BOMLine_ID, PP_Order_BOMLine_ID); } @Override public int getPP_Order_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_BOMLine_ID);
} @Override public void setQtyToIssue (final BigDecimal QtyToIssue) { set_Value (COLUMNNAME_QtyToIssue, QtyToIssue); } @Override public BigDecimal getQtyToIssue() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Candidate_IssueToOrder.java
1
请完成以下Java代码
public ImmutableSet<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public List<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); } @Override public boolean hasAttributes() { return false; } @Override public IViewRowAttributes getAttributes() throws EntityNotFoundException { throw new EntityNotFoundException("Row does not support attributes"); }
@Override public ViewId getIncludedViewId() { return includedViewId; } public ShipmentScheduleId getShipmentScheduleId() { return shipmentScheduleId; } public Optional<OrderLineId> getSalesOrderLineId() { return salesOrderLineId; } public ProductId getProductId() { return product != null ? ProductId.ofRepoIdOrNull(product.getIdAsInt()) : null; } public Quantity getQtyOrderedWithoutPicked() { return qtyOrdered.subtract(qtyPicked).toZeroIfNegative(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRow.java
1
请在Spring Boot框架中完成以下Java代码
public Integer add(UserAddDTO addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return returnId; } /** * 更新指定用户编号的用户 * * @param id 用户编号 * @param updateDTO 更新用户信息 DTO * @return 是否修改成功 */ @PutMapping("/{id}") public Boolean update(@PathVariable("id") Integer id, UserUpdateDTO updateDTO) { // 将 id 设置到 updateDTO 中 updateDTO.setId(id); // 更新用户记录 Boolean success = true; // 返回更新是否成功 return success; }
/** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @DeleteMapping("/{id}") public Boolean delete(@PathVariable("id") Integer id) { // 删除用户记录 Boolean success = false; // 返回是否更新成功 return success; } }
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public void setIsCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } @Override public void setVariableCount(int variableCount) { this.variableCount = variableCount; } @Override public int getVariableCount() { return variableCount; } @Override public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; }
@Override public int getIdentityLinkCount() { return identityLinkCount; } @Override public int getSubTaskCount() { return subTaskCount; } @Override public void setSubTaskCount(int subTaskCount) { this.subTaskCount = subTaskCount; } @Override public boolean isIdentityLinksInitialized() { return isIdentityLinksInitialized; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\TaskEntityImpl.java
2
请完成以下Java代码
public class MSV3PharmaImportPartnerInterceptor implements IImportInterceptor { public static final MSV3PharmaImportPartnerInterceptor instance = new MSV3PharmaImportPartnerInterceptor(); private static final String MSV3_Constant = "MSV3"; // default values for user and password MSV3_Vendor_ConfigIfNeeded // the values are per user and there will be changed by the user private static final String DEFAULT_UserID = "MSV3"; private static final String DEFAULT_Password = "MSV3"; private MSV3PharmaImportPartnerInterceptor() { } @Override public void onImport(IImportProcess<?> process, Object importModel, Object targetModel, int timing) { if (timing != IImportInterceptor.TIMING_AFTER_IMPORT) { return; } final I_I_BPartner ibpartner = InterfaceWrapperHelper.create(importModel, I_I_BPartner.class); if (targetModel instanceof org.compiere.model.I_C_BPartner) { final I_C_BPartner bpartner = InterfaceWrapperHelper.create(targetModel, I_C_BPartner.class); createMSV3_Vendor_ConfigIfNeeded(ibpartner, bpartner); } } private final void createMSV3_Vendor_ConfigIfNeeded(@NonNull final I_I_BPartner importRecord, @NonNull final I_C_BPartner bpartner) { if (!Check.isEmpty(importRecord.getMSV3_Vendor_Config_Name(), true) && MSV3_Constant.equals(importRecord.getMSV3_Vendor_Config_Name())) { if (importRecord.getMSV3_Vendor_Config_ID() > 0) { return; } final BPartnerId bpartnerId = BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()); final MSV3ClientConfigRepository configRepo = Adempiere.getBean(MSV3ClientConfigRepository.class); MSV3ClientConfig config = configRepo.getByVendorIdOrNull(bpartnerId); if (config == null) { config = configRepo.newMSV3ClientConfig() .baseUrl(toURL(importRecord)) .authUsername(DEFAULT_UserID) .authPassword(DEFAULT_Password) .bpartnerId(de.metas.vertical.pharma.msv3.protocol.types.BPartnerId.of(bpartnerId.getRepoId()))
.version(MSV3ClientConfig.VERSION_1) .build(); } config = configRepo.save(config); importRecord.setMSV3_Vendor_Config_ID(config.getConfigId().getRepoId()); } } private URL toURL(@NonNull final I_I_BPartner importRecord) { try { return new URL(importRecord.getMSV3_BaseUrl()); } catch (MalformedURLException e) { throw new AdempiereException("The MSV3_BaseUrl value of the given I_BPartner can't be parsed as URL", e) .appendParametersToMessage() .setParameter("MSV3_BaseUrl", importRecord.getMSV3_BaseUrl()) .setParameter("I_I_BPartner", importRecord); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\interceptor\MSV3PharmaImportPartnerInterceptor.java
1
请完成以下Java代码
public List<RetourePositionType> getPosition() { if (position == null) { position = new ArrayList<RetourePositionType>(); } return this.position; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setID(String value) { this.id = value; } /**
* Gets the value of the retoureSupportID property. * */ public int getRetoureSupportID() { return retoureSupportID; } /** * Sets the value of the retoureSupportID property. * */ public void setRetoureSupportID(int value) { this.retoureSupportID = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfrageType.java
1
请在Spring Boot框架中完成以下Java代码
abstract class ForwardingPackingItem implements IPackingItem { protected abstract IPackingItem getDelegate(); // Following methods are quite critical and in most cases would be overwritten, so it's better to not implement them here. //@formatter:off @Override public abstract boolean isSameAs(final IPackingItem item); @Override public abstract IPackingItem copy(); //@formatter:on @Override public I_C_UOM getC_UOM() { return getDelegate().getC_UOM(); } @Override public PackingItemGroupingKey getGroupingKey() { return getDelegate().getGroupingKey(); } @Override public BPartnerId getBPartnerId() { return getDelegate().getBPartnerId(); } @Override public BPartnerLocationId getBPartnerLocationId() { return getDelegate().getBPartnerLocationId(); } @Override public void setPartsFrom(final IPackingItem packingItem) { getDelegate().setPartsFrom(packingItem); } @Override public HUPIItemProductId getPackingMaterialId() { return getDelegate().getPackingMaterialId(); } @Override public void addParts(final IPackingItem packingItem) { getDelegate().addParts(packingItem); } public final IPackingItem addPartsAndReturn(final IPackingItem packingItem) { return getDelegate().addPartsAndReturn(packingItem); } @Override public void addParts(final PackingItemParts toAdd) { getDelegate().addParts(toAdd); } @Override public Set<WarehouseId> getWarehouseIds() { return getDelegate().getWarehouseIds(); } @Override public Set<ShipmentScheduleId> getShipmentScheduleIds()
{ return getDelegate().getShipmentScheduleIds(); } @Override public IPackingItem subtractToPackingItem( final Quantity subtrahent, final Predicate<PackingItemPart> acceptPartPredicate) { return getDelegate().subtractToPackingItem(subtrahent, acceptPartPredicate); } @Override public PackingItemParts subtract(final Quantity subtrahent) { return getDelegate().subtract(subtrahent); } @Override public PackingItemParts getParts() { return getDelegate().getParts(); } @Override public ProductId getProductId() { return getDelegate().getProductId(); } @Override public Quantity getQtySum() { return getDelegate().getQtySum(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\ForwardingPackingItem.java
2
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; }
public void setNickname(String nickname) { this.nickname = nickname; } public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\domain\User.java
1
请完成以下Java代码
public ImmutableMap<DocumentId, T> getDocumentId2TopLevelRows() { return getRowsIndex().getDocumentId2TopLevelRows(); } public ImmutableMap<DocumentId, T> getDocumentId2TopLevelRows(@NonNull final Predicate<T> filter) { return getRowsIndex().getDocumentId2TopLevelRows(filter); } public <ID extends RepoIdAware> ImmutableSet<ID> getRecordIdsToRefresh( @NonNull final DocumentIdsSelection rowIds, @NonNull final Function<DocumentId, ID> idMapper) { return getRowsIndex().getRecordIdsToRefresh(rowIds, idMapper); } public Stream<T> stream() {return getRowsIndex().stream();} public Stream<T> stream(Predicate<T> predicate) {return getRowsIndex().stream(predicate);} public long count(Predicate<T> predicate) {return getRowsIndex().count(predicate);} public boolean anyMatch(final Predicate<T> predicate) {return getRowsIndex().anyMatch(predicate);} public List<T> list() {return getRowsIndex().list();} public void compute(@NonNull final UnaryOperator<ImmutableRowsIndex<T>> remappingFunction) { holder.compute(remappingFunction); } public void addRow(@NonNull final T row) { compute(rows -> rows.addingRow(row)); } @SuppressWarnings("unused") public void removeRowsById(@NonNull final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return; } compute(rows -> rows.removingRowIds(rowIds)); } @SuppressWarnings("unused") public void removingIf(@NonNull final Predicate<T> predicate) { compute(rows -> rows.removingIf(predicate)); } public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRow(rowId, rowMapper)); } public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper)
{ compute(rows -> rows.changingRows(rowIds, rowMapper)); } public void setRows(@NonNull final List<T> rows) { holder.setValue(ImmutableRowsIndex.of(rows)); } @NonNull private ImmutableRowsIndex<T> getRowsIndex() { final ImmutableRowsIndex<T> rowsIndex = holder.getValue(); // shall not happen if (rowsIndex == null) { throw new AdempiereException("rowsIndex shall be set"); } return rowsIndex; } public Predicate<DocumentId> isRelevantForRefreshingByDocumentId() { final ImmutableRowsIndex<T> rows = getRowsIndex(); return rows::isRelevantForRefreshing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
1
请完成以下Java代码
public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_ValueNoCheck (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSumDeliveredInStockingUOM (final @Nullable BigDecimal SumDeliveredInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final @Nullable BigDecimal SumOrderedInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM); } @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_ValueNoCheck (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_M_InOut_Desadv_V.java
1
请在Spring Boot框架中完成以下Java代码
public class ForkJoinStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> { @Override public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .fork("SFork") .join("SJoin") .end("SF") .and() .withStates() .parent("SFork") .initial("Sub1-1") .end("Sub1-2") .and() .withStates() .parent("SFork") .initial("Sub2-1") .end("Sub2-2"); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions.withExternal() .source("SI").target("SFork").event("E1") .and().withExternal() .source("Sub1-1").target("Sub1-2").event("sub1") .and().withExternal() .source("Sub2-1").target("Sub2-2").event("sub2") .and() .withFork() .source("SFork")
.target("Sub1-1") .target("Sub2-1") .and() .withJoin() .source("Sub1-2") .source("Sub2-2") .target("SJoin"); } @Bean public Guard<String, String> mediumGuard() { return ctx -> false; } @Bean public Guard<String, String> highGuard() { return ctx -> false; } }
repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\ForkJoinStateMachineConfiguration.java
2
请完成以下Java代码
public void setRatioOperand (String RatioOperand) { set_Value (COLUMNNAME_RatioOperand, RatioOperand); } /** Get Operand. @return Ratio Operand */ public String getRatioOperand () { return (String)get_Value(COLUMNNAME_RatioOperand); } /** 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(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_RatioElement.java
1
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "dmnTest") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @ApiModelProperty(example = "Decision Table One") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "DecisionTableOne") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @ApiModelProperty(example = "This is a simple description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty(example = "3") public int getVersion() { return version; } public void setVersion(int version) {
this.version = version; } @ApiModelProperty(example = "dmn-DecisionTableOne.dmn") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "46aa6b3a-c0a1-11e6-bc93-6ab56fad108a") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "decision_table") public String getDecisionType() { return decisionType; } public void setDecisionType(String decisionType) { this.decisionType = decisionType; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DecisionResponse.java
2
请完成以下Java代码
public boolean isFindNew() { return findNew; } public void setFindNew(boolean findNew) { this.findNew = findNew; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; }
public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public Date getPublishtime() { return publishtime; } public void setPublishtime(Date publishtime) { this.publishtime = publishtime; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\VersionResult.java
1
请完成以下Java代码
public final class ValueNamePair extends NamePair { public static final ValueNamePair EMPTY = new ValueNamePair("", "", null/* help */); private final ValueNamePairValidationInformation m_validationInformation; public static ValueNamePair of( @JsonProperty("v") final String value, @JsonProperty("n") final String name) { return of(value, name, null/* help */); } public static ValueNamePair of( @JsonProperty("v") final String value, @JsonProperty("n") final String name, @JsonProperty("description") final String description) { if (Objects.equals(value, EMPTY.getValue()) && Objects.equals(name, EMPTY.getName())) { return EMPTY; } return new ValueNamePair(value, name, description); } @JsonCreator public static ValueNamePair of( @JsonProperty("v") final String value, @JsonProperty("n") final String name, @JsonProperty("description") final String description, @JsonProperty("validationInformation") @Nullable final ValueNamePairValidationInformation validationInformation) { if (Objects.equals(value, EMPTY.getValue()) && Objects.equals(name, EMPTY.getName()) && validationInformation == null) { return EMPTY; } return new ValueNamePair(value, name, description, validationInformation); } /** * Construct KeyValue Pair * * @param value value * @param name string representation */ public ValueNamePair(final String value, final String name, final String help) { super(name, help); m_value = value == null ? "" : value; m_validationInformation = null; } // ValueNamePair public ValueNamePair( final String value, final String name, final String help, @Nullable final ValueNamePairValidationInformation validationInformation) { super(name, help); m_value = value == null ? "" : value; m_validationInformation = validationInformation; } // ValueNamePair /** * The Value */ private final String m_value; /** * Get Value * * @return Value */ @JsonProperty("v") public String getValue() { return m_value; } // getValue /**
* Get Validation Message * * @return Validation Message */ @JsonProperty("validationInformation") @JsonInclude(JsonInclude.Include.NON_NULL) public ValueNamePairValidationInformation getValidationInformation() { return m_validationInformation; } /** * Get ID * * @return Value */ @Override @JsonIgnore public String getID() { return m_value; } // getID @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof ValueNamePair) { final ValueNamePair other = (ValueNamePair)obj; return Objects.equals(this.m_value, other.m_value) && Objects.equals(this.getName(), other.getName()) && Objects.equals(this.m_validationInformation, other.m_validationInformation); } return false; } // equals @Override public int hashCode() { return m_value.hashCode(); } // hashCode } // KeyValuePair
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePair.java
1
请完成以下Java代码
public I_AD_Archive retrieveArchive(@NonNull final ArchiveId archiveId) { return InterfaceWrapperHelper.load(archiveId, I_AD_Archive.class); } @Override public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId) { queryBL.createQueryBuilder(I_AD_Archive.class, Env.getCtx(), ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_AD_Archive.COLUMN_AD_Archive_ID, ids).create().iterateAndStream().filter(Objects::nonNull).forEach(archive -> archiveEventManager.firePdfUpdate(archive, userId)); } @Override public <T extends I_AD_Archive> T retrieveArchive(@NonNull final ArchiveId archiveId, @NonNull final Class<T> modelClass) { final T archive = loadOutOfTrx(archiveId, modelClass); if (archive == null) { throw new AdempiereException("@NotFound@ @AD_Archive_ID@: " + archiveId); } return archive; }
@Override public void updatePOReferenceIfExists( @NonNull final TableRecordReference recordReference, @Nullable final String poReference) { retrieveArchivesQuery(Env.getCtx(), recordReference) .create() .stream() .forEach(archive -> { archive.setPOReference(poReference); saveRecord(archive); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveDAO.java
1
请完成以下Java代码
private boolean isCloneEnabled() { return isCloneEnabled(_tableName); } private static boolean isCloneEnabled(@Nullable final Optional<String> tableName) { if (tableName == null || !tableName.isPresent()) { return false; } return CopyRecordFactory.isEnabledForTableName(tableName.get()); } public DocumentQueryOrderByList getDefaultOrderBys() { return getFieldBuilders() .stream()
.filter(DocumentFieldDescriptor.Builder::isDefaultOrderBy) .sorted(Ordering.natural().onResultOf(DocumentFieldDescriptor.Builder::getDefaultOrderByPriority)) .map(field -> DocumentQueryOrderBy.byFieldName(field.getFieldName(), field.isDefaultOrderByAscending())) .collect(DocumentQueryOrderByList.toDocumentQueryOrderByList()); } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder notFoundMessages(@Nullable final NotFoundMessages notFoundMessages) { this.notFoundMessages = notFoundMessages; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentEntityDescriptor.java
1
请完成以下Java代码
public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null;
this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsAlbumExample.java
1
请在Spring Boot框架中完成以下Java代码
public class PublisherController { @Autowired private ProducerService producerService; @Autowired private ReceiverService receiverService; private List<String> mesList; /** * 初始化消息 */ public PublisherController() { mesList = new ArrayList<>(); mesList.add("小小"); mesList.add("爸爸"); mesList.add("妈妈"); mesList.add("爷爷"); mesList.add("奶奶");
} @RequestMapping("/text/rocketmq") public Object callback() throws Exception { //总共发送五次消息 for (String s : mesList) { //创建生产信息 Message message = new Message(JmsConfig.TOPIC, "testtag", ("小小一家人的称谓:" + s).getBytes()); //发送 SendResult sendResult = producerService.getProducer().send(message); System.out.println(String.format("输出生产者信息={ %s }",sendResult)); } return "成功"; } }
repos\springBoot-master\springboot-rocketmq\src\main\java\cn\abel\queue\controller\PublisherController.java
2
请完成以下Java代码
default boolean isMoreThanAllowedSelected(final int maxAllowedSelectionSize) { return getSelectionSize().getSize() > maxAllowedSelectionSize; } /** * @return selected included rows of current single selected document */ default Set<TableRecordReference> getSelectedIncludedRecords() { return ImmutableSet.of(); } default boolean isSingleIncludedRecordSelected() { return getSelectedIncludedRecords().size() == 1; } <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass); default ProcessPreconditionsResolution acceptIfSingleSelection() { if (isNoSelection()) {
return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } else { return ProcessPreconditionsResolution.accept(); } } default OptionalBoolean isExistingDocument() {return OptionalBoolean.UNKNOWN;} default OptionalBoolean isProcessedDocument() { return OptionalBoolean.UNKNOWN; }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\IProcessPreconditionsContext.java
1
请完成以下Java代码
protected Token nextToken() throws ScanException { if (isEval()) { if (input.charAt(position) == '}') { return fixed(Symbol.END_EVAL); } return nextEval(); } else { if (position + 1 < input.length() && input.charAt(position + 1) == '{') { switch (input.charAt(position)) { case '#': return fixed(Symbol.START_EVAL_DEFERRED); case '$': return fixed(Symbol.START_EVAL_DYNAMIC); } } return nextText(); } } /** * Scan next token. * After calling this method, {@link #getToken()} and {@link #getPosition()} * can be used to retreive the token's image and input position. * @return scanned token */ public Token next() throws ScanException { if (token != null) { position += token.getSize();
} int length = input.length(); if (isEval()) { while (position < length && Character.isWhitespace(input.charAt(position))) { position++; } } if (position == length) { return token = fixed(Symbol.EOF); } return token = nextToken(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Scanner.java
1
请在Spring Boot框架中完成以下Java代码
public List<UserInfoResponse> getUserInfo(@ApiParam(name = "userId") @PathVariable String userId) { User user = getUserFromRequest(userId); return restResponseFactory.createUserInfoKeysResponse(identityService.getUserInfoKeys(user.getId()), user.getId()); } @ApiOperation(value = "Create a new user’s info entry", tags = { "Users" }, nickname = "createUserInfo", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the user was found and the info has been created."), @ApiResponse(code = 400, message = "Indicates the key or value was missing from the request body. Status description contains additional information about the error."), @ApiResponse(code = 404, message = "Indicates the requested user was not found."), @ApiResponse(code = 409, message = "Indicates there is already an info-entry with the given key for the user, update the resource instance (PUT).") }) @PostMapping(value = "/identity/users/{userId}/info", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public UserInfoResponse setUserInfo(@ApiParam(name = "userId") @PathVariable String userId, @RequestBody UserInfoRequest userRequest) { User user = getUserFromRequest(userId);
if (userRequest.getKey() == null) { throw new FlowableIllegalArgumentException("The key cannot be null."); } if (userRequest.getValue() == null) { throw new FlowableIllegalArgumentException("The value cannot be null."); } String existingValue = identityService.getUserInfo(user.getId(), userRequest.getKey()); if (existingValue != null) { throw new FlowableConflictException("User info with key '" + userRequest.getKey() + "' already exists for this user."); } identityService.setUserInfo(user.getId(), userRequest.getKey(), userRequest.getValue()); return restResponseFactory.createUserInfoResponse(userRequest.getKey(), userRequest.getValue(), user.getId()); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserInfoCollectionResource.java
2
请完成以下Java代码
public class OpenApiAuth implements Serializable { private static final long serialVersionUID = -5933153354153738498L; /** * id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 受权名称 */ private String name; /** * access key */ private String ak; /** * secret key */ private String sk; /** * 系统用户ID */ @Dict(dictTable = "sys_user",dicCode = "id",dicText = "username") private String systemUserId; /** * 创建人 */ private String createBy;
/** * 创建时间 */ private Date createTime; /** * 更新人 */ private String updateBy; /** * 更新时间 */ private Date updateTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\entity\OpenApiAuth.java
1
请完成以下Java代码
public ThreadPoolTaskSchedulerBuilder additionalCustomizers( Iterable<? extends ThreadPoolTaskSchedulerCustomizer> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return new ThreadPoolTaskSchedulerBuilder(this.poolSize, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, append(this.customizers, customizers)); } /** * Build a new {@link ThreadPoolTaskScheduler} instance and configure it using this * builder. * @return a configured {@link ThreadPoolTaskScheduler} instance. * @see #configure(ThreadPoolTaskScheduler) */ public ThreadPoolTaskScheduler build() { return configure(new ThreadPoolTaskScheduler()); } /** * Configure the provided {@link ThreadPoolTaskScheduler} instance using this builder. * @param <T> the type of task scheduler * @param taskScheduler the {@link ThreadPoolTaskScheduler} to configure * @return the task scheduler instance * @see #build()
*/ public <T extends ThreadPoolTaskScheduler> T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get(); map.from(this.poolSize).to(taskScheduler::setPoolSize); map.from(this.awaitTermination).to(taskScheduler::setWaitForTasksToCompleteOnShutdown); map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds).to(taskScheduler::setAwaitTerminationSeconds); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); map.from(this.taskDecorator).to(taskScheduler::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\ThreadPoolTaskSchedulerBuilder.java
1
请在Spring Boot框架中完成以下Java代码
private void buildBPRetrieveCamelRequest(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final String bPartnerIdentifier = request.getParameters().get(ExternalSystemConstants.PARAM_BPARTNER_ID); if (Check.isBlank(bPartnerIdentifier)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_BPARTNER_ID); } final JsonMetasfreshId externalSystemConfigId = request.getExternalSystemConfigId(); final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId(); final BPRetrieveCamelRequest retrieveCamelRequest = BPRetrieveCamelRequest.builder() .bPartnerIdentifier(bPartnerIdentifier) .externalSystemConfigId(externalSystemConfigId) .adPInstanceId(adPInstanceId) .build(); exchange.getIn().setBody(retrieveCamelRequest); } private void processRetrieveBPartnerResponse(@NonNull final Exchange exchange) { final JsonResponseComposite jsonResponseComposite = exchange.getIn().getBody(JsonResponseComposite.class); final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class); routeContext.setJsonResponseComposite(jsonResponseComposite); } private void setResponseComposite(@NonNull final Exchange exchange) { final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class); exchange.getIn().setBody(routeContext.getJsonResponseComposite()); } @Nullable private static JsonExportDirectorySettings getJsonExportDirSettings(@NonNull final JsonExternalSystemRequest externalSystemRequest) { final String exportDirSettings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_JSON_EXPORT_DIRECTORY_SETTINGS);
if (Check.isBlank(exportDirSettings)) { return null; } try { return JsonObjectMapperHolder.sharedJsonObjectMapper() .readValue(exportDirSettings, JsonExportDirectorySettings.class); } catch (final JsonProcessingException e) { throw new RuntimeException("Could not read value of type JsonExportDirectorySettings!" + "ExternalSystemConfigId=" + externalSystemRequest.getExternalSystemConfigId() + ";" + " PInstance=" + externalSystemRequest.getAdPInstanceId()); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\GRSSignumExportBPartnerRouteBuilder.java
2
请完成以下Java代码
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 Number of Months. @param NoMonths Number of Months */ public void setNoMonths (int NoMonths) { set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths)); } /** Get Number of Months. @return Number of Months */ public int getNoMonths () { Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths); if (ii == null) return 0; return ii.intValue(); }
/** RecognitionFrequency AD_Reference_ID=196 */ public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196; /** Month = M */ public static final String RECOGNITIONFREQUENCY_Month = "M"; /** Quarter = Q */ public static final String RECOGNITIONFREQUENCY_Quarter = "Q"; /** Year = Y */ public static final String RECOGNITIONFREQUENCY_Year = "Y"; /** Set Recognition frequency. @param RecognitionFrequency Recognition frequency */ public void setRecognitionFrequency (String RecognitionFrequency) { set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency); } /** Get Recognition frequency. @return Recognition frequency */ public String getRecognitionFrequency () { return (String)get_Value(COLUMNNAME_RecognitionFrequency); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java
1
请完成以下Java代码
public ValueExpression setVariable(String name, ValueExpression value) { ValueExpression previousValue = resolveVariable(name); scriptContext.setAttribute(name, value, ScriptContext.ENGINE_SCOPE); return previousValue; } } /** * FunctionMapper that uses the ScriptContext to resolve functions in EL. * */ private class ScriptContextFunctionMapper extends FunctionMapper { private ScriptContext scriptContext; ScriptContextFunctionMapper(ScriptContext ctx) { this.scriptContext = ctx; } private String getFullFunctionName(String prefix, String localName) {
return prefix + ":" + localName; } @Override public Method resolveFunction(String prefix, String localName) { String functionName = getFullFunctionName(prefix, localName); int scope = scriptContext.getAttributesScope(functionName); if (scope != -1) { // Methods are added as variables in the ScriptScope Object attributeValue = scriptContext.getAttribute(functionName); return (attributeValue instanceof Method) ? (Method) attributeValue : null; } else { return null; } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngine.java
1
请完成以下Java代码
public static Map<String, String[]> loadCorpusWithException(String folderPath, String charsetName) throws IOException { if (folderPath == null) throw new IllegalArgumentException("参数 folderPath == null"); File root = new File(folderPath); if (!root.exists()) throw new IllegalArgumentException(String.format("目录 %s 不存在", root.getAbsolutePath())); if (!root.isDirectory()) throw new IllegalArgumentException(String.format("目录 %s 不是一个目录", root.getAbsolutePath())); Map<String, String[]> dataSet = new TreeMap<String, String[]>(); File[] folders = root.listFiles(); if (folders == null) return null; for (File folder : folders) { if (folder.isFile()) continue; File[] files = folder.listFiles(); if (files == null) continue; String[] documents = new String[files.length]; for (int i = 0; i < files.length; i++) { documents[i] = readTxt(files[i], charsetName); } dataSet.put(folder.getName(), documents); } return dataSet; } public static String readTxt(File file, String charsetName) throws IOException
{ FileInputStream is = new FileInputStream(file); byte[] targetArray = new byte[is.available()]; int len; int off = 0; while ((len = is.read(targetArray, off, targetArray.length - off)) != -1 && off < targetArray.length) { off += len; } is.close(); return new String(targetArray, charsetName); } public static Map<String, String[]> loadCorpusWithException(String corpusPath) throws IOException { return loadCorpusWithException(corpusPath, "UTF-8"); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\utilities\TextProcessUtility.java
1
请完成以下Java代码
public void clear() { iflag_ = iscn = nfev = iycn = point = npt = iter = info = ispt = isyt = iypt = 0; stp = stp1 = 0.0; diag_ = null; w_ = null; v_ = null; mcsrch_ = null; } public int init(int n, int m) { //This is old interface for backword compatibility final int msize = 5; final int size = n; iflag_ = 0; w_ = new double[size * (2 * msize + 1) + 2 * msize]; Arrays.fill(w_, 0.0); diag_ = new double[size]; v_ = new double[size]; return 0; } public int optimize(double[] x, double f, double[] g) { return optimize(diag_.length, x, f, g, false, 1.0); } public int optimize(int size, double[] x, double f, double[] g, boolean orthant, double C) { int msize = 5; if (w_ == null) { iflag_ = 0; w_ = new double[size * (2 * msize + 1) + 2 * msize]; Arrays.fill(w_, 0.0); diag_ = new double[size]; v_ = new double[size]; if (orthant) { xi_ = new double[size]; } } else if (diag_.length != size || v_.length != size) { System.err.println("size of array is different"); return -1; } else if (orthant && v_.length != size) { System.err.println("size of array is different"); return -1; } int iflag = 0; if (orthant) {
iflag = lbfgs_optimize(size, msize, x, f, g, diag_, w_, orthant, C, v_, xi_, iflag_); iflag_ = iflag; } else { iflag = lbfgs_optimize(size, msize, x, f, g, diag_, w_, orthant, C, g, xi_, iflag_); iflag_ = iflag; } if (iflag < 0) { System.err.println("routine stops with unexpected error"); return -1; } if (iflag == 0) { clear(); return 0; // terminate } return 1; // evaluate next f and g } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\LbfgsOptimizer.java
1