instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Flux<RouteDefinition> getRouteDefinitions() { return reactiveRedisTemplate.scan(ScanOptions.scanOptions().match(createKey("*")).build()) .flatMap(key -> reactiveRedisTemplate.opsForValue().get(key)) .onErrorContinue((throwable, routeDefinition) -> { if (log.isErrorEnabled()) { log.error("get routes from redis error cause : {}", throwable.toString(), throwable); } }); } @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> { Objects.requireNonNull(routeDefinition.getId(), "id may not be null"); return routeDefinitionReactiveValueOperations.set(createKey(routeDefinition.getId()), routeDefinition) .flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new RuntimeException( String.format("Could not add route to redis repository: %s", routeDefinition)))); }); });
} @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> routeDefinitionReactiveValueOperations.delete(createKey(id)).flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException( String.format("Could not remove route from redis repository with id: %s", routeId)))); })); } private String createKey(String routeId) { return ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY + routeId; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RedisRouteDefinitionRepository.java
1
请完成以下Java代码
public boolean wasApplied() { return delegate.wasApplied(); } public ListenableFuture<List<Row>> allRows(Executor executor) { List<Row> allRows = new ArrayList<>(); SettableFuture<List<Row>> resultFuture = SettableFuture.create(); this.processRows(originalStatement, delegate, allRows, resultFuture, executor); return resultFuture; } private void processRows(Statement statement, AsyncResultSet resultSet, List<Row> allRows, SettableFuture<List<Row>> resultFuture, Executor executor) { allRows.addAll(loadRows(resultSet)); if (resultSet.hasMorePages()) { ByteBuffer nextPagingState = resultSet.getExecutionInfo().getPagingState(); Statement<?> nextStatement = statement.setPagingState(nextPagingState); TbResultSetFuture resultSetFuture = executeAsyncFunction.apply(nextStatement); Futures.addCallback(resultSetFuture, new FutureCallback<TbResultSet>() { @Override public void onSuccess(@Nullable TbResultSet result) { processRows(nextStatement, result,
allRows, resultFuture, executor); } @Override public void onFailure(Throwable t) { resultFuture.setException(t); } }, executor != null ? executor : MoreExecutors.directExecutor() ); } else { resultFuture.set(allRows); } } List<Row> loadRows(AsyncResultSet resultSet) { return Lists.newArrayList(resultSet.currentPage()); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSet.java
1
请完成以下Java代码
public class DDOrderLineHUDocumentHandler implements IHUDocumentHandler { private final static String SYSCONFIG_DD_OrderLine_Enforce_M_HU_PI_Item_Product = "de.metas.handlingunits.DD_OrderLine_Enforce_M_HU_PI_Item_Product"; /** * This method assumes that the given document is <code>DD_OrderLine</code> and returns * <ul> * <li><code>null</code> is the line has no product</li> * <li>the line's current PIIP f the line is new and already has a PIIP</li> * <li>the result of {@link IHUPIItemProductDAO#retrieveMaterialItemProduct(ProductId, BPartnerId, java.time.ZonedDateTime, String, boolean) (with type="transport unit") * otherwise</li> * </ul> */ @Override public I_M_HU_PI_Item_Product getM_HU_PI_ItemProductFor(final Object document, final ProductId productId) { if (productId == null) { // No product selected. Nothing to do. return null; } final de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine ddOrderLine = getDDOrderLine(document); final I_M_HU_PI_Item_Product piip; // the record is new // search for the right combination if (InterfaceWrapperHelper.isNew(ddOrderLine) && ddOrderLine.getM_HU_PI_Item_Product_ID() > 0) { piip = ddOrderLine.getM_HU_PI_Item_Product(); } else { final I_DD_Order ddOrder = ddOrderLine.getDD_Order(); final String huUnitType = X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit; piip = Services.get(IHUPIItemProductDAO.class).retrieveMaterialItemProduct( productId, BPartnerId.ofRepoIdOrNull(ddOrder.getC_BPartner_ID()), TimeUtil.asZonedDateTime(ddOrder.getDateOrdered()), huUnitType, false); // allowInfiniteCapacity = false
} return piip; } /** * Calls {@link #getM_HU_PI_ItemProductFor(Object, ProductId)} with the given <code>document</code> which is a <code>DD_OrderLine</code> and sets the PIIP to it. Does <b>not</b> save the dd order line. */ @Override public void applyChangesFor(final Object document) { final de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine ddOrderLine = getDDOrderLine(document); final boolean enforcePIIP = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DD_OrderLine_Enforce_M_HU_PI_Item_Product, false); if(!enforcePIIP) { return; } final ProductId productId = ProductId.ofRepoIdOrNull(ddOrderLine.getM_Product_ID()); final I_M_HU_PI_Item_Product piip = getM_HU_PI_ItemProductFor(ddOrderLine, productId); ddOrderLine.setM_HU_PI_Item_Product(piip); } private de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine getDDOrderLine(final Object document) { Check.assumeInstanceOf(document, I_DD_OrderLine.class, "document"); return InterfaceWrapperHelper.create(document, de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\hu_spis\DDOrderLineHUDocumentHandler.java
1
请完成以下Java代码
public static boolean isEntityTypeDisplayedInUIOrTrueIfNull( @NonNull final Properties ctx, @NonNull final String entityType) { // Get the constraint of current logged in role. final IUserRolePermissions role = Env.getUserRolePermissionsOrNull(ctx); if(role == null) { // cannot extract the role from given context => consider the entity as displayed return true; } return isEntityTypeDisplayedInUIOrTrueIfNull(role, entityType); } public static boolean isEntityTypeDisplayedInUIOrTrueIfNull( @NonNull final IUserRolePermissions role, @NonNull final String entityType) { final UIDisplayedEntityTypes constraint = role .getConstraint(UIDisplayedEntityTypes.class) .orElse(null); // If no constraint => return default (true) if (constraint == null) { return true; } // Ask the constraint return constraint.isDisplayedInUI(entityType); }
private final boolean showAllEntityTypes; private UIDisplayedEntityTypes(final boolean showAllEntityTypes) { super(); this.showAllEntityTypes = showAllEntityTypes; } @Override public boolean isInheritable() { return false; } /** * @return true if UI elements for given entity type shall be displayed */ public boolean isDisplayedInUI(final String entityType) { if (showAllEntityTypes) { return EntityTypesCache.instance.isActive(entityType); } else { return EntityTypesCache.instance.isDisplayedInUI(entityType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UIDisplayedEntityTypes.java
1
请在Spring Boot框架中完成以下Java代码
public class ForecastCreatedHandler implements MaterialEventHandler<ForecastCreatedEvent> { private final CandidateChangeService candidateChangeHandler; public ForecastCreatedHandler(@NonNull final CandidateChangeService candidateChangeHandler) { this.candidateChangeHandler = candidateChangeHandler; } @Override public Collection<Class<? extends ForecastCreatedEvent>> getHandledEventType() { return ImmutableList.of(ForecastCreatedEvent.class); } @Override public void handleEvent(@NonNull final ForecastCreatedEvent event) { final Forecast forecast = event.getForecast(); final CandidateBuilder candidateBuilder = Candidate.builderForEventDescriptor(event.getEventDescriptor()) //.status(EventUtil.getCandidateStatus(forecast.getDocStatus())) .type(CandidateType.STOCK_UP) .businessCase(CandidateBusinessCase.FORECAST); for (final ForecastLine forecastLine : forecast.getForecastLines()) {
complementBuilderFromForecastLine(candidateBuilder, forecast, forecastLine); final Candidate demandCandidate = candidateBuilder.build(); candidateChangeHandler.onCandidateNewOrChange(demandCandidate); } } private void complementBuilderFromForecastLine( @NonNull final CandidateBuilder candidateBuilder, @NonNull final Forecast forecast, @NonNull final ForecastLine forecastLine) { candidateBuilder .materialDescriptor(forecastLine.getMaterialDescriptor()) .businessCaseDetail(DemandDetail.forForecastLineId( forecastLine.getForecastLineId(), forecast.getForecastId(), forecastLine.getMaterialDescriptor().getQuantity())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\foreacast\ForecastCreatedHandler.java
2
请完成以下Java代码
public void setWEBUI_IncludedTabTopAction (boolean WEBUI_IncludedTabTopAction) { set_Value (COLUMNNAME_WEBUI_IncludedTabTopAction, Boolean.valueOf(WEBUI_IncludedTabTopAction)); } /** Get Is Included Tab Top Action. @return Is Included Tab Top Action */ @Override public boolean isWEBUI_IncludedTabTopAction () { Object oo = get_Value(COLUMNNAME_WEBUI_IncludedTabTopAction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Shortcut. @param WEBUI_Shortcut Shortcut */ @Override public void setWEBUI_Shortcut (java.lang.String WEBUI_Shortcut) { set_Value (COLUMNNAME_WEBUI_Shortcut, WEBUI_Shortcut); } /** Get Shortcut. @return Shortcut */ @Override public java.lang.String getWEBUI_Shortcut () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_Shortcut); } /** Set Is View Action. @param WEBUI_ViewAction Is View Action */ @Override public void setWEBUI_ViewAction (boolean WEBUI_ViewAction) { set_Value (COLUMNNAME_WEBUI_ViewAction, Boolean.valueOf(WEBUI_ViewAction)); } /** Get Is View Action. @return Is View Action */ @Override public boolean isWEBUI_ViewAction () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewAction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quick action. @param WEBUI_ViewQuickAction Quick action */
@Override public void setWEBUI_ViewQuickAction (boolean WEBUI_ViewQuickAction) { set_Value (COLUMNNAME_WEBUI_ViewQuickAction, Boolean.valueOf(WEBUI_ViewQuickAction)); } /** Get Quick action. @return Quick action */ @Override public boolean isWEBUI_ViewQuickAction () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewQuickAction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Default quick action. @param WEBUI_ViewQuickAction_Default Default quick action */ @Override public void setWEBUI_ViewQuickAction_Default (boolean WEBUI_ViewQuickAction_Default) { set_Value (COLUMNNAME_WEBUI_ViewQuickAction_Default, Boolean.valueOf(WEBUI_ViewQuickAction_Default)); } /** Get Default quick action. @return Default quick action */ @Override public boolean isWEBUI_ViewQuickAction_Default () { Object oo = get_Value(COLUMNNAME_WEBUI_ViewQuickAction_Default); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Process.java
1
请完成以下Java代码
protected TaskEntity verifyTaskParameters(CommandContext commandContext) { TaskEntity task = commandContext.getTaskEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isSuspended()) { throw new ActivitiException("It is not allowed to add an attachment to a suspended task"); } return task; } protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) { ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (execution == null) { throw new ActivitiObjectNotFoundException( "Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class ); } if (execution.isSuspended()) { throw new ActivitiException("It is not allowed to add an attachment to a suspended process instance"); } return execution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\CreateAttachmentCmd.java
1
请完成以下Java代码
public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** RecurringType AD_Reference_ID=282 */ public static final int RECURRINGTYPE_AD_Reference_ID=282; /** Invoice = I */ public static final String RECURRINGTYPE_Invoice = "I"; /** Order = O */ public static final String RECURRINGTYPE_Order = "O"; /** GL Journal = G */ public static final String RECURRINGTYPE_GLJournal = "G"; /** Project = J */ public static final String RECURRINGTYPE_Project = "J"; /** Set Recurring Type. @param RecurringType Type of Recurring Document */ public void setRecurringType (String RecurringType) { set_Value (COLUMNNAME_RecurringType, RecurringType); } /** Get Recurring Type. @return Type of Recurring Document */ public String getRecurringType () { return (String)get_Value(COLUMNNAME_RecurringType); } /** Set Maximum Runs. @param RunsMax Number of recurring runs */ public void setRunsMax (int RunsMax) { set_Value (COLUMNNAME_RunsMax, Integer.valueOf(RunsMax)); } /** Get Maximum Runs. @return Number of recurring runs */ public int getRunsMax () {
Integer ii = (Integer)get_Value(COLUMNNAME_RunsMax); if (ii == null) return 0; return ii.intValue(); } /** Set Remaining Runs. @param RunsRemaining Number of recurring runs remaining */ public void setRunsRemaining (int RunsRemaining) { set_ValueNoCheck (COLUMNNAME_RunsRemaining, Integer.valueOf(RunsRemaining)); } /** Get Remaining Runs. @return Number of recurring runs remaining */ public int getRunsRemaining () { Integer ii = (Integer)get_Value(COLUMNNAME_RunsRemaining); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring.java
1
请完成以下Spring Boot application配置
#production environment server.email: prod@mkyong.com server.cluster[0].ip=192.168.0.1 server.cluster[0].path=/app1 server.cluster[1].ip=192.168.0.2 server.cluster[1].
path=/app2 server.cluster[2].ip=192.168.0.3 server.cluster[2].path=/app3
repos\spring-boot-master\profile-properties\src\main\resources\application-prod.properties
2
请完成以下Java代码
private void dbUpdateCbPartnerIdsFromGlobalID(final ImportRecordsSelection selection) { StringBuilder sql; int no; sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name + " i ") .append("SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p ") .append("WHERE i." + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId) .append("=p." + I_C_BPartner.COLUMNNAME_GlobalId) .append(" AND p.AD_Client_ID=i.AD_Client_ID ") .append(" AND p.IsActive='Y') ") .append("WHERE C_BPartner_ID IS NULL AND " + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId + " IS NOT NULL") .append(" AND " + COLUMNNAME_I_IsImported + "='N'") .append(selection.toSqlWhereClause("i")); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); logger.info("Found BPartner={}", no);
} private void dbUpdateErrorMessages(final ImportRecordsSelection selection) { StringBuilder sql; int no; sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name) .append(" SET " + COLUMNNAME_I_IsImported + "='N', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Partner is mandatory, ' ") .append("WHERE " + I_I_BPartner_GlobalID.COLUMNNAME_C_BPartner_ID + " IS NULL ") .append("AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause()); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); logger.info("Value is mandatory={}", no); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportTableSqlUpdater.java
1
请在Spring Boot框架中完成以下Java代码
public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getAuthorizationUserId() { return authorizationUserId; } public boolean isAuthorizationGroupsSet() { return authorizationGroupsSet; } public String getTenantId() { return tenantId; }
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeAuthorization() { return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty()); } public List<List<String>> getSafeAuthorizationGroups() { return safeAuthorizationGroups; } public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) { this.safeAuthorizationGroups = safeAuthorizationGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CaseDefinitionQueryImpl.java
2
请完成以下Java代码
public void setPP_Order_Node(final org.eevolution.model.I_PP_Order_Node PP_Order_Node) { set_ValueFromPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class, PP_Order_Node); } @Override public int getPP_Order_Node_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_ID); } @Override public void setPP_Order_Node_ID(final int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, PP_Order_Node_ID); } @Override public int getPP_Order_Node_Product_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_Product_ID); } @Override public void setPP_Order_Node_Product_ID(final int PP_Order_Node_Product_ID) { if (PP_Order_Node_Product_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, PP_Order_Node_Product_ID); } @Override public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() { return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class); } @Override public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow) { set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow); } @Override public int getPP_Order_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID); } @Override public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID) { if (PP_Order_Workflow_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty(final @Nullable BigDecimal Qty) { set_Value(COLUMNNAME_Qty, Qty);
} @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNo(final int SeqNo) { set_Value(COLUMNNAME_SeqNo, SeqNo); } @Override public java.lang.String getSpecification() { return get_ValueAsString(COLUMNNAME_Specification); } @Override public void setSpecification(final @Nullable java.lang.String Specification) { set_Value(COLUMNNAME_Specification, Specification); } @Override public BigDecimal getYield() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield(final @Nullable BigDecimal Yield) { set_Value(COLUMNNAME_Yield, Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java
1
请完成以下Java代码
private void setCORSHeaders(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) { final String requestOrigin = httpRequest.getHeader("Origin"); final String accessControlAllowOrigin = getAccessControlAllowOrigin(requestOrigin); httpResponse.setHeader("Access-Control-Allow-Origin", accessControlAllowOrigin); logger.trace("Set Access-Control-Allow-Origin={} (request's Origin={})", accessControlAllowOrigin, requestOrigin); httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT"); // NOTE: Access-Control-Max-Age is browser dependent and each browser as a different max value. // e.g. chrome allows max 600sec=10min and it might be that everything above that is ignored. // see http://stackoverflow.com/questions/23543719/cors-access-control-max-age-is-ignored httpResponse.setHeader("Access-Control-Max-Age", "600"); httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Origin, Accept-Language, Accept, Authorization"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // allow cookies } private String getAccessControlAllowOrigin(final String requestOrigin) { final boolean corsEnabled = !webuiURLs.isCrossSiteUsageAllowed();
if (corsEnabled) { final String frontendURL = webuiURLs.getFrontendURL(); if (!Check.isBlank(frontendURL)) { return frontendURL; } else { logger.warn("Accepting any CORS Origin because even though CORS are enabled, the FrontendURL is not set." + "\n Please and set `{}` SysConfig or allow cross-site-usage (`{}` sysconfig).", WebuiURLs.SYSCONFIG_FRONTEND_URL, WebuiURLs.SYSCONFIG_IsCrossSiteUsageAllowed); } } // Fallback return Check.isBlank(requestOrigin) ? "*" : requestOrigin; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui\web\CORSFilter.java
1
请完成以下Java代码
public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_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(); } /** 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOM.java
1
请完成以下Java代码
public void downloadObject(String bucketName, String objectName) { String s3Url = "s3://" + bucketName + "/" + objectName; try { springCloudS3.downloadS3Object(s3Url); logger.info("{} file download result: {}", objectName, new File(objectName).exists()); } catch (IOException e) { logger.error(e.getMessage(), e); } } public void uploadObject(String bucketName, String objectName) { String s3Url = "s3://" + bucketName + "/" + objectName; File file = new File(objectName); try { springCloudS3.uploadFileToS3(file, s3Url); logger.info("{} file uploaded to S3", objectName); } catch (IOException e) { logger.error(e.getMessage(), e);
} } public void deleteBucket(String bucketName) { logger.trace("Deleting S3 objects under {} bucket...", bucketName); ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName); for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) { logger.info("Deleting S3 object: {}", objectSummary.getKey()); amazonS3.deleteObject(bucketName, objectSummary.getKey()); } logger.info("Deleting S3 bucket: {}", bucketName); amazonS3.deleteBucket(bucketName); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\s3\SpringCloudS3Service.java
1
请完成以下Java代码
public String getValueSql(final Object value, final List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); } else { valueSql = "?"; params.add(value); } if (truncSql == null) { return valueSql; } // note: cast is needed for postgresql, else you get "ERROR: function trunc(unknown, unknown) is not unique" return "TRUNC(?::timestamp, " + DB.TO_STRING(truncSql) + ")"; } /** * @deprecated Please use {@link #convertValue(java.util.Date)} */ @Nullable
@Override @Deprecated public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { return convertValue(TimeUtil.asTimestamp(value)); } public java.util.Date convertValue(final java.util.Date date) { if (date == null) { return null; } return TimeUtil.trunc(date, trunc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateTruncQueryFilterModifier.java
1
请完成以下Java代码
public Map<String, String> getNamespaces() { return namespaceMap; } public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } public String getSourceSystemId() { return sourceSystemId; } public void setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; } public List<String> getUserTaskFormTypes() { return userTaskFormTypes; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public List<String> getStartEventFormTypes() { return startEventFormTypes; }
public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } @JsonIgnore public Object getEventSupport() { return eventSupport; } public void setEventSupport(Object eventSupport) { this.eventSupport = eventSupport; } public String getStartFormKey(String processId) { FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement(); if (initialFlowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) initialFlowElement; return startEvent.getFormKey(); } return null; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAttributeCount() { return attributeCount; } public void setAttributeCount(Integer attributeCount) { this.attributeCount = attributeCount; }
public Integer getParamCount() { return paramCount; } public void setParamCount(Integer paramCount) { this.paramCount = paramCount; } @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(", name=").append(name); sb.append(", attributeCount=").append(attributeCount); sb.append(", paramCount=").append(paramCount); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeCategory.java
1
请完成以下Java代码
public class DefaultRedirectStrategy implements RedirectStrategy { protected final Log logger = LogFactory.getLog(getClass()); private boolean contextRelative; private HttpStatus statusCode = HttpStatus.FOUND; /** * Redirects the response to the supplied URL. * <p> * If <tt>contextRelative</tt> is set, the redirect value will be the value after the * request context path. Note that this will result in the loss of protocol * information (HTTP or HTTPS), so will cause problems if a redirect is being * performed to change to HTTPS, for example. */ @Override public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); redirectUrl = response.encodeRedirectURL(redirectUrl); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Redirecting to %s", redirectUrl)); } if (this.statusCode == HttpStatus.FOUND) { response.sendRedirect(redirectUrl); } else { response.setHeader(HttpHeaders.LOCATION, redirectUrl); response.setStatus(this.statusCode.value()); response.getWriter().flush(); } } protected String calculateRedirectUrl(String contextPath, String url) { if (!UrlUtils.isAbsoluteUrl(url)) { if (isContextRelative()) { return url; } return contextPath + url; } // Full URL, including http(s):// if (!isContextRelative()) { return url; } Assert.isTrue(url.contains(contextPath), "The fully qualified URL does not include context path.");
// Calculate the relative URL from the fully qualified URL, minus the last // occurrence of the scheme and base context. url = url.substring(url.lastIndexOf("://") + 3); url = url.substring(url.indexOf(contextPath) + contextPath.length()); if (url.length() > 1 && url.charAt(0) == '/') { url = url.substring(1); } return url; } /** * If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol * and context path (defaults to <tt>false</tt>). */ public void setContextRelative(boolean useRelativeContext) { this.contextRelative = useRelativeContext; } /** * Returns <tt>true</tt>, if the redirection URL should be calculated minus the * protocol and context path (defaults to <tt>false</tt>). */ protected boolean isContextRelative() { return this.contextRelative; } /** * Sets the HTTP status code to use. The default is {@link HttpStatus#FOUND}. * <p> * Note that according to RFC 7231, with {@link HttpStatus#FOUND}, a user agent MAY * change the request method from POST to GET for the subsequent request. If this * behavior is undesired, {@link HttpStatus#TEMPORARY_REDIRECT} can be used instead. * @param statusCode the HTTP status code to use. * @since 6.2 */ public void setStatusCode(HttpStatus statusCode) { Assert.notNull(statusCode, "statusCode cannot be null"); this.statusCode = statusCode; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\DefaultRedirectStrategy.java
1
请完成以下Java代码
public class DefaultSpringEventRegistryChangeDetectionExecutor implements EventRegistryChangeDetectionExecutor, DisposableBean { protected Duration initialDelay; protected Duration delay; protected TaskScheduler taskScheduler; protected ThreadPoolTaskScheduler threadPoolTaskScheduler; // If non-null, it means the scheduler has been created in this class protected EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager; public DefaultSpringEventRegistryChangeDetectionExecutor(long initialDelayInMs, long delayInMs) { this(initialDelayInMs, delayInMs, null); } public DefaultSpringEventRegistryChangeDetectionExecutor(long initialDelayInMs, long delayInMs, TaskScheduler taskScheduler) { this.initialDelay = Duration.ofMillis(initialDelayInMs); this.delay = Duration.ofMillis(delayInMs); if (taskScheduler != null) { this.taskScheduler = taskScheduler; } else { createDefaultTaskScheduler(); } } protected void createDefaultTaskScheduler() { threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(1); threadPoolTaskScheduler.setThreadNamePrefix("flowable-event-change-detector-"); taskScheduler = threadPoolTaskScheduler; } @Override public void initialize() { if (threadPoolTaskScheduler != null) { threadPoolTaskScheduler.initialize(); } Instant initialInstant = Instant.now().plus(initialDelay); taskScheduler.scheduleWithFixedDelay(createChangeDetectionRunnable(), initialInstant, delay); }
protected Runnable createChangeDetectionRunnable() { return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager); } @Override public void shutdown() { destroy(); } @Override public void destroy() { if (threadPoolTaskScheduler != null) { threadPoolTaskScheduler.destroy(); } } public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() { return eventRegistryChangeDetectionManager; } @Override public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; } public TaskScheduler getTaskScheduler() { return taskScheduler; } public void setTaskScheduler(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\management\DefaultSpringEventRegistryChangeDetectionExecutor.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_K_Category getK_Category() throws RuntimeException { return (I_K_Category)MTable.get(getCtx(), I_K_Category.Table_Name) .getPO(getK_Category_ID(), get_TrxName()); } /** Set Knowledge Category. @param K_Category_ID Knowledge Category */ public void setK_Category_ID (int K_Category_ID) { if (K_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Category_ID, Integer.valueOf(K_Category_ID)); } /** Get Knowledge Category. @return Knowledge Category */ public int getK_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Category Value. @param K_CategoryValue_ID The value of the category */ public void setK_CategoryValue_ID (int K_CategoryValue_ID) { if (K_CategoryValue_ID < 1) set_ValueNoCheck (COLUMNNAME_K_CategoryValue_ID, null); else set_ValueNoCheck (COLUMNNAME_K_CategoryValue_ID, Integer.valueOf(K_CategoryValue_ID)); } /** Get Category Value. @return The value of the category */ public int getK_CategoryValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_CategoryValue_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_CategoryValue.java
1
请完成以下Spring Boot application配置
spring: h2: console: enabled: true datasource: url: jdbc:h2:mem:mydb username: sa password: password driverClassName: org.h2.Driver jpa: database-platform: org.hibernate.dialect.H2Dialect defer-datasource-initialization: true show-sql: true properties: hibernate: format_sql: true generate_statistics: true ## Enable jdbc batch inserts. jdbc.batch_size: 4 order_inserts: true javax.cache.provider: org.ehcache.jsr107.EhcacheCachingProvider cache: ## Enable L2 cache region.fac
tory_class: org.hibernate.cache.jcache.JCacheRegionFactory #jcache use_second_level_cache: true use_query_cache: true jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE sql: init: data-locations: classpath:data-jfr.sql
repos\tutorials-master\persistence-modules\hibernate6\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class DataController { // 1 Spring Data JPA已自动为你注册bean,所以可自动注入 @Autowired PersonService personService; @RequestMapping("/save") public Person save(@RequestBody Person person) { personService.insert(person); return person; } @RequestMapping("/all") public List<Person> sort() {
List<Person> people = personService.findAll(); return people; } @RequestMapping("/page") public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) { Page<Person> pagePeople = personService.findByPage(pageNo, pageSize); return pagePeople; } }
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\controller\DataController.java
2
请在Spring Boot框架中完成以下Java代码
public class Review implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "book_id") private Book book; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @Override
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Review) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Review{" + "id=" + id + ", content=" + content + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Review.java
2
请完成以下Java代码
public void focusGained (FocusEvent e) { m_infocus = true; setText(getText()); // clear } // focusGained /** * Focus Lost * Enabled with Obscure * @param e event */ public void focusLost (FocusEvent e) { m_infocus = false; setText(getText()); // obscure
} // focus Lost // metas @Override public boolean isAutoCommit() { return true; } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VURL
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java
1
请完成以下Java代码
public void save(@NonNull final PaymentReservation reservation) { final I_C_Payment_Reservation record = reservation.getId() != null ? load(reservation.getId(), I_C_Payment_Reservation.class) : newInstance(I_C_Payment_Reservation.class); updateReservationRecord(record, reservation); saveRecord(record); reservation.setId(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID())); } private static void updateReservationRecord( @NonNull final I_C_Payment_Reservation record, @NonNull final PaymentReservation from) { InterfaceWrapperHelper.setValue(record, "AD_Client_ID", from.getClientId().getRepoId()); record.setAD_Org_ID(from.getOrgId().getRepoId()); record.setAmount(from.getAmount().toBigDecimal()); record.setBill_BPartner_ID(from.getPayerContactId().getBpartnerId().getRepoId()); record.setBill_User_ID(from.getPayerContactId().getUserId().getRepoId()); record.setBill_EMail(from.getPayerEmail().getAsString()); record.setC_Currency_ID(from.getAmount().getCurrencyId().getRepoId());
record.setC_Order_ID(from.getSalesOrderId().getRepoId()); record.setDateTrx(TimeUtil.asTimestamp(from.getDateTrx())); record.setPaymentRule(from.getPaymentRule().getCode()); record.setStatus(from.getStatus().getCode()); } private static PaymentReservation toPaymentReservation(@NonNull final I_C_Payment_Reservation record) { final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID()); return PaymentReservation.builder() .id(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID())) .clientId(ClientId.ofRepoId(record.getAD_Client_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .amount(Money.of(record.getAmount(), currencyId)) .payerContactId(BPartnerContactId.ofRepoId(record.getBill_BPartner_ID(), record.getBill_User_ID())) .payerEmail(EMailAddress.ofString(record.getBill_EMail())) .salesOrderId(OrderId.ofRepoId(record.getC_Order_ID())) .dateTrx(TimeUtil.asLocalDate(record.getDateTrx())) .paymentRule(PaymentRule.ofCode(record.getPaymentRule())) .status(PaymentReservationStatus.ofCode(record.getStatus())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationRepository.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<UserResponse> getUsers() { return users; } public void setUsers(List<UserResponse> users) { this.users = users; } public void addUser(UserResponse userRepresentation) { if (users == null) { users = new ArrayList<>(); } users.add(userRepresentation); } public List<GroupResponse> getGroups() {
return groups; } public void setGroups(List<GroupResponse> groups) { this.groups = groups; } public void addGroup(GroupResponse groupRepresentation) { if (groups == null) { groups = new ArrayList<>(); } groups.add(groupRepresentation); } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\privilege\PrivilegeResponse.java
2
请完成以下Java代码
public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } }
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\validationgroup\RegistrationForm.java
1
请在Spring Boot框架中完成以下Java代码
public class RemoveHopByHopHeadersFilter implements HttpHeadersFilter, Ordered { /** * Headers to remove as the result of applying the filter. */ public static final Set<String> HEADERS_REMOVED_ON_REQUEST = new HashSet<>( Arrays.asList("connection", "keep-alive", "transfer-encoding", "te", "trailer", "proxy-authorization", "proxy-authenticate", "x-application-context", "upgrade" // these two are not listed in // https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3 // "proxy-connection", // "content-length", )); private int order = Ordered.LOWEST_PRECEDENCE - 1; private Set<String> headers = HEADERS_REMOVED_ON_REQUEST; public Set<String> getHeaders() { return headers; } public void setHeaders(Set<String> headers) { Objects.requireNonNull(headers, "headers may not be null"); this.headers = headers.stream().map(String::toLowerCase).collect(Collectors.toSet()); } @Override public int getOrder() { return order; } public void setOrder(int order) { this.order = order; }
@Override public HttpHeaders filter(HttpHeaders originalHeaders, ServerWebExchange exchange) { HttpHeaders filtered = new HttpHeaders(); List<String> connectionOptions = originalHeaders.getConnection().stream().map(String::toLowerCase).toList(); Set<String> headersToRemove = new HashSet<>(headers); headersToRemove.addAll(connectionOptions); for (Map.Entry<String, List<String>> entry : originalHeaders.headerSet()) { if (!headersToRemove.contains(entry.getKey().toLowerCase(Locale.ROOT))) { filtered.addAll(entry.getKey(), entry.getValue()); } } return filtered; } @Override public boolean supports(Type type) { return type.equals(Type.REQUEST) || type.equals(Type.RESPONSE); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\RemoveHopByHopHeadersFilter.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/admin*") .hasAnyRole("ADMIN") .anyRequest() .authenticated()) .formLogin(Customizer.withDefaults()) .apply(clientErrorLogging()); return http.build(); } @Bean public ClientErrorLoggingConfigurer clientErrorLogging() { return new ClientErrorLoggingConfigurer(); }
@Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user1 = User.withUsername("user1") .password(passwordEncoder().encode("user")) .roles("USER") .build(); UserDetails admin = User.withUsername("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1, admin); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\spring-security-modules\spring-security-core-3\src\main\java\com\baeldung\dsl\SecurityConfig.java
2
请完成以下Java代码
public Builder setM_Material_Tracking(final I_M_Material_Tracking materialTracking) { _materialTracking = materialTracking; return this; } private int getM_Material_Tracking_ID() { Check.assumeNotNull(_materialTracking, "_materialTracking not null"); return _materialTracking.getM_Material_Tracking_ID(); } public Builder setAllProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders) { _allProductionOrders = qualityInspectionOrders; return this; } private List<IQualityInspectionOrder> getProductionOrders() { Check.assumeNotNull(_allProductionOrders, "_qualityInspectionOrders not null"); return _allProductionOrders; }
public Builder setNotYetInvoicedProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders) { _notYetInvoicedPPOrderIDs = new HashSet<>(); for (final IQualityInspectionOrder order : qualityInspectionOrders) { _notYetInvoicedPPOrderIDs.add(order.getPP_Order().getPP_Order_ID()); } return this; } private Set<Integer> getNotYetInvoicedPPOrderIDs() { Check.assumeNotNull(_notYetInvoicedPPOrderIDs, "_notYetInvoicedProductionOrders not null"); return _notYetInvoicedPPOrderIDs; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocumentsPricingInfo.java
1
请完成以下Java代码
public boolean isPrinted () { Object oo = get_Value(COLUMNNAME_IsPrinted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Max Value. @param MaxValue Max Value */ public void setMaxValue (int MaxValue) { set_Value (COLUMNNAME_MaxValue, Integer.valueOf(MaxValue)); } /** Get Max Value. @return Max Value */ public int getMaxValue () { Integer ii = (Integer)get_Value(COLUMNNAME_MaxValue); if (ii == null) return 0; return ii.intValue(); } /** Set Min Value. @param MinValue Min Value */ public void setMinValue (int MinValue) { set_Value (COLUMNNAME_MinValue, Integer.valueOf(MinValue)); } /** Get Min Value. @return Min Value */ public int getMinValue () { Integer ii = (Integer)get_Value(COLUMNNAME_MinValue); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Service date. @param ServiceDate Date service was provided */ public void setServiceDate (Timestamp ServiceDate) { set_Value (COLUMNNAME_ServiceDate, ServiceDate); } /** Get Service date. @return Date service was provided */ public Timestamp getServiceDate () { return (Timestamp)get_Value(COLUMNNAME_ServiceDate); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg)
{ set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java
1
请完成以下Java代码
public class ExternalWorkerTaskCompleteJobHandler implements JobHandler { public static final String TYPE = "external-worker-complete"; @Override public String getType() { return TYPE; } @Override public void execute(Job job, String configuration, ExecutionEntity execution, CommandContext commandContext) { VariableInstanceEntityManager variableInstanceEntityManager = commandContext.getVariableInstanceEntityManager(); List<VariableInstanceEntity> jobVariables = variableInstanceEntityManager.findVariableInstancesBySubScopeIdAndScopeType(execution.getId(), ScopeTypes.BPMN_EXTERNAL_WORKER); for (VariableInstanceEntity jobVariable : jobVariables) { execution.setVariable(jobVariable.getName(), jobVariable.getValue()); variableInstanceEntityManager.delete(jobVariable);
} if (configuration != null && configuration.startsWith("error:")) { String errorCode; if (configuration.length() > 6) { errorCode = configuration.substring(6); } else { errorCode = null; } ErrorPropagation.propagateError(errorCode, execution); } else { execution.signal(null, null); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\ExternalWorkerTaskCompleteJobHandler.java
1
请完成以下Java代码
public void setMailText3 (String MailText3) { set_Value (COLUMNNAME_MailText3, MailText3); } /** Get Mail Text 3. @return Optional third text part used for Mail message */ public String getMailText3 () { return (String)get_Value(COLUMNNAME_MailText3); } /** 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 Mail Template. @param R_MailText_ID Text templates for mailings */ public void setR_MailText_ID (int R_MailText_ID) { if (R_MailText_ID < 1) set_ValueNoCheck (COLUMNNAME_R_MailText_ID, null); else set_ValueNoCheck (COLUMNNAME_R_MailText_ID, Integer.valueOf(R_MailText_ID)); } /** Get Mail Template. @return Text templates for mailings */ public int getR_MailText_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_MailText.java
1
请完成以下Java代码
private static List<RemotePurchaseOrderCreatedItem> createResponseItems( @NonNull final MSV3PurchaseOrderTransaction purchaseTransaction, @NonNull final Map<OrderCreateRequestPackageItemId, PurchaseOrderRequestItem> purchaseOrderRequestItems) { if (purchaseTransaction.getResponse() == null) { return ImmutableList.of(); } final OrderCreateRequest request = purchaseTransaction.getRequest(); final ImmutableList.Builder<RemotePurchaseOrderCreatedItem> purchaseOrderResponseItems = ImmutableList.builder(); final List<OrderResponsePackage> responseOrders = purchaseTransaction .getResponse() .getOrderPackages(); for (int orderIdx = 0; orderIdx < responseOrders.size(); orderIdx++) { final OrderCreateRequestPackage requestOrder = request.getOrderPackages().get(orderIdx); final OrderResponsePackage responseOrder = responseOrders.get(orderIdx); final List<OrderCreateRequestPackageItem> requestItems = requestOrder.getItems(); final List<OrderResponsePackageItem> responseItems = responseOrder.getItems(); for (int itemIdx = 0; itemIdx < responseItems.size(); itemIdx++) { final OrderCreateRequestPackageItem requestItem = requestItems.get(itemIdx);
final OrderResponsePackageItem responseItem = responseItems.get(itemIdx); final RemotePurchaseOrderCreatedItemBuilder builder = RemotePurchaseOrderCreatedItem.builder() .remotePurchaseOrderId(responseOrder.getId().getValueAsString()) .correspondingRequestItem(purchaseOrderRequestItems.get(requestItem.getId())); for (final OrderResponsePackageItemPart responseItemPart : responseItem.getParts()) { final Type type = responseItemPart.getType(); if (type.isNoDeliveryPossible()) { continue; } final MSV3OrderResponsePackageItemPartRepoId internalItemId = purchaseTransaction.getResponseItemPartRepoId(responseItemPart.getId()); builder .confirmedDeliveryDateOrNull(responseItemPart.getDeliveryDate()) .confirmedOrderQuantity(responseItemPart.getQty().getValueAsBigDecimal()) .internalItemId(internalItemId); purchaseOrderResponseItems.add(builder.build()); } } } return purchaseOrderResponseItems.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderClientImpl.java
1
请完成以下Java代码
protected void ensureDeploymentsWithIdsExists(Set<String> expected, List<DeploymentEntity> actual) { Map<String, DeploymentEntity> deploymentMap = new HashMap<>(); for (DeploymentEntity deployment : actual) { deploymentMap.put(deployment.getId(), deployment); } List<String> missingDeployments = getMissingElements(expected, deploymentMap); if (!missingDeployments.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The following deployments are not found by id: "); builder.append(StringUtil.join(missingDeployments.iterator())); throw new NotFoundException(builder.toString()); } } protected void ensureResourcesWithIdsExist(String deploymentId, Set<String> expectedIds, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getId(), resource); } ensureResourcesWithKeysExist(deploymentId, expectedIds, resources, "id"); } protected void ensureResourcesWithNamesExist(String deploymentId, Set<String> expectedNames, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getName(), resource);
} ensureResourcesWithKeysExist(deploymentId, expectedNames, resources, "name"); } protected void ensureResourcesWithKeysExist(String deploymentId, Set<String> expectedKeys, Map<String, ResourceEntity> actual, String valueProperty) { List<String> missingResources = getMissingElements(expectedKeys, actual); if (!missingResources.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The deployment with id '"); builder.append(deploymentId); builder.append("' does not contain the following resources with "); builder.append(valueProperty); builder.append(": "); builder.append(StringUtil.join(missingResources.iterator())); throw new NotFoundException(builder.toString()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeployCmd.java
1
请在Spring Boot框架中完成以下Java代码
public BatchEntity createBatch(BatchBuilder batchBuilder) { BatchEntity batchEntity = dataManager.create(); batchEntity.setBatchType(batchBuilder.getBatchType()); batchEntity.setBatchSearchKey(batchBuilder.getSearchKey()); batchEntity.setBatchSearchKey2(batchBuilder.getSearchKey2()); batchEntity.setCreateTime(getClock().getCurrentTime()); batchEntity.setStatus(batchBuilder.getStatus()); batchEntity.setBatchDocumentJson(batchBuilder.getBatchDocumentJson(), serviceConfiguration.getEngineName()); batchEntity.setTenantId(batchBuilder.getTenantId()); dataManager.insert(batchEntity); return batchEntity; } @Override public Batch completeBatch(String batchId, String status) { BatchEntity batchEntity = findById(batchId); batchEntity.setCompleteTime(getClock().getCurrentTime()); batchEntity.setStatus(status); return batchEntity; } @Override public void deleteBatches(BatchQueryImpl batchQuery) { dataManager.deleteBatches(batchQuery); } @Override public void delete(String batchId) { BatchEntity batch = dataManager.findById(batchId); List<BatchPart> batchParts = getBatchPartEntityManager().findBatchPartsByBatchId(batch.getId()); if (batchParts != null && batchParts.size() > 0) {
for (BatchPart batchPart : batchParts) { getBatchPartEntityManager().deleteBatchPartEntityAndResources((BatchPartEntity) batchPart); } } ByteArrayRef batchDocRefId = batch.getBatchDocRefId(); if (batchDocRefId != null && batchDocRefId.getId() != null) { batchDocRefId.delete(serviceConfiguration.getEngineName()); } delete(batch); } protected BatchPartEntityManager getBatchPartEntityManager() { return serviceConfiguration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchEntityManagerImpl.java
2
请完成以下Java代码
public LocalDate getDocumentDate(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(productBom.getAD_Org_ID())); return TimeUtil.asLocalDate(productBom.getDateDoc(), timeZone); } @Override public String completeIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBomRecord = extractProductBom(docFields); productBomRecord.setDocAction(X_C_RemittanceAdvice.DOCACTION_Re_Activate); productBomRecord.setProcessed(true); return X_PP_Product_BOM.DOCSTATUS_Completed;
} @Override public void reactivateIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); productBom.setProcessed(false); productBom.setDocAction(X_PP_Product_BOM.DOCACTION_Complete); } private static I_PP_Product_BOM extractProductBom(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_PP_Product_BOM.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\document\PP_Product_BOM_DocHandler.java
1
请在Spring Boot框架中完成以下Java代码
public UniversalBankTransactionType getUniversalBankTransaction() { return universalBankTransaction; } /** * Sets the value of the universalBankTransaction property. * * @param value * allowed object is * {@link UniversalBankTransactionType } * */ public void setUniversalBankTransaction(UniversalBankTransactionType value) { this.universalBankTransaction = value; } /** * Indicates that no payment takes place as a result of this invoice. * * @return * possible object is * {@link NoPaymentType } * */ public NoPaymentType getNoPayment() { return noPayment; } /** * Sets the value of the noPayment property. * * @param value * allowed object is * {@link NoPaymentType } * */ public void setNoPayment(NoPaymentType value) { this.noPayment = value; } /** * Indicates that a direct debit will take place as a result of this invoice. * * @return * possible object is * {@link DirectDebitType } * */ public DirectDebitType getDirectDebit() { return directDebit; } /** * Sets the value of the directDebit property. * * @param value * allowed object is
* {@link DirectDebitType } * */ public void setDirectDebit(DirectDebitType value) { this.directDebit = value; } /** * Used to denote details about a SEPA direct debit, via which this invoice has to be paid. * * @return * possible object is * {@link SEPADirectDebitType } * */ public SEPADirectDebitType getSEPADirectDebit() { return sepaDirectDebit; } /** * Sets the value of the sepaDirectDebit property. * * @param value * allowed object is * {@link SEPADirectDebitType } * */ public void setSEPADirectDebit(SEPADirectDebitType value) { this.sepaDirectDebit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentMethodType.java
2
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue private Long id; @Size(min = 2, message = "First name must have at least 2 characters") private String firstName; @Size(min = 2, message = "Last name must have at least 2 characters") private String lastName; public Employee() { } public Employee(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return String.format("Employee[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\data\Employee.java
2
请完成以下Java代码
public class HitPolicyEntry { protected final HitPolicy hitPolicy; protected final BuiltinAggregator aggregator; public HitPolicyEntry(HitPolicy hitPolicy, BuiltinAggregator builtinAggregator) { this.hitPolicy = hitPolicy; this.aggregator = builtinAggregator; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HitPolicyEntry that = (HitPolicyEntry) o; if (hitPolicy != that.hitPolicy) return false; return aggregator == that.aggregator;
} @Override public int hashCode() { int result = hitPolicy != null ? hitPolicy.hashCode() : 0; result = 31 * result + (aggregator != null ? aggregator.hashCode() : 0); return result; } public HitPolicy getHitPolicy() { return hitPolicy; } public BuiltinAggregator getAggregator() { return aggregator; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\HitPolicyEntry.java
1
请完成以下Java代码
public static Integer getOK() { return OK; } public static Integer getERROR() { return ERROR; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message;
} public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
repos\SpringBoot-Learning-master\1.x\Chapter3-1-6\src\main\java\com\didispace\dto\ErrorInfo.java
1
请完成以下Java代码
public EvaluationContext createEvaluationContext(Collection<? extends Cache> caches, Method method, Object[] args, Object target, Class<?> targetClass, Object result, BeanFactory beanFactory) { CacheExpressionRootObject rootObject = new CacheExpressionRootObject( caches, method, args, target, targetClass); Method targetMethod = getTargetMethod(targetClass, method); CacheEvaluationContext evaluationContext = new CacheEvaluationContext( rootObject, targetMethod, args, getParameterNameDiscoverer()); if (result == RESULT_UNAVAILABLE) { evaluationContext.addUnavailableVariable(RESULT_VARIABLE); } else if (result != NO_RESULT) { evaluationContext.setVariable(RESULT_VARIABLE, result); } if (beanFactory != null) { evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory)); } return evaluationContext; } public Object key(String keyExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) { return getExpression(this.keyCache, methodKey, keyExpression).getValue(evalContext); } public boolean condition(String conditionExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) { return getExpression(this.conditionCache, methodKey, conditionExpression).getValue(evalContext, boolean.class); } public boolean unless(String unlessExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return getExpression(this.unlessCache, methodKey, unlessExpression).getValue(evalContext, boolean.class); } /** * Clear all caches. */ void clear() { this.keyCache.clear(); this.conditionCache.clear(); this.unlessCache.clear(); this.targetMethodCache.clear(); } private Method getTargetMethod(Class<?> targetClass, Method method) { AnnotatedElementKey methodKey = new AnnotatedElementKey(method, targetClass); Method targetMethod = this.targetMethodCache.get(methodKey); if (targetMethod == null) { targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); if (targetMethod == null) { targetMethod = method; } this.targetMethodCache.put(methodKey, targetMethod); } return targetMethod; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\expression\CacheOperationExpressionEvaluator.java
1
请在Spring Boot框架中完成以下Java代码
private ConnectionFactoryBeanCreationException connectionFactoryBeanCreationException(String message, @Nullable String r2dbcUrl, EmbeddedDatabaseConnection embeddedDatabaseConnection) { return new ConnectionFactoryBeanCreationException(message, r2dbcUrl, embeddedDatabaseConnection); } private @Nullable String ifHasText(@Nullable String candidate) { return (StringUtils.hasText(candidate)) ? candidate : null; } static class ConnectionFactoryBeanCreationException extends BeanCreationException { private final @Nullable String url; private final EmbeddedDatabaseConnection embeddedDatabaseConnection; ConnectionFactoryBeanCreationException(String message, @Nullable String url, EmbeddedDatabaseConnection embeddedDatabaseConnection) { super(message);
this.url = url; this.embeddedDatabaseConnection = embeddedDatabaseConnection; } @Nullable String getUrl() { return this.url; } EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() { return this.embeddedDatabaseConnection; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryOptionsInitializer.java
2
请完成以下Java代码
protected boolean isNullModel(final I_M_AttributeSetInstance model) { if (model == null) { return true; } // Case: null marker was returned. See "getModelFromObject" method. return model.getM_AttributeSetInstance_ID() <= 0; } @Override protected ASIWithPackingItemTemplateAttributeStorage createAttributeStorage(final I_M_AttributeSetInstance model) { return new ASIWithPackingItemTemplateAttributeStorage(this, model); } @Override
public IAttributeStorage getAttributeStorageIfHandled(final Object modelObj) { final I_M_AttributeSetInstance asi = getModelFromObject(modelObj); if (asi == null) { return null; } // Case: this modelObj is handled by this factory but there was no ASI value set // => don't go forward and ask other factories but instead return an NullAttributeStorage if (asi.getM_AttributeSetInstance_ID() <= 0) { return NullAttributeStorage.instance; } return getAttributeStorageForModel(asi); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ASIAwareAttributeStorageFactory.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_RMALine getM_RMALine() throws RuntimeException { return (org.compiere.model.I_M_RMALine)MTable.get(getCtx(), org.compiere.model.I_M_RMALine.Table_Name) .getPO(getM_RMALine_ID(), get_TrxName()); } /** Set RMA-Position. @param M_RMALine_ID Return Material Authorization Line */ public void setM_RMALine_ID (int M_RMALine_ID) { if (M_RMALine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_RMALine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_RMALine_ID, Integer.valueOf(M_RMALine_ID)); } /** Get RMA-Position. @return Return Material Authorization Line */ public int getM_RMALine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RMALine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Einzelpreis. @param PriceActual Effektiver Preis */ public void setPriceActual (BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ public BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return Env.ZERO; return bd; } /** Set Verarbeitet. @param Processed The document has been processed */ public void setProcessed (boolean Processed) {
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param QtyEntered Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity Invoiced. @param QtyInvoiced Invoiced Quantity */ public void setQtyInvoiced (BigDecimal QtyInvoiced) { set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Quantity Invoiced. @return Invoiced Quantity */ public BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java
1
请完成以下Java代码
private static UserRolePermissionsKey extractUserRolePermissionsKey(final IValidationContext evalCtx) { return UserRolePermissionsKey.fromEvaluatee(evalCtx, LookupDataSourceContext.PARAM_UserRolePermissionsKey.getName()); } private static String extractContextTableName(final IValidationContext evalCtx) { final String contextTableName = evalCtx.get_ValueAsString(IValidationContext.PARAMETER_ContextTableName); if (Check.isEmpty(contextTableName)) { throw new AdempiereException("Failed getting " + IValidationContext.PARAMETER_ContextTableName + " from " + evalCtx); } return contextTableName; } private static String extractDocStatus(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_DocStatus); } private static DocTypeId extractDocTypeId(final IValidationContext evalCtx) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocType_ID, -1)); if (docTypeId != null) { return docTypeId; } return DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocTypeTarget_ID, -1)); } private static SOTrx extractSOTrx(final IValidationContext evalCtx) { return SOTrx.ofBoolean(evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_IsSOTrx, false)); }
private static boolean extractProcessing(final IValidationContext evalCtx) { final Boolean valueAsBoolean = evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_Processing, false); return valueAsBoolean != null && valueAsBoolean; } private static String extractOrderType(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_OrderType); } @Override public Set<String> getParameters(@Nullable final String contextTableName) { final HashSet<String> parameters = new HashSet<>(PARAMETERS); final IDocActionOptionsBL docActionOptionsBL = Services.get(IDocActionOptionsBL.class); parameters.addAll(docActionOptionsBL.getRequiredParameters(contextTableName)); return parameters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\DocActionValidationRule.java
1
请完成以下Java代码
public void setVHU_Source_ID (final int VHU_Source_ID) { if (VHU_Source_ID < 1) set_Value (COLUMNNAME_VHU_Source_ID, null); else set_Value (COLUMNNAME_VHU_Source_ID, VHU_Source_ID); } @Override public int getVHU_Source_ID() { return get_ValueAsInt(COLUMNNAME_VHU_Source_ID); } /** * VHUStatus AD_Reference_ID=540478 * Reference name: HUStatus */ public static final int VHUSTATUS_AD_Reference_ID=540478; /** Planning = P */ public static final String VHUSTATUS_Planning = "P"; /** Active = A */ public static final String VHUSTATUS_Active = "A"; /** Destroyed = D */ public static final String VHUSTATUS_Destroyed = "D"; /** Picked = S */
public static final String VHUSTATUS_Picked = "S"; /** Shipped = E */ public static final String VHUSTATUS_Shipped = "E"; /** Issued = I */ public static final String VHUSTATUS_Issued = "I"; @Override public void setVHUStatus (final java.lang.String VHUStatus) { set_ValueNoCheck (COLUMNNAME_VHUStatus, VHUStatus); } @Override public java.lang.String getVHUStatus() { return get_ValueAsString(COLUMNNAME_VHUStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trace.java
1
请完成以下Java代码
public boolean processIt(final String processAction) { m_processMsg = null; return Services.get(IDocumentBL.class).processIt(this, processAction); } @Override public boolean reActivateIt() { log.info(toString()); // Before reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE); if (m_processMsg != null) return false; setProcessed(false); setDocAction(DOCACTION_Complete); // After reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE); if (m_processMsg != null) return false; return true; } // reActivateIt @Override public boolean rejectIt() { return true; } @Override public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return true; } // reverseAccrualIt @Override public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false;
// After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return true; } /** * Unlock Document. * * @return true if success */ @Override public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt @Override public boolean voidIt() { return false; } @Override public int getC_Currency_ID() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateConditions.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiKeyAuthenticationProvider extends AbstractAuthenticationProvider { private final ApiKeyService apiKeyService; public ApiKeyAuthenticationProvider(ApiKeyService apiKeyService, UserAuthDetailsCache userAuthDetailsCache) { super(null, userAuthDetailsCache); this.apiKeyService = apiKeyService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { ApiKeyAuthRequest apiKeyAuthRequest = (ApiKeyAuthRequest) authentication.getCredentials(); SecurityUser securityUser = authenticate(apiKeyAuthRequest.apiKey()); return new ApiKeyAuthenticationToken(securityUser); } private SecurityUser authenticate(String key) { if (StringUtils.isEmpty(key)) { throw new BadCredentialsException("Empty API key"); }
ApiKey apiKey = apiKeyService.findApiKeyByValue(key); if (apiKey == null) { throw new BadCredentialsException("User not found for the provided API key"); } if (!apiKey.isEnabled()) { throw new DisabledException("API key auth is not active"); } if (apiKey.getExpirationTime() != 0 && apiKey.getExpirationTime() < System.currentTimeMillis()) { throw new CredentialsExpiredException("API key is expired"); } return super.authenticateByUserId(apiKey.getTenantId(), apiKey.getUserId()); } @Override public boolean supports(Class<?> authentication) { return ApiKeyAuthenticationToken.class.isAssignableFrom(authentication); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\pat\ApiKeyAuthenticationProvider.java
2
请完成以下Java代码
public void registerIfAbsent() { final ITableCacheConfig cacheConfig = create(); final boolean override = false; cacheService.addTableCacheConfig(cacheConfig, override); } @Override public ITableCacheConfig create() { final IMutableTableCacheConfig cacheConfig = new MutableTableCacheConfig(tableName); cacheConfig.setEnabled(isEnabled()); cacheConfig.setTrxLevel(getTrxLevel()); cacheConfig.setCacheMapType(getCacheMapType()); cacheConfig.setExpireMinutes(getExpireMinutes()); cacheConfig.setInitialCapacity(getInitialCapacity()); cacheConfig.setMaxCapacity(getMaxCapacity()); return cacheConfig; } @Override public ITableCacheConfigBuilder setTemplate(final ITableCacheConfig template) { this.template = template; return this; } @Override public ITableCacheConfigBuilder setEnabled(final boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { if (enabled != null) { return enabled; } if (template != null) { return template.isEnabled(); } throw new IllegalStateException("Cannot get IsEnabled"); } @Override public ITableCacheConfigBuilder setTrxLevel(final TrxLevel trxLevel) { this.trxLevel = trxLevel; return this; } public TrxLevel getTrxLevel() { if (trxLevel != null) { return trxLevel; } if (template != null) { return template.getTrxLevel(); } throw new IllegalStateException("Cannot get TrxLevel"); } @Override public ITableCacheConfigBuilder setCacheMapType(final CacheMapType cacheMapType) { this.cacheMapType = cacheMapType; return this; } public CacheMapType getCacheMapType() { if (cacheMapType != null) { return cacheMapType; }
if (template != null) { return template.getCacheMapType(); } throw new IllegalStateException("Cannot get CacheMapType"); } public int getInitialCapacity() { if (initialCapacity > 0) { return initialCapacity; } else if (template != null) { return template.getInitialCapacity(); } throw new IllegalStateException("Cannot get InitialCapacity"); } @Override public ITableCacheConfigBuilder setInitialCapacity(final int initialCapacity) { this.initialCapacity = initialCapacity; return this; } public int getMaxCapacity() { if (maxCapacity > 0) { return maxCapacity; } else if (template != null) { return template.getMaxCapacity(); } return -1; } @Override public ITableCacheConfigBuilder setMaxCapacity(final int maxCapacity) { this.maxCapacity = maxCapacity; return this; } public int getExpireMinutes() { if (expireMinutes > 0 || expireMinutes == ITableCacheConfig.EXPIREMINUTES_Never) { return expireMinutes; } else if (template != null) { return template.getExpireMinutes(); } throw new IllegalStateException("Cannot get ExpireMinutes"); } @Override public ITableCacheConfigBuilder setExpireMinutes(final int expireMinutes) { this.expireMinutes = expireMinutes; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheConfigBuilder.java
1
请完成以下Java代码
public AmountAndCurrencyExchangeDetails3 getAnncdPstngAmt() { return anncdPstngAmt; } /** * Sets the value of the anncdPstngAmt property. * * @param value * allowed object is * {@link AmountAndCurrencyExchangeDetails3 } * */ public void setAnncdPstngAmt(AmountAndCurrencyExchangeDetails3 value) { this.anncdPstngAmt = value; } /** * Gets the value of the prtryAmt property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtryAmt property.
* * <p> * For example, to add a new item, do as follows: * <pre> * getPrtryAmt().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AmountAndCurrencyExchangeDetails4 } * * */ public List<AmountAndCurrencyExchangeDetails4> getPrtryAmt() { if (prtryAmt == null) { prtryAmt = new ArrayList<AmountAndCurrencyExchangeDetails4>(); } return this.prtryAmt; } }
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\AmountAndCurrencyExchange3.java
1
请完成以下Java代码
public List<Order> handle(FindAllOrderedProductsQuery query) { return new ArrayList<>(orders.values()); } @QueryHandler public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) { return Mono.fromCallable(orders::values) .flatMapMany(Flux::fromIterable); } @QueryHandler public Integer handle(TotalProductsShippedQuery query) { return orders.values() .stream() .filter(o -> o.getOrderStatus() == OrderStatus.SHIPPED) .map(o -> Optional.ofNullable(o.getProducts() .get(query.getProductId())) .orElse(0)) .reduce(0, Integer::sum); }
@QueryHandler public Order handle(OrderUpdatesQuery query) { return orders.get(query.getOrderId()); } private void emitUpdate(Order order) { emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId() .equals(q.getOrderId()), order); } @Override public void reset(List<Order> orderList) { orders.clear(); orderList.forEach(o -> orders.put(o.getOrderId(), o)); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\InMemoryOrdersEventHandler.java
1
请完成以下Java代码
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框架中完成以下Java代码
public Map<ShipmentScheduleId, de.metas.handlingunits.model.I_M_ShipmentSchedule> getByIdsAsRecordMap(@NonNull final Set<ShipmentScheduleId> ids) { return huShipmentScheduleBL.getByIds(ids); } public I_M_ShipmentSchedule getByIdAsRecord(@NonNull final ShipmentScheduleId id) { return huShipmentScheduleBL.getById(id); } public Quantity getQtyToDeliver(@NonNull final I_M_ShipmentSchedule schedule) { return huShipmentScheduleBL.getQtyToDeliver(schedule); } public Quantity getQtyScheduledForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord) { return huShipmentScheduleBL.getQtyScheduledForPicking(shipmentScheduleRecord); } public ImmutableList<ShipmentSchedule> getBy(@NonNull final ShipmentScheduleQuery query) { return shipmentScheduleRepository.getBy(query); } private ShipmentScheduleInfo fromRecord(final I_M_ShipmentSchedule shipmentSchedule) { return ShipmentScheduleInfo.builder() .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID())) .warehouseId(shipmentScheduleBL.getWarehouseId(shipmentSchedule)) .bpartnerId(shipmentScheduleBL.getBPartnerId(shipmentSchedule)) .salesOrderLineId(Optional.ofNullable(OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID()))) .productId(ProductId.ofRepoId(shipmentSchedule.getM_Product_ID())) .asiId(AttributeSetInstanceId.ofRepoIdOrNone(shipmentSchedule.getM_AttributeSetInstance_ID())) .bestBeforePolicy(ShipmentAllocationBestBeforePolicy.optionalOfNullableCode(shipmentSchedule.getShipmentAllocation_BestBefore_Policy())) .record(shipmentSchedule) .build(); } public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request) {
huShipmentScheduleBL.addQtyPickedAndUpdateHU(request); } public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId) { huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId); } public Stream<Packageable> stream(@NonNull final PackageableQuery query) { return packagingDAO.stream(query); } public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord) { return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord); } public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds); } public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache() { return huShipmentScheduleBL.newLoadingCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java
2
请完成以下Java代码
public class AD_BoilerPlate_Report extends JavaProcess { private String p_MsgText = null; private int p_AD_PrintFormat_ID = -1; @Override protected void prepare() { for (ProcessInfoParameter para : getParametersAsArray()) { final String name = para.getParameterName(); if (para.getParameter() == null) ; else if (X_T_BoilerPlate_Spool.COLUMNNAME_MsgText.equals(name)) { p_MsgText = para.getParameter().toString(); } else if ("AD_PrintFormat_ID".equals(name)) { p_AD_PrintFormat_ID = para.getParameterAsInt(); } } // if (p_MsgText == null && MADBoilerPlate.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { final MADBoilerPlate bp = new MADBoilerPlate(getCtx(), getRecord_ID(), get_TrxName()); p_MsgText = bp.getTextSnippetParsed(null); } } @Override protected String doIt() throws Exception { createRecord(p_MsgText); // // Set Custom PrintFormat if needed if (p_AD_PrintFormat_ID > 0) { final MPrintFormat pf = MPrintFormat.get(getCtx(), p_AD_PrintFormat_ID, false); getResult().setPrintFormat(pf); } //
// Jasper Report else if (isJasperReport()) { startJasper(); } return "OK"; } private void createRecord(String text) { MADBoilerPlate.createSpoolRecord(getCtx(), getAD_Client_ID(), getPinstanceId(), text, get_TrxName()); } private boolean isJasperReport() { final String whereClause = I_AD_Process.COLUMNNAME_AD_Process_ID + "=?" + " AND " + I_AD_Process.COLUMNNAME_JasperReport + " IS NOT NULL"; return new Query(getCtx(), I_AD_Process.Table_Name, whereClause, get_TrxName()) .setParameters(getProcessInfo().getAdProcessId()) .anyMatch(); } private void startJasper() { ProcessInfo.builder() .setCtx(getCtx()) .setProcessCalledFrom(getProcessInfo().getProcessCalledFrom()) .setAD_Client_ID(getAD_Client_ID()) .setAD_User_ID(getAD_User_ID()) .setPInstanceId(getPinstanceId()) .setAD_Process_ID(0) .setTableName(I_T_BoilerPlate_Spool.Table_Name) // .buildAndPrepareExecution() .onErrorThrowException() .executeSync(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilerPlate_Report.java
1
请完成以下Java代码
public DeserializationHandlerResponse handle(ErrorHandlerContext context, ConsumerRecord<byte[], byte[]> record, Exception exception) { if (this.recoverer == null) { return DeserializationHandlerResponse.FAIL; } try { this.recoverer.accept(record, exception); return DeserializationHandlerResponse.CONTINUE; } catch (RuntimeException e) { LOGGER.error("Recoverer threw an exception; recovery failed", e); return DeserializationHandlerResponse.FAIL; } } @Override public void configure(Map<String, ?> configs) { if (configs.containsKey(KSTREAM_DESERIALIZATION_RECOVERER)) { Object configValue = configs.get(KSTREAM_DESERIALIZATION_RECOVERER); if (configValue instanceof ConsumerRecordRecoverer) { this.recoverer = (ConsumerRecordRecoverer) configValue; } else if (configValue instanceof String) { fromString(configValue); } else if (configValue instanceof Class) { fromClass(configValue); } else { LOGGER.error("Unknown property type for " + KSTREAM_DESERIALIZATION_RECOVERER + "; failed deserializations cannot be recovered"); } } } private void fromString(Object configValue) throws LinkageError {
try { @SuppressWarnings("unchecked") Class<? extends ConsumerRecordRecoverer> clazz = (Class<? extends ConsumerRecordRecoverer>) ClassUtils .forName((String) configValue, RecoveringDeserializationExceptionHandler.class.getClassLoader()); Constructor<? extends ConsumerRecordRecoverer> constructor = clazz.getConstructor(); this.recoverer = constructor.newInstance(); } catch (Exception e) { LOGGER.error("Failed to instantiate recoverer, failed deserializations cannot be recovered", e); } } private void fromClass(Object configValue) { try { @SuppressWarnings("unchecked") Class<? extends ConsumerRecordRecoverer> clazz = (Class<? extends ConsumerRecordRecoverer>) configValue; Constructor<? extends ConsumerRecordRecoverer> constructor = clazz.getConstructor(); this.recoverer = constructor.newInstance(); } catch (Exception e) { LOGGER.error("Failed to instantiate recoverer, failed deserializations cannot be recovered", e); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\streams\RecoveringDeserializationExceptionHandler.java
1
请完成以下Java代码
public final class StringUtil { /** * Checks whether a String seams to be an expression or not * * @param text the text to check * @return true if the text seams to be an expression false otherwise */ public static boolean isExpression(String text) { if (text == null) { return false; } text = text.trim(); return text.startsWith("${") || text.startsWith("#{"); } /** * Splits a String by an expression. * * @param text the text to split * @param regex the regex to split by * @return the parts of the text or null if text was null */ public static String[] split(String text, String regex) { if (text == null) { return null; } else if (regex == null) { return new String[] { text }; } else { String[] result = text.split(regex); for (int i = 0; i < result.length; i++) { result[i] = result[i].trim(); } return result; } } /** * Joins a list of Strings to a single one. * * @param delimiter the delimiter between the joined parts * @param parts the parts to join * @return the joined String or null if parts was null */ public static String join(String delimiter, String... parts) {
if (parts == null) { return null; } if (delimiter == null) { delimiter = ""; } StringBuilder stringBuilder = new StringBuilder(); for (int i=0; i < parts.length; i++) { if (i > 0) { stringBuilder.append(delimiter); } stringBuilder.append(parts[i]); } return stringBuilder.toString(); } /** * Returns either the passed in String, or if the String is <code>null</code>, an empty String (""). * * <pre> * StringUtils.defaultString(null) = "" * StringUtils.defaultString("") = "" * StringUtils.defaultString("bat") = "bat" * </pre> * * @param text the String to check, may be null * @return the passed in String, or the empty String if it was <code>null</code> */ public static String defaultString(String text) { return text == null ? "" : text; } /** * Fetches the stack trace of an exception as a String. * * @param throwable to get the stack trace from * @return the stack trace as String */ public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw, true)); return sw.toString(); } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\StringUtil.java
1
请完成以下Java代码
public class TimerEventListenerExport extends AbstractPlanItemDefinitionExport<TimerEventListener> { @Override protected Class<TimerEventListener> getExportablePlanItemDefinitionClass() { return TimerEventListener.class; } @Override protected String getPlanItemDefinitionXmlElementValue(TimerEventListener timerEventListener) { return ELEMENT_TIMER_EVENT_LISTENER; } @Override protected void writePlanItemDefinitionSpecificAttributes(TimerEventListener timerEventListener, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(timerEventListener, xtw); if (StringUtils.isNotEmpty(timerEventListener.getAvailableConditionExpression())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION, timerEventListener.getAvailableConditionExpression()); } } @Override protected void writePlanItemDefinitionBody(CmmnModel model, TimerEventListener timerEventListener, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { if (StringUtils.isNotEmpty(timerEventListener.getTimerExpression())) { xtw.writeStartElement(ELEMENT_TIMER_EXPRESSION);
xtw.writeCData(timerEventListener.getTimerExpression()); xtw.writeEndElement(); } if (StringUtils.isNotEmpty(timerEventListener.getTimerStartTriggerSourceRef())) { xtw.writeStartElement(ELEMENT_PLAN_ITEM_START_TRIGGER); xtw.writeAttribute(ATTRIBUTE_PLAN_ITEM_START_TRIGGER_SRC_REF, timerEventListener.getTimerStartTriggerSourceRef()); xtw.writeStartElement(ELEMENT_STANDARD_EVENT); xtw.writeCData(timerEventListener.getTimerStartTriggerStandardEvent()); xtw.writeEndElement(); xtw.writeEndElement(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\TimerEventListenerExport.java
1
请完成以下Java代码
public CmmnActivityBehavior createEmailActivityBehavior(PlanItem planItem, ServiceTask task) { return classDelegateFactory.create(CmmnMailActivityDelegate.class.getName(), task.getFieldExtensions()); } @Override public SendEventActivityBehavior createSendEventActivityBehavior(PlanItem planItem, SendEventServiceTask sendEventServiceTask) { return new SendEventActivityBehavior(sendEventServiceTask); } @Override public ExternalWorkerTaskActivityBehavior createExternalWorkerActivityBehaviour(PlanItem planItem, ExternalWorkerServiceTask externalWorkerServiceTask) { return new ExternalWorkerTaskActivityBehavior(externalWorkerServiceTask); } @Override public ScriptTaskActivityBehavior createScriptTaskActivityBehavior(PlanItem planItem, ScriptServiceTask task) { return new ScriptTaskActivityBehavior(task); } @Override public CasePageTaskActivityBehaviour createCasePageTaskActivityBehaviour(PlanItem planItem, CasePageTask task) { return new CasePageTaskActivityBehaviour(task); } public void setClassDelegateFactory(CmmnClassDelegateFactory classDelegateFactory) { this.classDelegateFactory = classDelegateFactory; }
public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } protected Expression createExpression(String refExpressionString) { Expression expression = null; if (StringUtils.isNotEmpty(refExpressionString)) { expression = expressionManager.createExpression(refExpressionString); } return expression; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\DefaultCmmnActivityBehaviorFactory.java
1
请完成以下Java代码
public final PurchaseView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } public final PurchaseView getById(final ViewId viewId) { final PurchaseView view = getByIdOrNull(viewId); if (view == null) { throw new EntityNotFoundException("View " + viewId + " was not found"); } return view; } @Override public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { final PurchaseView view = views.getIfPresent(viewId); if (view == null || !view.isAllowClosingPerUserRequest()) { return; } if (closeAction.isDone()) { onViewClosedByUser(view); } views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } @Override public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final IView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PurchaseView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = newViewId(); final List<PurchaseDemand> demands = getDemands(request); final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands); final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList);
final PurchaseView view = PurchaseView.builder() .viewId(viewId) .rowsSupplier(rowsSupplier) .additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors()) .build(); return view; } protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors() { return ImmutableList.of(); } private final PurchaseRowsSupplier createRowsSupplier( final ViewId viewId, final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList) { final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder() .purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList) .viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff .purchaseRowFactory(purchaseRowFactory) .availabilityCheckService(availabilityCheckService) .build() .createPurchaseRowsSupplier(); return rowsSupplier; } protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass); Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass); return RelatedProcessDescriptor.builder() .processId(processId) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java
1
请完成以下Java代码
public abstract class ConversationNodeImpl extends BaseElementImpl implements ConversationNode { protected static Attribute<String> nameAttribute; protected static ElementReferenceCollection<Participant, ParticipantRef> participantRefCollection; protected static ElementReferenceCollection<MessageFlow, MessageFlowRef> messageFlowRefCollection; protected static ChildElementCollection<CorrelationKey> correlationKeyCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ConversationNode.class, BPMN_ELEMENT_CONVERSATION_NODE) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .abstractType(); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); participantRefCollection = sequenceBuilder.elementCollection(ParticipantRef.class) .qNameElementReferenceCollection(Participant.class) .build(); messageFlowRefCollection = sequenceBuilder.elementCollection(MessageFlowRef.class) .qNameElementReferenceCollection(MessageFlow.class) .build(); correlationKeyCollection = sequenceBuilder.elementCollection(CorrelationKey.class) .build(); typeBuilder.build(); } public ConversationNodeImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this);
} public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<Participant> getParticipants() { return participantRefCollection.getReferenceTargetElements(this); } public Collection<MessageFlow> getMessageFlows() { return messageFlowRefCollection.getReferenceTargetElements(this); } public Collection<CorrelationKey> getCorrelationKeys() { return correlationKeyCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConversationNodeImpl.java
1
请完成以下Java代码
public String getTelephone() { return telephone; } /** * Set the telephone. * * @param telephone the telephone */ public void setTelephone(String telephone) { this.telephone = telephone; } /** * Get the user type. * * @return the user type */ public Integer getUserType() { return userType; } /** * Set the user type. * * @param userType the user type */ public void setUserType(Integer userType) { this.userType = userType; } /** * Get the creates the by. * * @return the creates the by */ public String getCreateBy() { return createBy; } /** * Set the creates the by. * * @param createBy the creates the by */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * Get the creates the time. * * @return the creates the time */ public Date getCreateTime() { return createTime; } /** * Set the creates the time. * * @param createTime the creates the time */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * Get the update by. * * @return the update by */ public String getUpdateBy() { return updateBy; } /** * Set the update by. * * @param updateBy the update by */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } /** * Get the update time. * * @return the update time */ public Date getUpdateTime() { return updateTime; } /** * Set the update time. *
* @param updateTime the update time */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * Get the disabled. * * @return the disabled */ public Integer getDisabled() { return disabled; } /** * Set the disabled. * * @param disabled the disabled */ public void setDisabled(Integer disabled) { this.disabled = disabled; } /** * Get the theme. * * @return the theme */ public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. * * @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
private void doDataSourceHealthCheck(Health.Builder builder) { Assert.state(this.jdbcTemplate != null, "'jdbcTemplate' must not be null"); builder.up().withDetail("database", getProduct(this.jdbcTemplate)); String validationQuery = this.query; if (StringUtils.hasText(validationQuery)) { builder.withDetail("validationQuery", validationQuery); // Avoid calling getObject as it breaks MySQL on Java 7 and later List<Object> results = this.jdbcTemplate.query(validationQuery, new SingleColumnRowMapper()); Object result = DataAccessUtils.requiredSingleResult(results); builder.withDetail("result", result); } else { builder.withDetail("validationQuery", "isValid()"); boolean valid = isConnectionValid(this.jdbcTemplate); builder.status((valid) ? Status.UP : Status.DOWN); } } private String getProduct(JdbcTemplate jdbcTemplate) { return jdbcTemplate.execute((ConnectionCallback<String>) this::getProduct); } private String getProduct(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName(); } private Boolean isConnectionValid(JdbcTemplate jdbcTemplate) { return jdbcTemplate.execute((ConnectionCallback<Boolean>) this::isConnectionValid); } private Boolean isConnectionValid(Connection connection) throws SQLException { return connection.isValid(0); } /** * Set the {@link DataSource} to use. * @param dataSource the data source */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); } /** * Set a specific validation query to use to validate a connection. If none is set, a * validation based on {@link Connection#isValid(int)} is used. * @param query the validation query to use */ public void setQuery(String query) { this.query = query; } /** * Return the validation query or {@code null}. * @return the query
*/ public @Nullable String getQuery() { return this.query; } /** * {@link RowMapper} that expects and returns results from a single column. */ private static final class SingleColumnRowMapper implements RowMapper<Object> { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columns = metaData.getColumnCount(); if (columns != 1) { throw new IncorrectResultSetColumnCountException(1, columns); } Object result = JdbcUtils.getResultSetValue(rs, 1); Assert.state(result != null, "'result' must not be null"); return result; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java
1
请完成以下Java代码
public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final AbstractProcessApplication processApplication = operationContext.getAttachment(PROCESS_APPLICATION); ClassLoader configurationClassloader = null; if(processApplication != null) { configurationClassloader = processApplication.getProcessApplicationClassloader(); } else { configurationClassloader = ProcessEngineConfiguration.class.getClassLoader(); } String configurationClassName = jobAcquisitionXml.getJobExecutorClassName(); if(configurationClassName == null || configurationClassName.isEmpty()) { configurationClassName = RuntimeContainerJobExecutor.class.getName(); } // create & instantiate the job executor class Class<? extends JobExecutor> jobExecutorClass = loadJobExecutorClass(configurationClassloader, configurationClassName); JobExecutor jobExecutor = instantiateJobExecutor(jobExecutorClass); // apply properties Map<String, String> properties = jobAcquisitionXml.getProperties(); PropertyHelper.applyProperties(jobExecutor, properties); // construct service for job executor JmxManagedJobExecutor jmxManagedJobExecutor = new JmxManagedJobExecutor(jobExecutor);
// deploy the job executor service into the container serviceContainer.startService(ServiceTypes.JOB_EXECUTOR, jobAcquisitionXml.getName(), jmxManagedJobExecutor); } protected JobExecutor instantiateJobExecutor(Class<? extends JobExecutor> configurationClass) { try { return configurationClass.newInstance(); } catch (Exception e) { throw LOG.couldNotInstantiateJobExecutorClass(e); } } @SuppressWarnings("unchecked") protected Class<? extends JobExecutor> loadJobExecutorClass(ClassLoader processApplicationClassloader, String jobExecutorClassname) { try { return (Class<? extends JobExecutor>) processApplicationClassloader.loadClass(jobExecutorClassname); } catch (ClassNotFoundException e) { throw LOG.couldNotLoadJobExecutorClass(e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartJobAcquisitionStep.java
1
请完成以下Java代码
public String getISBN() { return ISBN; } public void setISBN(String ISBN) { this.ISBN = ISBN; } public Date getPublished() { return published; } public void setPublished(Date published) { this.published = published; } public BigDecimal getPages() { return pages; } public void setPages(BigDecimal pages) { this.pages = pages; }
public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\deserialization\jsondeserialize\Book.java
1
请完成以下Java代码
public class TransitionInstanceJobHandler implements MigratingDependentInstanceParseHandler<MigratingTransitionInstance, List<JobEntity>> { @Override public void handle(MigratingInstanceParseContext parseContext, MigratingTransitionInstance transitionInstance, List<JobEntity> elements) { for (JobEntity job : elements) { if (!isAsyncContinuation(job)) { continue; } ScopeImpl targetScope = transitionInstance.getTargetScope(); if (targetScope != null) { JobDefinitionEntity targetJobDefinitionEntity = parseContext.getTargetJobDefinition(transitionInstance.getTargetScope().getId(), job.getJobHandlerType()); MigratingAsyncJobInstance migratingJobInstance =
new MigratingAsyncJobInstance(job, targetJobDefinitionEntity, transitionInstance.getTargetScope()); transitionInstance.setDependentJobInstance(migratingJobInstance); parseContext.submit(migratingJobInstance); } parseContext.consume(job); } } protected static boolean isAsyncContinuation(JobEntity job) { return job != null && AsyncContinuationJobHandler.TYPE.equals(job.getJobHandlerType()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\TransitionInstanceJobHandler.java
1
请完成以下Java代码
public String initUpdateOwnerForm() { return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } @PostMapping("/owners/{ownerId}/edit") public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { redirectAttributes.addFlashAttribute("error", "There was an error in updating the owner."); return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } if (!Objects.equals(owner.getId(), ownerId)) { result.rejectValue("id", "mismatch", "The owner ID in the form does not match the URL."); redirectAttributes.addFlashAttribute("error", "Owner ID mismatch. Please try again."); return "redirect:/owners/{ownerId}/edit"; } owner.setId(ownerId); this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Owner Values Updated"); return "redirect:/owners/{ownerId}"; } /** * Custom handler for displaying an owner. * @param ownerId the ID of the owner to display * @return a ModelMap with the model attributes for the view */ @GetMapping("/owners/{ownerId}") public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { ModelAndView mav = new ModelAndView("owners/ownerDetails"); Optional<Owner> optionalOwner = this.owners.findById(ownerId); Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException( "Owner not found with id: " + ownerId + ". Please ensure the ID is correct ")); mav.addObject(owner); return mav; } }
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\OwnerController.java
1
请完成以下Java代码
public Object getRawEvent() { return message; } @Override public Object getBody() { byte[] body = message.getBody(); MessageProperties messageProperties = message.getMessageProperties(); String contentType = messageProperties != null ? messageProperties.getContentType() : null; String bodyContent = null; if (stringContentTypes.contains(contentType)) { bodyContent = new String(body, StandardCharsets.UTF_8); } else { bodyContent = Base64.getEncoder().encodeToString(body); } return bodyContent; } @Override public Map<String, Object> getHeaders() { if (headers == null) { headers = retrieveHeaders(); } return headers; } protected Map<String, Object> retrieveHeaders() { Map<String, Object> headers = new HashMap<>(); Map<String, Object> headerMap = message.getMessageProperties().getHeaders(); for (String headerName : headerMap.keySet()) { headers.put(headerName, headerMap.get(headerName)); }
return headers; } public Collection<String> getStringContentTypes() { return stringContentTypes; } public void setStringContentTypes(Collection<String> stringContentTypes) { this.stringContentTypes = stringContentTypes; } @Override public String toString() { return "RabbitInboundEvent{" + "message=" + message + ", stringContentTypes=" + stringContentTypes + ", headers=" + headers + '}'; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitInboundEvent.java
1
请完成以下Java代码
public static JsonPOSPayment of(@NonNull final POSPayment payment) { final POSPaymentProcessingStatus paymentProcessingStatus = payment.getPaymentProcessingStatus(); return builder() .uuid(payment.getExternalId()) .paymentMethod(payment.getPaymentMethod()) .amount(payment.getAmount().toBigDecimal()) .cashTenderedAmount(payment.getCashTenderedAmount().toBigDecimal()) .cashGiveBackAmount(payment.getCashGiveBackAmount().toBigDecimal()) .cardReaderName(extractCardReaderName(payment)) .status(JsonPOSPaymentStatus.of(paymentProcessingStatus)) .statusDetails(payment.getCardProcessingDetails() != null ? payment.getCardProcessingDetails().getSummary() : null) .allowCheckout(paymentProcessingStatus.isAllowCheckout()) .allowDelete(payment.isAllowDelete()) .allowRefund(payment.isAllowRefund()) .hashCode(payment.hashCode()) .build(); } @Nullable private static String extractCardReaderName(@NonNull final POSPayment payment) {
final POSPaymentCardProcessingDetails cardProcessingDetails = payment.getCardProcessingDetails(); if (cardProcessingDetails == null) { return null; } final POSCardReader cardReader = cardProcessingDetails.getCardReader(); if (cardReader == null) { return null; } return cardReader.getName(); } RemotePOSPayment toRemotePOSPayment() { return RemotePOSPayment.builder() .uuid(uuid) .paymentMethod(paymentMethod) .amount(amount) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\json\JsonPOSPayment.java
1
请完成以下Java代码
public static Predicate<BPartnerContact> createContactFilterFor(@NonNull final IdentifierString contactIdentifier) { return c -> matches(contactIdentifier, c); } private boolean matches( @NonNull final IdentifierString contactIdentifier, @NonNull final BPartnerContact contact) { switch (contactIdentifier.getType()) { case EXTERNAL_ID: return contactIdentifier.asExternalId().equals(contact.getExternalId()); case GLN: throw new AdempiereException("IdentifierStrings with type=" + Type.GLN + " are not supported for contacts") .appendParametersToMessage() .setParameter("contactIdentifier", contactIdentifier); case METASFRESH_ID: return contactIdentifier.asMetasfreshId().equals(MetasfreshId.of(contact.getId())); case VALUE: return contactIdentifier.asValue().equals(contact.getValue()); default: throw new AdempiereException("Unexpected type; contactIdentifier=" + contactIdentifier); } }
@Nullable public static InvoiceRule getInvoiceRule(@Nullable final JsonInvoiceRule jsonInvoiceRule) { if (jsonInvoiceRule == null) { return null; } switch (jsonInvoiceRule) { case AfterDelivery: return InvoiceRule.AfterDelivery; case CustomerScheduleAfterDelivery: return InvoiceRule.CustomerScheduleAfterDelivery; case Immediate: return InvoiceRule.Immediate; case OrderCompletelyDelivered: return InvoiceRule.OrderCompletelyDelivered; case AfterPick: return InvoiceRule.AfterPick; default: throw new AdempiereException("Unsupported JsonInvliceRule " + jsonInvoiceRule); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\BPartnerCompositeRestUtils.java
1
请完成以下Java代码
public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } /** * <p> * Sets the {@link LogoutHandler}s used when integrating with * {@link HttpServletRequest} with Servlet 3 APIs. Specifically it will be used when * {@link HttpServletRequest#logout()} is invoked in order to log the user out. So * long as the {@link LogoutHandler}s do not commit the {@link HttpServletResponse} * (expected), then the user is in charge of handling the response. * </p> * <p> * If the value is null (default), the default container behavior will be retained * when invoking {@link HttpServletRequest#logout()}. * </p> * @param logoutHandlers the {@code List&lt;LogoutHandler&gt;}s when invoking * {@link HttpServletRequest#logout()}. */ public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) { this.logoutHandlers = logoutHandlers; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { chain.doFilter(this.requestFactory.create((HttpServletRequest) req, (HttpServletResponse) res), res); } @Override public void afterPropertiesSet() throws ServletException { super.afterPropertiesSet(); updateFactory(); } private void updateFactory() { String rolePrefix = this.rolePrefix; this.requestFactory = createServlet3Factory(rolePrefix); }
/** * Sets the {@link AuthenticationTrustResolver} to be used. The default is * {@link AuthenticationTrustResolverImpl}. * @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be * null. */ public void setTrustResolver(AuthenticationTrustResolver trustResolver) { Assert.notNull(trustResolver, "trustResolver cannot be null"); this.trustResolver = trustResolver; updateFactory(); } private HttpServletRequestFactory createServlet3Factory(String rolePrefix) { HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix, this.securityContextRepository); factory.setTrustResolver(this.trustResolver); factory.setAuthenticationEntryPoint(this.authenticationEntryPoint); factory.setAuthenticationManager(this.authenticationManager); factory.setLogoutHandlers(this.logoutHandlers); factory.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); return factory; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilter.java
1
请完成以下Java代码
public class X_C_BankStatement_Import_File extends org.compiere.model.PO implements I_C_BankStatement_Import_File, org.compiere.model.I_Persistent { private static final long serialVersionUID = -988637955L; /** Standard Constructor */ public X_C_BankStatement_Import_File (final Properties ctx, final int C_BankStatement_Import_File_ID, @Nullable final String trxName) { super (ctx, C_BankStatement_Import_File_ID, trxName); } /** Load Constructor */ public X_C_BankStatement_Import_File (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BankStatement_Import_File_ID (final int C_BankStatement_Import_File_ID) { if (C_BankStatement_Import_File_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_ID, C_BankStatement_Import_File_ID); } @Override public int getC_BankStatement_Import_File_ID() { return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_ID); } @Override public void setFileName (final String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override
public void setImported (final @Nullable java.sql.Timestamp Imported) { set_Value (COLUMNNAME_Imported, Imported); } @Override public java.sql.Timestamp getImported() { return get_ValueAsTimestamp(COLUMNNAME_Imported); } @Override public void setIsMatchAmounts (final boolean IsMatchAmounts) { set_Value (COLUMNNAME_IsMatchAmounts, IsMatchAmounts); } @Override public boolean isMatchAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsMatchAmounts); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File.java
1
请完成以下Java代码
public class TransactionIdentifier1 { @XmlElement(name = "TxDtTm", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar txDtTm; @XmlElement(name = "TxRef", required = true) protected String txRef; /** * Gets the value of the txDtTm property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getTxDtTm() { return txDtTm; } /** * Sets the value of the txDtTm property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setTxDtTm(XMLGregorianCalendar value) { this.txDtTm = value; }
/** * Gets the value of the txRef property. * * @return * possible object is * {@link String } * */ public String getTxRef() { return txRef; } /** * Sets the value of the txRef property. * * @param value * allowed object is * {@link String } * */ public void setTxRef(String value) { this.txRef = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionIdentifier1.java
1
请完成以下Java代码
public void JsonLib() { for (int i = 0; i < count; i++) { JsonLibUtil.bean2Json(p); } } @Benchmark public void Gson() { for (int i = 0; i < count; i++) { GsonUtil.bean2Json(p); } } @Benchmark public void FastJson() { for (int i = 0; i < count; i++) { FastJsonUtil.bean2Json(p); } } @Benchmark public void Jackson() { for (int i = 0; i < count; i++) { JacksonUtil.bean2Json(p); } } @Setup public void prepare() { List<Person> friends=new ArrayList<Person>(); friends.add(createAPerson("小明",null)); friends.add(createAPerson("Tony",null));
friends.add(createAPerson("陈小二",null)); p=createAPerson("邵同学",friends); } @TearDown public void shutdown() { } private Person createAPerson(String name,List<Person> friends) { Person newPerson=new Person(); newPerson.setName(name); newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last")); newPerson.setAge(24); List<String> hobbies=new ArrayList<String>(); hobbies.add("篮球"); hobbies.add("游泳"); hobbies.add("coding"); newPerson.setHobbies(hobbies); Map<String,String> clothes=new HashMap<String, String>(); clothes.put("coat", "Nike"); clothes.put("trousers", "adidas"); clothes.put("shoes", "安踏"); newPerson.setClothes(clothes); newPerson.setFriends(friends); return newPerson; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\JsonSerializeBenchmark.java
1
请完成以下Java代码
public void addPurgeInformation(String key, Long value) { deletedEntities.put(key, value); } @Override public Map<String, Long> getPurgeReport() { return deletedEntities; } @Override public String getPurgeReportAsString() { StringBuilder builder = new StringBuilder(); for (String key : deletedEntities.keySet()) { builder.append("Table: ").append(key) .append(" contains: ").append(getReportValue(key)) .append(" rows\n"); } return builder.toString(); } @Override public Long getReportValue(String key) { return deletedEntities.get(key);
} @Override public boolean containsReport(String key) { return deletedEntities.containsKey(key); } public boolean isEmpty() { return deletedEntities.isEmpty(); } public boolean isDbContainsLicenseKey() { return dbContainsLicenseKey; } public void setDbContainsLicenseKey(boolean dbContainsLicenseKey) { this.dbContainsLicenseKey = dbContainsLicenseKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\DatabasePurgeReport.java
1
请完成以下Java代码
protected void add(final HUReceiptLinePartCandidate receiptLinePartToAdd) { // // Try adding Part to existing Receipt Line Candidate for (final HUReceiptLineCandidate receiptLineCandidate : receiptLineCandidates) { if (receiptLineCandidate.add(receiptLinePartToAdd)) { stale = true; // we need to recompute the amounts return; } } // // Create a new Receipt Line Candidate and add the Part to it final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); final HUReceiptLineCandidate receiptLineCandidate = new HUReceiptLineCandidate(receiptSchedule); if (!receiptLineCandidate.add(receiptLinePartToAdd)) { // shall not happen throw new AdempiereException("New candidate " + receiptLineCandidate + " refused to add " + receiptLinePartToAdd); } receiptLineCandidates.add(receiptLineCandidate); // 06135: don't forget to add the fruits of our labour :-P stale = true; // we need to recompute the amounts } public List<HUReceiptLineCandidate> getHUReceiptLineCandidates() { return receiptLineCandidatesRO; }
private final void updateIfStale() { if (!stale) { return; } // // Compute qty&quality (qtys, discount percent, quality notices) // Collect receipt schedule allocations final ReceiptQty qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId); final List<I_M_ReceiptSchedule_Alloc> receiptScheduleAllocs = new ArrayList<I_M_ReceiptSchedule_Alloc>(); for (final HUReceiptLineCandidate receiptLineCandidate : receiptLineCandidates) { final ReceiptQty lineQtyAndQuality = receiptLineCandidate.getQtyAndQuality(); qtyAndQuality.add(lineQtyAndQuality); receiptScheduleAllocs.addAll(receiptLineCandidate.getReceiptScheduleAllocs()); } // // Update cumulated values _qtyAndQuality = qtyAndQuality; stale = false; // not staled anymore } public final ReceiptQty getQtyAndQuality() { updateIfStale(); return _qtyAndQuality; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLineCandidatesBuilder.java
1
请完成以下Java代码
public void setHeader_Line1 (final java.lang.String Header_Line1) { set_Value (COLUMNNAME_Header_Line1, Header_Line1); } @Override public java.lang.String getHeader_Line1() { return get_ValueAsString(COLUMNNAME_Header_Line1); } @Override public void setHeader_Line2 (final java.lang.String Header_Line2) { set_Value (COLUMNNAME_Header_Line2, Header_Line2); } @Override public java.lang.String getHeader_Line2() { return get_ValueAsString(COLUMNNAME_Header_Line2); } @Override public void setIsDefault (final boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, IsDefault); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault);
} @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSQL_Select (final java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Zebra_Config.java
1
请完成以下Java代码
public static void customizePrefernces() { final IMsgBL msgBL = Services.get(IMsgBL.class); final Border insetBorder = BorderFactory.createEmptyBorder(2, 2, 2, 0); final FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT); final CPanel dlmPanel = new CPanel(); dlmPanel.setLayout(flowLayout); dlmPanel.setBorder(insetBorder); final CLabel dlmLevelLabel = new CLabel(); dlmLevelLabel.setText(msgBL.getMsg(Env.getCtx(), DLMPermanentIniCustomizer.INI_P_DLM_DLM_LEVEL)); final Map<Integer, ValueNamePair> values = getValues(); final CComboBox<ValueNamePair> dlmLevelField = new CComboBox<>(ImmutableList.of(values.get(IMigratorService.DLM_Level_TEST), values.get(IMigratorService.DLM_Level_ARCHIVE))); dlmPanel.add(dlmLevelLabel); dlmPanel.add(dlmLevelField); Preference.addSettingsPanel(dlmPanel, preference -> { // do this on load final int dlmLevel = DLMPermanentIniCustomizer.INSTANCE.getDlmLevel(); dlmLevelField.setSelectedItem(values.get(dlmLevel)); }, preference -> {
// do this on store final ValueNamePair selectedItem = dlmLevelField.getSelectedItem(); if(selectedItem != null) { Ini.setProperty(DLMPermanentIniCustomizer.INI_P_DLM_DLM_LEVEL, selectedItem.getValue()); } }); } public static Map<Integer, ValueNamePair> getValues() { final IMsgBL msgBL = Services.get(IMsgBL.class); // note that this this is no typo; the entry for "live" shall have the "test" value because the DLM engine might temporarily // change the level of individual records from live (i.e. 1) to test (i.e. 2), // but those records with level "test" shall not be hidden from the user. // Also see the constants' javadocs for more details. final ValueNamePair live = ValueNamePair.of(Integer.toString(IMigratorService.DLM_Level_TEST), msgBL.translate(Env.getCtx(), IMigratorService.MSG_DLM_Level_LIVE)); final ValueNamePair archive = ValueNamePair.of(Integer.toString(IMigratorService.DLM_Level_ARCHIVE), msgBL.translate(Env.getCtx(), IMigratorService.MSG_DLM_Level_ARCHIVE)); return ImmutableMap.of(IMigratorService.DLM_Level_TEST, live, IMigratorService.DLM_Level_ARCHIVE, archive); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\swingui\src\main\java\de\metas\dlm\swingui\PreferenceCustomizer.java
1
请完成以下Java代码
public class DataStream { public static void textDataProcessingByteStream(String fileName, String content) throws IOException { PrintStream out = new PrintStream(fileName); out.print(content); out.flush(); out.close(); } public static void textDataProcessingCharStream(String fileName, String content) throws IOException { PrintWriter out = new PrintWriter(fileName); out.print(content); out.flush(); out.close(); } public static void nonTextDataProcessing(String fileName, String streamOutputFile, String writerOutputFile) throws IOException { FileInputStream inputStream = new FileInputStream(fileName); PrintStream printStream = new PrintStream(streamOutputFile); int b;
while ((b = inputStream.read()) != -1) { printStream.write(b); } printStream.close(); FileReader reader = new FileReader(fileName); PrintWriter writer = new PrintWriter(writerOutputFile); int c; while ((c = reader.read()) != -1) { writer.write(c); } writer.close(); inputStream.close(); } }
repos\tutorials-master\core-java-modules\core-java-io-4\src\main\java\com\baeldung\iostreams\DataStream.java
1
请完成以下Java代码
public class Orders { @Field("cust_id") private String custId; private long amount; private String status; public Orders(String custId, long amount, String status) { this.custId = custId; this.amount = amount; this.status = status; } public String getCustId() { return custId; } public void setCustId(String custId) { this.custId = custId; } public long getAmount() {
return amount; } public void setAmount(long amount) { this.amount = amount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\2.x_data\2-5 MongoDB 分布式计算 Aggregate VS Mapreduce\spring-boot-mongodb-mapreduce\src\main\java\com\neo\model\Orders.java
1
请完成以下Java代码
public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Remote Client. @param Remote_Client_ID Remote Client to be used to replicate / synchronize data with. */ public void setRemote_Client_ID (int Remote_Client_ID) { if (Remote_Client_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID)); } /** Get Remote Client. @return Remote Client to be used to replicate / synchronize data with. */ public int getRemote_Client_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Organization. @param Remote_Org_ID Remote Organization to be used to replicate / synchronize data with. */
public void setRemote_Org_ID (int Remote_Org_ID) { if (Remote_Org_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID)); } /** Get Remote Organization. @return Remote Organization to be used to replicate / synchronize data with. */ public int getRemote_Org_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
1
请完成以下Java代码
public class App { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(App.class); public static void main(String[] args) { Blade.of() .get("/", ctx -> ctx.render("index.html")) .get("/basic-route-example", ctx -> ctx.text("GET called")) .post("/basic-route-example", ctx -> ctx.text("POST called")) .put("/basic-route-example", ctx -> ctx.text("PUT called")) .delete("/basic-route-example", ctx -> ctx.text("DELETE called")) .addStatics("/custom-static") // .showFileList(true) .enableCors(true)
.before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri())) .on(EventType.SERVER_STARTED, e -> { String version = WebContext.blade() .env("app.version") .orElse("N/D"); log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version); }) .on(EventType.SESSION_CREATED, e -> { Session session = (Session) e.attribute("session"); session.attribute("mySessionValue", "Baeldung"); }) .use(new BaeldungMiddleware()) .start(App.class, args); } }
repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\App.java
1
请在Spring Boot框架中完成以下Java代码
public Date getLockExpirationTime() { return lockExpirationTime; } @Override public void setLockExpirationTime(Date claimedUntil) { this.lockExpirationTime = claimedUntil; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) { if (jobByteArrayRef == null) { return null; } return jobByteArrayRef.asString(getEngineType()); } protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoryJobEntity[").append("id=").append(id) .append(", jobHandlerType=").append(jobHandlerType); if (scopeType != null) { sb.append(", scopeType=").append(scopeType); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java
2
请完成以下Java代码
protected void logUserOperation(CommandContext commandContext) { PropertyChange suspensionStateChanged = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName()); PropertyChange includeProcessInstances = new PropertyChange(INCLUDE_PROCESS_INSTANCES_PROPERTY, null, isIncludeSubResources()); commandContext.getOperationLogManager() .logProcessDefinitionOperation( getLogEntryOperation(), processDefinitionId, processDefinitionKey, Arrays.asList(suspensionStateChanged, includeProcessInstances) ); } // ABSTRACT METHODS //////////////////////////////////////////////////////////////////// /** * Subclasses should return the type of the {@link JobHandler} here. it will be used when * the user provides an execution date on which the actual state change will happen. */ @Override protected abstract String getDelayedExecutionJobHandlerType(); /** * Subclasses should return the type of the {@link AbstractSetJobDefinitionStateCmd} here. * It will be used to suspend or activate the {@link JobDefinition}s. * @param jobDefinitionSuspensionStateBuilder */ protected abstract AbstractSetJobDefinitionStateCmd getSetJobDefinitionStateCmd(UpdateJobDefinitionSuspensionStateBuilderImpl jobDefinitionSuspensionStateBuilder);
@Override protected AbstractSetProcessInstanceStateCmd getNextCommand() { UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder = createProcessInstanceCommandBuilder(); return getNextCommand(processInstanceCommandBuilder); } @Override protected String getDeploymentId(CommandContext commandContext) { if (processDefinitionId != null) { return getDeploymentIdByProcessDefinition(commandContext, processDefinitionId); } else if (processDefinitionKey != null) { return getDeploymentIdByProcessDefinitionKey(commandContext, processDefinitionKey, isTenantIdSet, tenantId); } return null; } protected abstract AbstractSetProcessInstanceStateCmd getNextCommand(UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetProcessDefinitionStateCmd.java
1
请完成以下Java代码
public boolean isOldNull () { Object oo = get_Value(COLUMNNAME_IsOldNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set New Value. @param NewValue New field value */ @Override public void setNewValue (java.lang.String NewValue) { set_Value (COLUMNNAME_NewValue, NewValue); } /** Get New Value. @return New field value */ @Override public java.lang.String getNewValue () { return (java.lang.String)get_Value(COLUMNNAME_NewValue); } /** Set Old Value. @param OldValue
The old file data */ @Override public void setOldValue (java.lang.String OldValue) { set_Value (COLUMNNAME_OldValue, OldValue); } /** Get Old Value. @return The old file data */ @Override public java.lang.String getOldValue () { return (java.lang.String)get_Value(COLUMNNAME_OldValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationData.java
1
请完成以下Java代码
private JSONLookupValue toJSONLookupValue(final LookupValue lookupValue) { return JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } @GetMapping("/{asiDocId}/field/{attributeName}/dropdown") public JSONLookupValuesList getAttributeDropdown( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValues(attributeName)) .transform(this::toJSONLookupValuesList); } @PostMapping(value = "/{asiDocId}/complete") public JSONLookupValue complete( @PathVariable("asiDocId") final String asiDocIdStr, @RequestBody final JSONCompleteASIRequest request) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return Execution.callInNewExecution("complete", () -> completeInTrx(asiDocId, request))
.transform(this::toJSONLookupValue); } private LookupValue completeInTrx(final DocumentId asiDocId, final JSONCompleteASIRequest request) { return asiRepo.forASIDocumentWritable( asiDocId, NullDocumentChangesCollector.instance, documentsCollection, asiDoc -> { final List<JSONDocumentChangedEvent> events = request.getEvents(); if (events != null && !events.isEmpty()) { asiDoc.processValueChanges(events, REASON_ProcessASIDocumentChanges); } return asiDoc.complete(); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRestController.java
1
请完成以下Java代码
protected void unlockJobIfNeeded() { try { if (job.isExclusive()) { processEngineConfiguration.getCommandExecutor().execute(new UnlockExclusiveJobCmd(job)); } } catch (ActivitiOptimisticLockingException optimisticLockingException) { if (log.isDebugEnabled()) { log.debug( "Optimistic locking exception while unlocking the job. If you have multiple async executors running against the same database, " + "this exception means that this thread tried to acquire an exclusive job, which already was changed by another async executor thread." + "This is expected behavior in a clustered environment. " + "You can ignore this message if you indeed have multiple job executor acquisition threads running against the same database. " + "Exception message: {}", optimisticLockingException.getMessage() ); } } catch (Throwable t) { log.error("Error while unlocking exclusive job " + job.getId(), t); } } /** * Returns true if lock succeeded, or no lock was needed. * Returns false if locking was unsuccessfull. */ protected boolean lockJobIfNeeded() { try { if (job.isExclusive()) { processEngineConfiguration.getCommandExecutor().execute(new LockExclusiveJobCmd(job)); } } catch (Throwable lockException) { if (log.isDebugEnabled()) { log.debug( "Could not lock exclusive job. Unlocking job so it can be acquired again. Catched exception: " + lockException.getMessage() ); } // Release the job again so it can be acquired later or by another node unacquireJob(); return false; }
return true; } protected void unacquireJob() { CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { commandContext.getJobManager().unacquire(job); } else { processEngineConfiguration .getCommandExecutor() .execute( new Command<Void>() { public Void execute(CommandContext commandContext) { commandContext.getJobManager().unacquire(job); return null; } } ); } } protected void handleFailedJob(final Throwable exception) { processEngineConfiguration .getCommandExecutor() .execute(new HandleFailedJobCmd(jobId, processEngineConfiguration, exception)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ExecuteAsyncRunnable.java
1
请完成以下Java代码
protected Unmarshaller createUnmarshaller(Class<?>... types) { try { return getContext(types).createUnmarshaller(); } catch (JAXBException e) { throw LOG.unableToCreateUnmarshaller(e); } } public static TransformerFactory defaultTransformerFactory() { return TransformerFactory.newInstance(); } public static DocumentBuilderFactory defaultDocumentBuilderFactory() { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); LOG.documentBuilderFactoryConfiguration("namespaceAware", "true"); documentBuilderFactory.setValidating(false); LOG.documentBuilderFactoryConfiguration("validating", "false"); documentBuilderFactory.setIgnoringComments(true); LOG.documentBuilderFactoryConfiguration("ignoringComments", "true"); documentBuilderFactory.setIgnoringElementContentWhitespace(false); LOG.documentBuilderFactoryConfiguration("ignoringElementContentWhitespace", "false"); return documentBuilderFactory; } public static Class<?> loadClass(String classname, DataFormat dataFormat) { // first try context classoader ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(cl != null) { try { return cl.loadClass(classname); } catch(Exception e) { // ignore } } // else try the classloader which loaded the dataformat cl = dataFormat.getClass().getClassLoader(); try { return cl.loadClass(classname); } catch (ClassNotFoundException e) { throw LOG.classNotFound(classname, e); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlDataFormat.java
1
请完成以下Java代码
public OrderCostId getOrderCostId() {return orderCostDetailId.getOrderCostId();} public OrderId getOrderId() {return orderAndLineId.getOrderId();} public OrderLineId getOrderLineId() {return orderAndLineId.getOrderLineId();} public InOutId getInOutId() {return inoutAndLineId.getInOutId();} public InOutLineId getInOutLineId() {return inoutAndLineId.getInOutLineId();} public void addCostAmountInvoiced(@NonNull final Money amtToAdd) { this.costAmountInvoiced = this.costAmountInvoiced.add(amtToAdd); this.isInvoiced = this.costAmount.isEqualByComparingTo(this.costAmountInvoiced); } public Money getCostAmountToInvoice() { return costAmount.subtract(costAmountInvoiced); }
public Money getCostAmountForQty(final Quantity qty, CurrencyPrecision precision) { if (qty.equalsIgnoreSource(this.qty)) { return costAmount; } else if (qty.isZero()) { return costAmount.toZero(); } else { final Money price = costAmount.divide(this.qty.toBigDecimal(), CurrencyPrecision.ofInt(12)); return price.multiply(qty.toBigDecimal()).round(precision); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCost.java
1
请完成以下Java代码
void run() throws Exception { String lowerCaseHeader = this.header.toLowerCase(Locale.ROOT); if (lowerCaseHeader.contains("upgrade: websocket") && lowerCaseHeader.contains("sec-websocket-version: 13")) { runWebSocket(); } if (lowerCaseHeader.contains("get /livereload.js")) { InputStream stream = getClass().getResourceAsStream("livereload.js"); Assert.state(stream != null, "Resource 'livereload.js' not found"); this.outputStream.writeHttp(stream, "text/javascript"); } } private void runWebSocket() throws Exception { this.webSocket = true; String accept = getWebsocketAcceptResponse(); this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); new Frame("{\"command\":\"hello\",\"protocols\":[\"http://livereload.com/protocols/official-7\"]," + "\"serverName\":\"spring-boot\"}") .write(this.outputStream); while (this.running) { readWebSocketFrame(); } } private void readWebSocketFrame() throws IOException { try { Frame frame = Frame.read(this.inputStream); if (frame.getType() == Frame.Type.PING) { writeWebSocketFrame(new Frame(Frame.Type.PONG)); } else if (frame.getType() == Frame.Type.CLOSE) { throw new ConnectionClosedException(); } else if (frame.getType() == Frame.Type.TEXT) { logger.debug(LogMessage.format("Received LiveReload text frame %s", frame)); } else { throw new IOException("Unexpected Frame Type " + frame.getType()); } } catch (SocketTimeoutException ex) {
writeWebSocketFrame(new Frame(Frame.Type.PING)); Frame frame = Frame.read(this.inputStream); if (frame.getType() != Frame.Type.PONG) { throw new IllegalStateException("No Pong"); } } } /** * Trigger livereload for the client using this connection. * @throws IOException in case of I/O errors */ void triggerReload() throws IOException { if (this.webSocket) { logger.debug("Triggering LiveReload"); writeWebSocketFrame(new Frame("{\"command\":\"reload\",\"path\":\"/\"}")); } } private void writeWebSocketFrame(Frame frame) throws IOException { frame.write(this.outputStream); } private String getWebsocketAcceptResponse() throws NoSuchAlgorithmException { Matcher matcher = WEBSOCKET_KEY_PATTERN.matcher(this.header); Assert.state(matcher.find(), "No Sec-WebSocket-Key"); String response = matcher.group(1).trim() + WEBSOCKET_GUID; MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(response.getBytes(), 0, response.length()); return Base64.getEncoder().encodeToString(messageDigest.digest()); } /** * Close the connection. * @throws IOException in case of I/O errors */ void close() throws IOException { this.running = false; this.socket.close(); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\Connection.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } public I_M_LotCtl getM_LotCtl() throws RuntimeException { return (I_M_LotCtl)MTable.get(getCtx(), I_M_LotCtl.Table_Name) .getPO(getM_LotCtl_ID(), get_TrxName()); } /** Set Lot Control. @param M_LotCtl_ID Product Lot Control */ public void setM_LotCtl_ID (int M_LotCtl_ID) { if (M_LotCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID)); } /** Get Lot Control. @return Product Lot Control */ 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代码
public org.compiere.model.I_C_CostClassification_Category getC_CostClassification_Category() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class); } @Override public void setC_CostClassification_Category(final org.compiere.model.I_C_CostClassification_Category C_CostClassification_Category) { set_ValueFromPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class, C_CostClassification_Category); } @Override public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID) { if (C_CostClassification_Category_ID < 1) set_Value (COLUMNNAME_C_CostClassification_Category_ID, null); else set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID); } @Override public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID); }
@Override public org.compiere.model.I_C_CostClassification getC_CostClassification() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class); } @Override public void setC_CostClassification(final org.compiere.model.I_C_CostClassification C_CostClassification) { set_ValueFromPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class, C_CostClassification); } @Override public void setC_CostClassification_ID (final int C_CostClassification_ID) { if (C_CostClassification_ID < 1) set_Value (COLUMNNAME_C_CostClassification_ID, null); else set_Value (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID); } @Override public int getC_CostClassification_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Fact_Acct_Transactions_View.java
1
请完成以下Java代码
private DefaultMutableTreeNode assertNoCycles(final I_PP_Product_BOMLine bomLine) { final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM(); if (!bom.isActive()) { return null; } // Check Child = Parent error final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID()); final ProductId parentProductId = ProductId.ofRepoId(bom.getM_Product_ID()); if (productId.equals(parentProductId)) { throw new BOMCycleException(bom, productId); } // Check BOM Loop Error if (!markProductAsSeen(parentProductId)) {
throw new BOMCycleException(bom, parentProductId); } return assertNoCycles(parentProductId); } private void clearSeenProducts() { seenProductIds.clear(); } private boolean markProductAsSeen(final ProductId productId) { return seenProductIds.add(productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMCycleDetection.java
1
请完成以下Java代码
private final void onButtonPressed() { try { // Show the dialog final VImageDialog vid = new VImageDialog(Env.getWindow(m_WindowNo), m_WindowNo, m_mImage); vid.setVisible(true); // Do nothing if user canceled (i.e. closed the window) if (vid.isCanceled()) { return; } final int AD_Image_ID = vid.getAD_Image_ID(); final Integer newValue = AD_Image_ID > 0 ? AD_Image_ID : null; // m_mImage = null; // force reload setValue(newValue); // set explicitly // try { fireVetoableChange(m_columnName, null, newValue); } catch (PropertyVetoException pve) {} } catch (Exception e) { Services.get(IClientUI.class).error(m_WindowNo, e); } } // actionPerformed // Field for Value Preference private GridField m_mField = null;
/** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (GridField mField) { m_mField = mField; } // setField @Override public GridField getField() { return m_mField; } // metas @Override public boolean isAutoCommit() { return true; } } // VImage
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VImage.java
1
请完成以下Java代码
public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getTimezone() { return timezone; }
public void setTimezone(String timezone) { this.timezone = timezone; } @JsonIgnore @Override public String getId() { return zip; } @JsonIgnore @Override public boolean isNew() { return !persisted; } }
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\domain\ZipCode.java
1
请完成以下Java代码
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 void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { Graphics copy = g.create(); if (copy != null) { try { copy.translate(x, y); paintLine(c, copy, w, h); } finally { copy.dispose(); } } } // paintBorder /** * Paint Line with Header * @param c * @param g * @param w * @param h */ private void paintLine (Component c, Graphics g, int w, int h) { int y = h-SPACE; // Line g.setColor(Color.darkGray); g.drawLine(GAP, y, w-GAP, y); g.setColor(Color.white); g.drawLine(GAP, y+1, w-GAP, y+1); // last part of line if (m_header == null || m_header.length() == 0) return;
// Header Text g.setColor(m_color); g.setFont(m_font); int x = GAP; if (!Language.getLoginLanguage().isLeftToRight()) { } g.drawString(m_header, GAP, h-SPACE-1); } // paintLine /** * Set Header * @param newHeader String - '_' are replaced by spaces */ public void setHeader(String newHeader) { m_header = newHeader.replace('_', ' '); } // setHeader /** * Get Header * @return header string */ public String getHeader() { return m_header; } // getHeader } // VLine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLine.java
1
请完成以下Java代码
public void joinTransaction() { delegate.joinTransaction(); } public boolean isJoinedToTransaction() { return delegate.isJoinedToTransaction(); } public <T> T unwrap(Class<T> cls) { return delegate.unwrap(cls); } public Object getDelegate() { return delegate.getDelegate(); } public void close() { log.info("[I229] close"); delegate.close(); } public boolean isOpen() { boolean isOpen = delegate.isOpen(); log.info("[I236] isOpen: " + isOpen); return isOpen; } public EntityTransaction getTransaction() { log.info("[I240] getTransaction()"); return delegate.getTransaction(); } public EntityManagerFactory getEntityManagerFactory() { return delegate.getEntityManagerFactory(); } public CriteriaBuilder getCriteriaBuilder() { return delegate.getCriteriaBuilder(); } public Metamodel getMetamodel() { return delegate.getMetamodel(); }
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) { return delegate.createEntityGraph(rootType); } public EntityGraph<?> createEntityGraph(String graphName) { return delegate.createEntityGraph(graphName); } public EntityGraph<?> getEntityGraph(String graphName) { return delegate.getEntityGraph(graphName); } public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) { return delegate.getEntityGraphs(entityClass); } public EntityManagerWrapper(EntityManager delegate) { this.delegate = delegate; } } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\CarsODataJPAServiceFactory.java
1
请完成以下Java代码
private List<Object> getValues(@NonNull final I_C_Invoice_Candidate ic) { final List<Object> values = new ArrayList<>(); final I_C_DocType invoiceDocType = Optional.ofNullable(DocTypeId.ofRepoIdOrNull(ic.getC_DocTypeInvoice_ID())) .map(docTypeBL::getById) .orElse(null); final DocTypeId docTypeIdToBeUsed = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() <= 0) .map(I_C_DocType::getC_DocType_ID) .map(DocTypeId::ofRepoId) .orElse(null); values.add(docTypeIdToBeUsed); values.add(ic.getAD_Org_ID()); final BPartnerLocationAndCaptureId billLocation = invoiceCandBL.getBillLocationId(ic, false); values.add(billLocation.getBpartnerRepoId()); values.add(billLocation.getBPartnerLocationRepoId()); final int currencyId = ic.getC_Currency_ID(); values.add(currencyId <= 0 ? 0 : currencyId); // Dates // 08511 workaround - we don't add dates in header aggregation key values.add(null); // ic.getDateInvoiced()); values.add(null); // ic.getDateAcct()); // task 08437 // IsSOTrx
values.add(ic.isSOTrx()); // Pricing System final int pricingSystemId = IPriceListDAO.M_PricingSystem_ID_None; // 08511 workaround values.add(pricingSystemId); values.add(invoiceCandBL.isTaxIncluded(ic)); // task 08451 final Boolean compact = true; values.add(compact ? toHashcode(ic.getDescriptionHeader()) : ic.getDescriptionHeader()); values.add(compact ? toHashcode(ic.getDescriptionBottom()) : ic.getDescriptionBottom()); final DocTypeInvoicingPoolId docTypeInvoicingPoolId = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() > 0) .map(I_C_DocType::getC_DocType_Invoicing_Pool_ID) .map(DocTypeInvoicingPoolId::ofRepoId) .orElse(null); values.add(docTypeInvoicingPoolId); return values; } private static int toHashcode(final String s) { if (Check.isEmpty(s, true)) { return 0; } return s.hashCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\agg\key\impl\ICHeaderAggregationKeyBuilder_OLD.java
1