instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public DecisionEntity findLatestDecisionByKey(String DefinitionKey) { return dataManager.findLatestDecisionByKey(DefinitionKey); } @Override public DecisionEntity findLatestDecisionByKeyAndTenantId(String DefinitionKey, String tenantId) { return dataManager.findLatestDecisionByKeyAndTenantId(DefinitionKey, tenantId); } @Override public void deleteDecisionsByDeploymentId(String deploymentId) { dataManager.deleteDecisionsByDeploymentId(deploymentId); } @Override public List<DmnDecision> findDecisionsByQueryCriteria(DecisionQueryImpl DefinitionQuery) { return dataManager.findDecisionsByQueryCriteria(DefinitionQuery); } @Override public long findDecisionCountByQueryCriteria(DecisionQueryImpl DefinitionQuery) { return dataManager.findDecisionCountByQueryCriteria(DefinitionQuery); } @Override public DecisionEntity findDecisionByDeploymentAndKey(String deploymentId, String DefinitionKey) { return dataManager.findDecisionByDeploymentAndKey(deploymentId, DefinitionKey); } @Override public DecisionEntity findDecisionByDeploymentAndKeyAndTenantId(String deploymentId, String decisionKey, String tenantId) { return dataManager.findDecisionByDeploymentAndKeyAndTenantId(deploymentId, decisionKey, tenantId); } @Override public DecisionEntity findDecisionByKeyAndVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { if (tenantId == null || DmnEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findDecisionByKeyAndVersion(definitionKey, definitionVersion); } else { return dataManager.findDecisionByKeyAndVersionAndTenantId(definitionKey, definitionVersion, tenantId);
} } @Override public List<DmnDecision> findDecisionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDecisionsByNativeQuery(parameterMap); } @Override public long findDecisionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDecisionCountByNativeQuery(parameterMap); } @Override public void updateDecisionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateDecisionTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DefinitionEntityManagerImpl.java
1
请完成以下Java代码
public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Status AD_Reference_ID=542015 * Reference name: OutboundLogLineStatus */ public static final int STATUS_AD_Reference_ID=542015; /** Print_Success = Print_Success */ public static final String STATUS_Print_Success = "Print_Success"; /** Print_Failure = Print_Failure */ public static final String STATUS_Print_Failure = "Print_Failure"; /** Email_Success = Email_Success */ public static final String STATUS_Email_Success = "Email_Success"; /** Email_Failure = Email_Failure */ public static final String STATUS_Email_Failure = "Email_Failure"; @Override public void setStatus (final @Nullable java.lang.String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() {
return get_ValueAsString(COLUMNNAME_Status); } @Override public void setStoreURI (final @Nullable java.lang.String StoreURI) { set_Value (COLUMNNAME_StoreURI, StoreURI); } @Override public java.lang.String getStoreURI() { return get_ValueAsString(COLUMNNAME_StoreURI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Log_Line.java
1
请在Spring Boot框架中完成以下Java代码
public NursingService getNursingService(String albertaApiKey, String _id) throws ApiException { ApiResponse<NursingService> resp = getNursingServiceWithHttpInfo(albertaApiKey, _id); return resp.getData(); } /** * Daten eines einzelnen Pflegedienstes abrufen * Szenario - das WaWi fragt bei Alberta nach, wie die Daten des Pflegedienstes mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id des Pflegedienstes (required) * @return ApiResponse&lt;NursingService&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<NursingService> getNursingServiceWithHttpInfo(String albertaApiKey, String _id) throws ApiException { com.squareup.okhttp.Call call = getNursingServiceValidateBeforeCall(albertaApiKey, _id, null, null); Type localVarReturnType = new TypeToken<NursingService>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Daten eines einzelnen Pflegedienstes abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, wie die Daten des Pflegedienstes mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id des Pflegedienstes (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getNursingServiceAsync(String albertaApiKey, String _id, final ApiCallback<NursingService> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() {
@Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getNursingServiceValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<NursingService>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\NursingServiceApi.java
2
请在Spring Boot框架中完成以下Java代码
public class LoginService { @Autowired private LoginDao loginDao; @Autowired private TokenService tokenService; /** * 登录表单提交 */ public JSONObject authLogin(JSONObject jsonObject) { String username = jsonObject.getString("username"); String password = jsonObject.getString("password"); JSONObject info = new JSONObject(); JSONObject user = loginDao.checkUser(username, password); if (user == null) { throw new CommonJsonException(ErrorEnum.E_10010); } String token = tokenService.generateToken(username); info.put("token", token); return CommonUtil.successJson(info); }
/** * 查询当前登录用户的权限等信息 */ public JSONObject getInfo() { //从session获取用户信息 SessionUserInfo userInfo = tokenService.getUserInfo(); log.info(userInfo.toString()); return CommonUtil.successJson(userInfo); } /** * 退出登录 */ public JSONObject logout() { tokenService.invalidateToken(); return CommonUtil.successJson(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\LoginService.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Sequence getAD_Sequence() { return get_ValueAsPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setAD_Sequence(final org.compiere.model.I_AD_Sequence AD_Sequence) { set_ValueFromPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class, AD_Sequence); } @Override public void setAD_Sequence_ID (final int AD_Sequence_ID) { if (AD_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, AD_Sequence_ID); } @Override public int getAD_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_AD_Sequence_ID); } @Override public void setCalendarDay (final @Nullable java.lang.String CalendarDay) { set_Value (COLUMNNAME_CalendarDay, CalendarDay); } @Override public java.lang.String getCalendarDay() { return get_ValueAsString(COLUMNNAME_CalendarDay); } @Override public void setCalendarMonth (final @Nullable java.lang.String CalendarMonth) {
set_Value (COLUMNNAME_CalendarMonth, CalendarMonth); } @Override public java.lang.String getCalendarMonth() { return get_ValueAsString(COLUMNNAME_CalendarMonth); } @Override public void setCalendarYear (final java.lang.String CalendarYear) { set_ValueNoCheck (COLUMNNAME_CalendarYear, CalendarYear); } @Override public java.lang.String getCalendarYear() { return get_ValueAsString(COLUMNNAME_CalendarYear); } @Override public void setCurrentNext (final int CurrentNext) { set_Value (COLUMNNAME_CurrentNext, CurrentNext); } @Override public int getCurrentNext() { return get_ValueAsInt(COLUMNNAME_CurrentNext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_No.java
1
请完成以下Java代码
public void setDocTypeId(final I_C_DunningDoc dunningDoc) { final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final DocTypeQuery query = DocTypeQuery .builder() .adClientId(dunningDoc.getAD_Client_ID()) .adOrgId(dunningDoc.getAD_Org_ID()) .docBaseType(Dunning_Constants.DocBaseType_Dunnig) .build(); final DocTypeId docTypeId = docTypeDAO.getDocTypeId(query); dunningDoc.setC_DocType_ID(docTypeId.getRepoId()); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, // ifColumnsChanged = I_C_DunningDoc.COLUMNNAME_Processed) public void createDocResponsible(final I_C_DunningDoc dunningDoc) { if (dunningDoc.isProcessed()) { Services.get(IWorkflowBL.class).createDocResponsible(dunningDoc, dunningDoc.getAD_Org_ID()); } }
/** * Updates <code>C_DunningDoc.BPartnerAddress</code> when the the <code>C_BPartner_Location_ID</code> column is changed. * Task 07359 */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = I_C_DunningDoc.COLUMNNAME_C_BPartner_Location_ID) public void updateAddressField(final I_C_DunningDoc dunningDoc) { final IDocumentLocationBL documentLocationBL = SpringContextHolder.instance.getBean(IDocumentLocationBL.class); documentLocationBL.updateRenderedAddressAndCapturedLocation(DunningDocDocumentLocationAdapterFactory.locationAdapter(dunningDoc)); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void scheduleDataExport(final I_C_DunningDoc dunningDoc) { C_DunningDoc_CreateExportData.scheduleOnTrxCommit(dunningDoc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\modelvalidator\C_DunningDoc.java
1
请在Spring Boot框架中完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { return checkSingleDraftedServiceRepairReturns(context); } @ProcessParamLookupValuesProvider( parameterName = PARAM_M_Product_ID, numericKey = true, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.list, lookupTableName = I_M_Product.Table_Name) public LookupValuesList getProducts() { final ImmutableSet<ProductId> sparePartIds = getSparePartsCalculation().getAllowedSparePartIds(); return lookupDataSourceFactory.searchInTableLookup(I_M_Product.Table_Name).findByIdsOrdered(sparePartIds); } @Override public void onParameterChanged(@NonNull final String parameterName) { if (PARAM_M_Product_ID.equals(parameterName)) { final ProductId sparePartId = this.sparePartId; if (sparePartId != null) { final Quantity qty = getSparePartsCalculation().computeQtyOfSparePartsRequiredNet(sparePartId, uomConversionBL).orElse(null); this.qtyBD = qty != null ? qty.toBigDecimal() : null; this.uomId = qty != null ? qty.getUomId() : null; } } } @Override protected String doIt() { final InOutId customerReturnId = getCustomerReturnId(); final Quantity qtyReturned = getQtyReturned();
repairCustomerReturnsService.prepareAddSparePartsToCustomerReturn() .customerReturnId(customerReturnId) .productId(sparePartId) .qtyReturned(qtyReturned) .build(); return MSG_OK; } private Quantity getQtyReturned() { if (qtyBD == null) { throw new FillMandatoryException("Qty"); } if (uomId == null) { throw new FillMandatoryException("C_UOM_ID"); } final I_C_UOM uom = uomDAO.getById(uomId); return Quantity.of(qtyBD, uom); } private SparePartsReturnCalculation getSparePartsCalculation() { SparePartsReturnCalculation sparePartsCalculation = _sparePartsCalculation; if (sparePartsCalculation == null) { sparePartsCalculation = _sparePartsCalculation = repairCustomerReturnsService.getSparePartsCalculation(getCustomerReturnId()); } return sparePartsCalculation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\CustomerReturns_AddSpareParts.java
2
请完成以下Java代码
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException { List<Record> records = new ArrayList<>(); for (String artist : artists) { Map<String, Double> tags = lastFm .topTagsFor(artist) .execute() .body() .all(); // Only keep popular tags. tags .entrySet() .removeIf(e -> !topTags.contains(e.getKey())); records.add(new Record(artist, tags)); } return records; } private static Set<String> getTop100Tags() throws IOException { return lastFm .topTags()
.execute() .body() .all(); } private static List<String> getTop100Artists() throws IOException { List<String> artists = new ArrayList<>(); for (int i = 1; i <= 2; i++) { artists.addAll(lastFm .topArtists(i) .execute() .body() .all()); } return artists; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\LastFm.java
1
请完成以下Java代码
private static String concatValues(@NonNull final Collection<String> values) { return String.join(" ", values); } @NonNull public String getSingleValue(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { return concatValues(getValueList(attributeType, valueProvider)); } @NonNull private ImmutableList<String> getValueList(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { return streamEligibleConfigs(attributeType, valueProvider) .map(config -> valueProvider.apply(config.getAttributeValue())) .filter(Check::isNotBlank) .collect(ImmutableList.toImmutableList()); } public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { return streamEligibleConfigs(attributeType, valueProvider) .map(JsonMappingConfig::getGroupKey) .filter(Check::isNotBlank) .distinct() .collect(ImmutableList.toImmutableList()); }
public List<JsonDetail> getDetailsForGroupAndType( @NonNull final String attributeGroupKey, @NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider) .filter(config -> attributeGroupKey.equals(config.getGroupKey())) .filter(config -> Check.isNotBlank(config.getAttributeKey())) .map(config -> new AbstractMap.SimpleImmutableEntry<>( Integer.parseInt(config.getAttributeKey()), valueProvider.apply(config.getAttributeValue()))) .filter(entry -> Check.isNotBlank(entry.getValue())) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.joining(" ")))); return detailsByKindId.entrySet().stream() .map(entry -> JsonDetail.builder() .kindId(entry.getKey()) .value(entry.getValue()) .build()) .collect(Collectors.toList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java
1
请完成以下Java代码
public class MetadataProjectDescriptionCustomizer implements ProjectDescriptionCustomizer { private static final char[] VALID_MAVEN_SPECIAL_CHARACTERS = new char[] { '_', '-', '.' }; private final InitializrMetadata metadata; public MetadataProjectDescriptionCustomizer(InitializrMetadata metadata) { this.metadata = metadata; } @Override public void customize(MutableProjectDescription description) { if (!StringUtils.hasText(description.getApplicationName())) { description .setApplicationName(this.metadata.getConfiguration().generateApplicationName(description.getName())); } String targetArtifactId = determineValue(description.getArtifactId(), () -> this.metadata.getArtifactId().getContent()); description.setArtifactId(cleanMavenCoordinate(targetArtifactId, "-")); if (targetArtifactId.equals(description.getBaseDirectory())) { description.setBaseDirectory(cleanMavenCoordinate(targetArtifactId, "-")); } if (!StringUtils.hasText(description.getDescription())) { description.setDescription(this.metadata.getDescription().getContent()); } String targetGroupId = determineValue(description.getGroupId(), () -> this.metadata.getGroupId().getContent()); description.setGroupId(cleanMavenCoordinate(targetGroupId, ".")); if (!StringUtils.hasText(description.getName())) { description.setName(this.metadata.getName().getContent()); } else if (targetArtifactId.equals(description.getName())) { description.setName(cleanMavenCoordinate(targetArtifactId, "-")); } description.setPackageName(this.metadata.getConfiguration() .cleanPackageName(description.getPackageName(), description.getLanguage(), this.metadata.getPackageName().getContent())); if (description.getPlatformVersion() == null) { description.setPlatformVersion(Version.parse(this.metadata.getBootVersions().getDefault().getId())); } if (!StringUtils.hasText(description.getVersion())) { description.setVersion(this.metadata.getVersion().getContent()); } } private String cleanMavenCoordinate(String coordinate, String delimiter) { String[] elements = coordinate.split("[^\\w\\-.]+"); if (elements.length == 1) { return coordinate; } StringBuilder builder = new StringBuilder(); for (String element : elements) { if (shouldAppendDelimiter(element, builder)) {
builder.append(delimiter); } builder.append(element); } return builder.toString(); } private boolean shouldAppendDelimiter(String element, StringBuilder builder) { if (builder.isEmpty()) { return false; } for (char c : VALID_MAVEN_SPECIAL_CHARACTERS) { int prevIndex = builder.length() - 1; if (element.charAt(0) == c || builder.charAt(prevIndex) == c) { return false; } } return true; } private String determineValue(String candidate, Supplier<String> fallback) { return (StringUtils.hasText(candidate)) ? candidate : fallback.get(); } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\MetadataProjectDescriptionCustomizer.java
1
请在Spring Boot框架中完成以下Java代码
public class CallDispatcherRouteBuilder extends RouteBuilder { @VisibleForTesting static final String DISPATCH_ROUTE_ID = "MF-To-ExternalSystem-Dispatcher"; @NonNull private final ProcessLogger processLogger; @VisibleForTesting final static String FROM_MF_ROUTE_ID = "RabbitMQ_from_MF_ID"; public CallDispatcherRouteBuilder(final @NonNull ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void configure() { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(StaticEndpointBuilders.direct(MF_ERROR_ROUTE_ID)); from(FROM_MF_ROUTE) .routeId(FROM_MF_ROUTE_ID) .to("direct:dispatch"); from("direct:dispatch") .routeId(DISPATCH_ROUTE_ID) .streamCache("true") .unmarshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonExternalSystemRequest.class)) .process(this::processExternalSystemRequest) .log("routing request to route ${header." + HEADER_TARGET_ROUTE + "}") .process(this::logRequestRouted) .toD("direct:${header." + HEADER_TARGET_ROUTE + "}", false) .process(this::logInvocationDone); } private void logRequestRouted(@NonNull final Exchange exchange) { final String targetRoute = exchange.getIn().getHeader(HEADER_TARGET_ROUTE, String.class); processLogger.logMessage("Routing request to: " + targetRoute, exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class)); } private void logInvocationDone(@NonNull final Exchange exchange) { final String targetRoute = exchange.getIn().getHeader(HEADER_TARGET_ROUTE, String.class); processLogger.logMessage("Invocation done: " + targetRoute, exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class)); }
private void processExternalSystemRequest(@NonNull final Exchange exchange) { final var request = exchange.getIn().getBody(JsonExternalSystemRequest.class); exchange.getIn().setHeader(HEADER_TARGET_ROUTE, request.getExternalSystemName().getName() + "-" + request.getCommand()); exchange.getIn().setHeader(HEADER_TRACE_ID, request.getTraceId()); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); } if (EmptyUtil.isNotBlank(request.getWriteAuditEndpoint())) { exchange.getIn().setHeader(HEADER_AUDIT_TRAIL, request.getWriteAuditEndpoint()); } if (request.getParameters() != null && Check.isNotBlank(request.getParameters().get(PARAM_CHILD_CONFIG_VALUE))) { exchange.getIn().setHeader(HEADER_EXTERNAL_SYSTEM_VALUE, request.getParameters().get(PARAM_CHILD_CONFIG_VALUE)); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\from_mf\CallDispatcherRouteBuilder.java
2
请完成以下Java代码
public class MybatisPrivilegeDataManager extends AbstractIdmDataManager<PrivilegeEntity> implements PrivilegeDataManager { public MybatisPrivilegeDataManager(IdmEngineConfiguration idmEngineConfiguration) { super(idmEngineConfiguration); } @Override public PrivilegeEntity create() { return new PrivilegeEntityImpl(); } @Override public Class<? extends PrivilegeEntity> getManagedEntityClass() { return PrivilegeEntityImpl.class; } @Override @SuppressWarnings("unchecked") public List<Privilege> findPrivilegeByQueryCriteria(PrivilegeQueryImpl query) { return getDbSqlSession().selectList("selectPrivilegeByQueryCriteria", query, getManagedEntityClass()); } @Override
public long findPrivilegeCountByQueryCriteria(PrivilegeQueryImpl query) { return (Long) getDbSqlSession().selectOne("selectPrivilegeCountByQueryCriteria", query); } @Override @SuppressWarnings("unchecked") public List<Privilege> findPrivilegeByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectPrivilegeByNativeQuery", parameterMap); } @Override public long findPrivilegeCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectPrivilegeCountByNativeQuery", parameterMap); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\data\impl\MybatisPrivilegeDataManager.java
1
请完成以下Java代码
public boolean isEvaluateRepetitionRule() { // Only event listeners can be repeating on occur return planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener; } @Override protected boolean shouldAggregateForSingleInstance() { return true; } @Override protected boolean shouldAggregateForMultipleInstances() { return true; } @Override protected void internalExecute() {
planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext)); planItemInstanceEntity.setOccurredTime(planItemInstanceEntity.getEndedTime()); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceOccurred(planItemInstanceEntity); } @Override protected Map<String, String> getAsyncLeaveTransitionMetadata() { throw new UnsupportedOperationException("Occur does not support async leave"); } @Override public String getOperationName() { return "[Occur plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\OccurPlanItemInstanceOperation.java
1
请完成以下Java代码
public class CalloutEXP_FormatLine extends CalloutEngine { public String column(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) { I_EXP_FormatLine formatLine = InterfaceWrapperHelper.create(mTab, I_EXP_FormatLine.class); I_AD_Column column = formatLine.getAD_Column(); if (column == null || column.getAD_Column_ID() <= 0) return ""; formatLine.setValue(column.getColumnName()); formatLine.setName(column.getColumnName()); formatLine.setAD_Reference_ID(column.getAD_Reference_ID()); if (column.isMandatory()) formatLine.setIsMandatory(true); if (column.isIdentifier() || column.isParent() || column.isKey()) { formatLine.setIsMandatory(true); formatLine.setIsPartUniqueIndex(true);
} if (!"D".equals(column.getEntityType())) { formatLine.setEntityType(column.getEntityType()); } if (DisplayType.isLookup(column.getAD_Reference_ID())) { formatLine.setType(X_EXP_FormatLine.TYPE_ReferencedEXPFormat); } return ""; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\esb\callout\CalloutEXP_FormatLine.java
1
请在Spring Boot框架中完成以下Java代码
public Buyer taxIdentifier(TaxIdentifier taxIdentifier) { this.taxIdentifier = taxIdentifier; return this; } /** * Get taxIdentifier * * @return taxIdentifier **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public TaxIdentifier getTaxIdentifier() { return taxIdentifier; } public void setTaxIdentifier(TaxIdentifier taxIdentifier) { this.taxIdentifier = taxIdentifier; } public Buyer username(String username) { this.username = username; return this; } /** * The buyer&#39;s eBay user ID. * * @return username **/ @javax.annotation.Nullable @ApiModelProperty(value = "The buyer's eBay user ID.") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Buyer buyer = (Buyer)o; return Objects.equals(this.taxAddress, buyer.taxAddress) && Objects.equals(this.taxIdentifier, buyer.taxIdentifier) && Objects.equals(this.username, buyer.username); } @Override public int hashCode() { return Objects.hash(taxAddress, taxIdentifier, username); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Buyer {\n"); sb.append(" taxAddress: ").append(toIndentedString(taxAddress)).append("\n"); sb.append(" taxIdentifier: ").append(toIndentedString(taxIdentifier)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Buyer.java
2
请完成以下Java代码
private boolean addGLJournalLine0(final I_GL_JournalLine glJournalLine) { final List<I_Fact_Acct> factAcctRecords = factAcctDAO.retrieveForDocumentLine(I_GL_Journal.Table_Name, glJournalLine.getGL_Journal_ID(), glJournalLine); // // Skip not posted GL Journal Lines, but warn the user if (factAcctRecords.isEmpty()) { final String summary = journalLineBL.getDocumentNo(glJournalLine); loggable.addLog("@Error@: @I_GL_JournalLine_ID@ @Posted@=@N@: " + summary); return false; } final I_C_TaxDeclarationLine taxDeclarationLine = createTaxDeclarationLine(glJournalLine); createTaxDeclarationAccts(taxDeclarationLine, factAcctRecords.iterator()); return true; } private I_C_TaxDeclarationLine createTaxDeclarationLine(final I_GL_JournalLine glJournalLine) { final String summary = journalLineBL.getDocumentNo(glJournalLine); final I_C_TaxDeclarationLine taxDeclarationLine = newTaxDeclarationLine(); taxDeclarationLine.setAD_Org_ID(glJournalLine.getAD_Org_ID()); taxDeclarationLine.setIsManual(false); // taxDeclarationLine.setGL_JournalLine(glJournalLine); taxDeclarationLine.setC_Currency_ID(glJournalLine.getC_Currency_ID()); taxDeclarationLine.setDateAcct(glJournalLine.getDateAcct()); taxDeclarationLine.setC_DocType_ID(glJournalLine.getGL_Journal().getC_DocType_ID()); taxDeclarationLine.setDocumentNo(summary); //
final ITaxAccountable taxAccountable = journalLineBL.asTaxAccountable(glJournalLine); // NOTE: Tax on sales transactions is booked on CR, tax on purchase transactions is booked on DR final boolean isSOTrx = taxAccountable.isAccountSignCR(); taxDeclarationLine.setIsSOTrx(isSOTrx); taxDeclarationLine.setC_Tax_ID(taxAccountable.getC_Tax_ID()); taxDeclarationLine.setTaxBaseAmt(taxAccountable.getTaxBaseAmt()); taxDeclarationLine.setTaxAmt(taxAccountable.getTaxAmt()); save(taxDeclarationLine); return taxDeclarationLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\tax\impl\TaxDeclarationLinesBuilder.java
1
请完成以下Java代码
public ResponseEntity<PageResult<DeptDto>> queryDept(DeptQueryCriteria criteria) throws Exception { List<DeptDto> depts = deptService.queryAll(criteria, true); return new ResponseEntity<>(PageUtil.toPage(depts, depts.size()),HttpStatus.OK); } @ApiOperation("查询部门:根据ID获取同级与上级数据") @PostMapping("/superior") @PreAuthorize("@el.check('user:list','dept:list')") public ResponseEntity<Object> getDeptSuperior(@RequestBody List<Long> ids, @RequestParam(defaultValue = "false") Boolean exclude) { Set<DeptDto> deptSet = new LinkedHashSet<>(); for (Long id : ids) { DeptDto deptDto = deptService.findById(id); List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>()); if(exclude){ for (DeptDto dept : depts) { if(dept.getId().equals(deptDto.getPid())) { dept.setSubCount(dept.getSubCount() - 1); } } // 编辑部门时不显示自己以及自己下级的数据,避免出现PID数据环形问题 depts = depts.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toList()); } deptSet.addAll(depts); } return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptSet)),HttpStatus.OK); } @Log("新增部门") @ApiOperation("新增部门") @PostMapping @PreAuthorize("@el.check('dept:add')") public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } deptService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改部门") @ApiOperation("修改部门") @PutMapping @PreAuthorize("@el.check('dept:edit')") public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){ deptService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} @Log("删除部门") @ApiOperation("删除部门") @DeleteMapping @PreAuthorize("@el.check('dept:del')") public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){ Set<DeptDto> deptDtos = new HashSet<>(); for (Long id : ids) { List<Dept> deptList = deptService.findByPid(id); deptDtos.add(deptService.findById(id)); if(CollectionUtil.isNotEmpty(deptList)){ deptDtos = deptService.getDeleteDepts(deptList, deptDtos); } } // 验证是否被角色或用户关联 deptService.verification(deptDtos); deptService.delete(deptDtos); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DeptController.java
1
请完成以下Java代码
private Quantity convertDurationToQuantity( final Duration duration, final ProductId resourceProductId, final UomId targetUomId) { final Quantity qty = convertDurationToQuantity(duration, resourceProductId); return utils.convertToUOM(qty, targetUomId, resourceProductId); } private Quantity convertDurationToQuantity( final Duration duration, final ProductId resourceProductId) { final I_C_UOM durationUOM = productsService.getStockUOM(resourceProductId); final TemporalUnit durationUnit = UOMUtil.toTemporalUnit(durationUOM); final BigDecimal durationBD = DurationUtils.toBigDecimal(duration, durationUnit); return Quantity.of(durationBD, durationUOM); } private CostPrice getProductActualCostPrice(@NonNull final CostSegmentAndElement costSegmentAndElement) { return currentCostsRepo.getOrCreate(costSegmentAndElement)
.getCostPrice(); } @Override public MoveCostsResult createMovementCosts(@NonNull final MoveCostsRequest request) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } @Override public CostDetailAdjustment recalculateCostDetailAmountAndUpdateCurrentCost(final CostDetail costDetail, final CurrentCost currentCost) { return standardCostingMethodHandler.recalculateCostDetailAmountAndUpdateCurrentCost(costDetail, currentCost); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\costing\methods\ManufacturingStandardCostingMethodHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaUserCredentialsDao extends JpaAbstractDao<UserCredentialsEntity, UserCredentials> implements UserCredentialsDao, TenantEntityDao<UserCredentials> { @Autowired private UserCredentialsRepository userCredentialsRepository; @Override protected Class<UserCredentialsEntity> getEntityClass() { return UserCredentialsEntity.class; } @Override protected JpaRepository<UserCredentialsEntity, UUID> getRepository() { return userCredentialsRepository; } @Override public UserCredentials findByUserId(TenantId tenantId, UUID userId) { return DaoUtil.getData(userCredentialsRepository.findByUserId(userId)); } @Override public UserCredentials findByActivateToken(TenantId tenantId, String activateToken) { return DaoUtil.getData(userCredentialsRepository.findByActivateToken(activateToken)); } @Override public UserCredentials findByResetToken(TenantId tenantId, String resetToken) { return DaoUtil.getData(userCredentialsRepository.findByResetToken(resetToken)); } @Override public void removeByUserId(TenantId tenantId, UserId userId) { userCredentialsRepository.removeByUserId(userId.getId()); } @Override public void setLastLoginTs(TenantId tenantId, UserId userId, long lastLoginTs) { userCredentialsRepository.updateLastLoginTsByUserId(userId.getId(), lastLoginTs);
} @Override public int incrementFailedLoginAttempts(TenantId tenantId, UserId userId) { return userCredentialsRepository.incrementFailedLoginAttemptsByUserId(userId.getId()); } @Override public void setFailedLoginAttempts(TenantId tenantId, UserId userId, int failedLoginAttempts) { userCredentialsRepository.updateFailedLoginAttemptsByUserId(userId.getId(), failedLoginAttempts); } @Override public PageData<UserCredentials> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(userCredentialsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserCredentialsDao.java
2
请完成以下Spring Boot application配置
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1 spring.datasource.primary.username=root spring.datasource.primary.password=52261340 spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver spring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2 spring.datasource.secondary.username=root spring.datasource.seco
ndary.password=52261340 spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
repos\SpringBoot-Learning-master\1.x\Chapter3-2-4\src\main\resources\application.properties
2
请完成以下Java代码
public static int nthPadovanTermIterativeMethodWithVariables(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } int p0 = 1, p1 = 1, p2 = 1; int tempNthTerm; for (int i = 3; i <= n; i++) { tempNthTerm = p0 + p1; p0 = p1; p1 = p2; p2 = tempNthTerm; } return p2; }
public static int nthPadovanTermUsingFormula(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } // Padovan spiral constant (plastic number) - the real root of x^3 - x - 1 = 0 final double PADOVAN_CONSTANT = 1.32471795724474602596; // Normalization factor to approximate Padovan sequence values final double NORMALIZATION_FACTOR = 1.045356793252532962; double p = Math.pow(PADOVAN_CONSTANT, n - 1); return (int) Math.round(p / NORMALIZATION_FACTOR); } }
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\padovan\PadovanSeriesUtils.java
1
请完成以下Java代码
public void setCn(int cn) { this.cn = cn; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("[%s] cn=%d, codelen=%d, ", word, cn, codelen)); sb.append("code=("); for (int i = 0; i < codelen; i++) { if (i > 0) sb.append(','); sb.append(code[i]); }
sb.append("), point=("); for (int i = 0; i < codelen; i++) { if (i > 0) sb.append(','); sb.append(point[i]); } sb.append(")"); return sb.toString(); } @Override public int compareTo(VocabWord that) { return that.cn - this.cn; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\VocabWord.java
1
请完成以下Java代码
public void setReadWrite (boolean rw) { if (super.isEnabled() != rw) super.setEnabled(rw); } // setReadWrite /** * Is it possible to edit * @return true, if editable */ @Override public boolean isReadWrite() { return super.isEnabled(); } // isReadWrite /** * Set Editor to value * @param value value of the editor */ @Override public void setValue (Object value) { if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */
@Override public Object getValue() { return getText(); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return getText(); } // getDisplay } // CToggleButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CToggleButton.java
1
请完成以下Java代码
protected PreparedStatement createPreparedStatement() throws SQLException { final PreparedStatement pstmt = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); return pstmt; } @Override protected CityVO fetch(ResultSet rs) throws SQLException { final CityVO vo = new CityVO(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4)); return vo; } }); } private int getAD_Client_ID() { return Env.getAD_Client_ID(Env.getCtx()); } private int getC_Country_ID() { return countryId; }
public void setC_Country_ID(final int countryId) { this.countryId = countryId > 0 ? countryId : -1; } public int getC_Region_ID() { return regionId; } public void setC_Region_ID(final int regionId) { this.regionId = regionId > 0 ? regionId : -1; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\CityAutoCompleter.java
1
请完成以下Java代码
public class DefaultInvoiceHistoryTabHandler implements IInvoiceHistoryTabHandler { /** * Map is sorted */ private final Map<Integer, Boolean> tabEnabledMap = new TreeMap<>(); public DefaultInvoiceHistoryTabHandler() { super(); } @Override public void setTabEnabled(final int tabIndex, final boolean enabled) { tabEnabledMap.put(tabIndex, enabled); } @Override public boolean isTabEnabled(final int tabIndex) { final Boolean enabled = tabEnabledMap.get(tabIndex); return enabled == Boolean.TRUE || enabled == null; // null is also true } @Override public int getTabIndexEffective(final int tabIndex) { int tabIndexToUse = tabIndex; for (final Integer tabIndexEnabled : tabEnabledMap.keySet()) { if (tabIndexEnabled > tabIndex) // note that we must go one additional step (i.e first tab) { return tabIndexToUse; // we shall not go over the tab we're searching for } if (!isTabEnabled(tabIndexEnabled)) // if tab is not enabled before, then assume an earlier tab (one position before)) {
tabIndexToUse--; } } return tabIndexToUse; } @Override public void initializeTab(final Runnable initializeTabRunnable, final int tabIndex) { final Boolean enabled = isTabEnabled(tabIndex); if (enabled) { initializeTabRunnable.run(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\history\impl\DefaultInvoiceHistoryTabHandler.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public boolean isInheritBusinessKey() { return inheritBusinessKey; } public void setInheritBusinessKey(boolean inheritBusinessKey) { this.inheritBusinessKey = inheritBusinessKey; } public CallActivity clone() { CallActivity clone = new CallActivity(); clone.setValues(this); return clone; } public void setValues(CallActivity otherElement) { super.setValues(otherElement); setCalledElement(otherElement.getCalledElement());
setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); inParameters = new ArrayList<IOParameter>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<IOParameter>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CallActivity.java
1
请完成以下Java代码
public List<HistoryEvent> createHistoryEvents(HistoryEventProducer producer) { return producer.createUserOperationLogEvents(context); } }); } protected boolean writeUserOperationLogOnlyWithLoggedInUser() { return Context.getCommandContext().isRestrictUserOperationLogToAuthenticatedUsers(); } protected boolean isUserOperationLogEnabledOnCommandContext() { return Context.getCommandContext().isUserOperationLogEnabled(); } protected String getOperationType(IdentityOperationResult operationResult) { switch (operationResult.getOperation()) { case IdentityOperationResult.OPERATION_CREATE: return UserOperationLogEntry.OPERATION_TYPE_CREATE;
case IdentityOperationResult.OPERATION_UPDATE: return UserOperationLogEntry.OPERATION_TYPE_UPDATE; case IdentityOperationResult.OPERATION_DELETE: return UserOperationLogEntry.OPERATION_TYPE_DELETE; case IdentityOperationResult.OPERATION_UNLOCK: return UserOperationLogEntry.OPERATION_TYPE_UNLOCK; default: return null; } } protected void configureQuery(UserOperationLogQueryImpl query) { getAuthorizationManager().configureUserOperationLogQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserOperationLogManager.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractValueTypeImpl other = (AbstractValueTypeImpl) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name))
return false; return true; } protected Boolean isTransient(Map<String, Object> valueInfo) { if (valueInfo != null && valueInfo.containsKey(VALUE_INFO_TRANSIENT)) { Object isTransient = valueInfo.get(VALUE_INFO_TRANSIENT); if (isTransient instanceof Boolean) { return (Boolean) isTransient; } else { throw new IllegalArgumentException("The property 'transient' should have a value of type 'boolean'."); } } return false; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\AbstractValueTypeImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PrintFormatId implements RepoIdAware { @JsonCreator public static PrintFormatId ofRepoId(final int repoId) { return new PrintFormatId(repoId); } public static PrintFormatId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PrintFormatId(repoId) : null; } public static Optional<PrintFormatId> optionalOfRepoId(@Nullable final Integer repoId) { return repoId != null ? Optional.ofNullable(ofRepoIdOrNull(repoId)) : Optional.empty(); } int repoId; private PrintFormatId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "AD_PrintFormat_ID"); } @JsonValue @Override public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final PrintFormatId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\PrintFormatId.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ResponsibleType AD_Reference_ID=304 * Reference name: WF_Participant Type */ public static final int RESPONSIBLETYPE_AD_Reference_ID=304; /** Organisation = O */ public static final String RESPONSIBLETYPE_Organisation = "O"; /** Human = H */
public static final String RESPONSIBLETYPE_Human = "H"; /** Rolle = R */ public static final String RESPONSIBLETYPE_Rolle = "R"; /** Systemressource = S */ public static final String RESPONSIBLETYPE_Systemressource = "S"; /** Other = X */ public static final String RESPONSIBLETYPE_Other = "X"; @Override public void setResponsibleType (final java.lang.String ResponsibleType) { set_Value (COLUMNNAME_ResponsibleType, ResponsibleType); } @Override public java.lang.String getResponsibleType() { return get_ValueAsString(COLUMNNAME_ResponsibleType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java
1
请完成以下Java代码
public void setPaySelection_includedTab (java.lang.String PaySelection_includedTab) { set_Value (COLUMNNAME_PaySelection_includedTab, PaySelection_includedTab); } /** Get PaySelection_includedTab. @return PaySelection_includedTab */ @Override public java.lang.String getPaySelection_includedTab () { return (java.lang.String)get_Value(COLUMNNAME_PaySelection_includedTab); } /** * PaySelectionTrxType AD_Reference_ID=541109 * Reference name: PaySelectionTrxType */ public static final int PAYSELECTIONTRXTYPE_AD_Reference_ID=541109; /** Direct Debit = DD */ public static final String PAYSELECTIONTRXTYPE_DirectDebit = "DD"; /** Credit Transfer = CT */ public static final String PAYSELECTIONTRXTYPE_CreditTransfer = "CT"; /** Set Transaktionsart. @param PaySelectionTrxType Transaktionsart */ @Override public void setPaySelectionTrxType (java.lang.String PaySelectionTrxType) { set_Value (COLUMNNAME_PaySelectionTrxType, PaySelectionTrxType); } /** Get Transaktionsart. @return Transaktionsart */ @Override public java.lang.String getPaySelectionTrxType () { return (java.lang.String)get_Value(COLUMNNAME_PaySelectionTrxType); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Gesamtbetrag. @param TotalAmt Gesamtbetrag */ @Override public void setTotalAmt (java.math.BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Gesamtbetrag. @return Gesamtbetrag */ @Override public java.math.BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelection.java
1
请在Spring Boot框架中完成以下Java代码
public class AdMessageId implements RepoIdAware { int repoId; private AdMessageId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Message_Id"); } @NonNull @JsonCreator public static AdMessageId ofRepoId(final int repoId) { return new AdMessageId(repoId); } @Nullable public static AdMessageId ofRepoIdOrNull(final int repoId) {
return repoId > 0 ? ofRepoId(repoId) : null; } @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final AdMessageId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(@Nullable final AdMessageId id1, @Nullable final AdMessageId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessageId.java
2
请完成以下Java代码
public String getButtonText() { return getButtonConfigProperty("text"); } @JsonIgnore public void setButtonText(String buttonText) { getButtonConfig().ifPresent(buttonConfig -> { buttonConfig.set("text", new TextNode(buttonText)); }); } @NoXss(fieldName = "web notification button link") @Length(fieldName = "web notification button link", max = 300, message = "cannot be longer than 300 chars") @JsonIgnore public String getButtonLink() { return getButtonConfigProperty("link"); } @JsonIgnore public void setButtonLink(String buttonLink) { getButtonConfig().ifPresent(buttonConfig -> { buttonConfig.set("link", new TextNode(buttonLink)); }); } private String getButtonConfigProperty(String property) { return getButtonConfig() .map(buttonConfig -> buttonConfig.get(property)) .filter(JsonNode::isTextual) .map(JsonNode::asText).orElse(null); }
private Optional<ObjectNode> getButtonConfig() { return Optional.ofNullable(additionalConfig) .map(config -> config.get("actionButtonConfig")).filter(JsonNode::isObject) .map(config -> (ObjectNode) config); } @Override public NotificationDeliveryMethod getMethod() { return NotificationDeliveryMethod.WEB; } @Override public WebDeliveryMethodNotificationTemplate copy() { return new WebDeliveryMethodNotificationTemplate(this); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\template\WebDeliveryMethodNotificationTemplate.java
1
请完成以下Java代码
public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() {
RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); Object accessToken = request.getParameter("accessToken"); if(accessToken == null) { log.warn("access token is empty"); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); return null; } log.info("access token ok"); return null; } }
repos\SpringBoot-Learning-master\1.x\Chapter9-1-5\api-gateway\src\main\java\com\didispace\filter\AccessFilter.java
1
请完成以下Java代码
public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) { this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } @Override public boolean supports(ConfigAttribute attribute) { for (AccessDecisionVoter<?> voter : this.decisionVoters) { if (voter.supports(attribute)) { return true; } } return false; } /** * Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support * the presented class. * <p>
* If one or more voters cannot support the presented class, <code>false</code> is * returned. * @param clazz the type of secured object being presented * @return true if this type is supported */ @Override public boolean supports(Class<?> clazz) { for (AccessDecisionVoter<?> voter : this.decisionVoters) { if (!voter.supports(clazz)) { return false; } } return true; } @Override public String toString() { return this.getClass().getSimpleName() + " [DecisionVoters=" + this.decisionVoters + ", AllowIfAllAbstainDecisions=" + this.allowIfAllAbstainDecisions + "]"; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AbstractAccessDecisionManager.java
1
请完成以下Java代码
private void bind(@Nullable ConfigurationPropertiesBean bean) { if (bean == null) { return; } Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT, "Cannot bind @ConfigurationProperties for bean '" + bean.getName() + "'. Ensure that @ConstructorBinding has not been applied to regular bean"); try { this.binder.bind(bean); } catch (Exception ex) { throw new ConfigurationPropertiesBindException(bean, ex); } } /** * Register a {@link ConfigurationPropertiesBindingPostProcessor} bean if one is not
* already registered. * @param registry the bean definition registry * @since 2.2.0 */ public static void register(BeanDefinitionRegistry registry) { Assert.notNull(registry, "'registry' must not be null"); if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder .rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class) .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, definition); } ConfigurationPropertiesBinder.register(registry); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindingPostProcessor.java
1
请完成以下Java代码
protected void parseConfiguration(String configuration) { try { JsonNode jsonConfiguration = objectMapper.readTree(configuration); parseConfiguration(jsonConfiguration); } catch (IOException e) { throw new HalRelationCacheConfigurationException("Unable to parse cache configuration", e); } } protected void parseConfiguration(JsonNode jsonConfiguration) { parseCacheImplementationClass(jsonConfiguration); parseCacheConfigurations(jsonConfiguration); } protected void parseCacheImplementationClass(JsonNode jsonConfiguration) { JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHE_IMPLEMENTATION); if (jsonNode != null) { String cacheImplementationClassName = jsonNode.textValue(); Class<?> cacheImplementationClass = loadClass(cacheImplementationClassName); setCacheImplementationClass(cacheImplementationClass); } else { throw new HalRelationCacheConfigurationException("Unable to find the " + CONFIG_CACHE_IMPLEMENTATION + " parameter"); } } protected void parseCacheConfigurations(JsonNode jsonConfiguration) { JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHES); if (jsonNode != null) { Iterator<Entry<String, JsonNode>> cacheConfigurations = jsonNode.fields(); while (cacheConfigurations.hasNext()) { Entry<String, JsonNode> cacheConfiguration = cacheConfigurations.next();
parseCacheConfiguration(cacheConfiguration.getKey(), cacheConfiguration.getValue()); } } } @SuppressWarnings("unchecked") protected void parseCacheConfiguration(String halResourceClassName, JsonNode jsonConfiguration) { try { Class<?> halResourceClass = loadClass(halResourceClassName); Map<String, Object> configuration = objectMapper.treeToValue(jsonConfiguration, Map.class); addCacheConfiguration(halResourceClass, configuration); } catch (IOException e) { throw new HalRelationCacheConfigurationException("Unable to parse cache configuration for HAL resource " + halResourceClassName); } } protected Class<?> loadClass(String className) { try { // use classloader which loaded the REST api classes return Class.forName(className, true, HalRelationCacheConfiguration.class.getClassLoader()); } catch (ClassNotFoundException e) { throw new HalRelationCacheConfigurationException("Unable to load class of cache configuration " + className, e); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalRelationCacheConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
private String reserveDocumentNo(@NonNull final DocTypeId docTypeId) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false) .setClientId(Env.getClientId()) .setFailOnError(true) .build(); if (documentNo == null || documentNo == IDocumentNoBuilder.NO_DOCUMENTNO) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } private ShipmentDeclaration createShipmentDeclaration( @NonNull final DocTypeId docTypeId, @NonNull final Set<InOutAndLineId> shipmentAndLineIds, @NonNull final String docAction, @NonNull final String documentNo) { Check.assumeNotEmpty(shipmentAndLineIds, "shipmentAndLineIds is not empty"); final InOutId shipmentId = CollectionUtils.extractSingleElement(shipmentAndLineIds, InOutAndLineId::getInOutId); final I_M_InOut shipment = Services.get(IInOutDAO.class).getById(shipmentId); final ImmutableList<ShipmentDeclarationLine> shipmentDeclarationLines = shipmentAndLineIds .stream() .map(shipmentAndLineId -> createShipmentDeclarationLine(shipmentAndLineId)) .collect(ImmutableList.toImmutableList()); final ShipmentDeclaration shipmentDeclaration = ShipmentDeclaration.builder() .docTypeId(docTypeId) .documentNo(documentNo) // .bpartnerAndLocationId(BPartnerLocationId.ofRepoId(shipment.getC_BPartner_ID(), shipment.getC_BPartner_Location_ID())) .userId(UserId.ofRepoIdOrNull(shipment.getAD_User_ID())) // .shipmentDate(TimeUtil.asLocalDate(shipment.getMovementDate())) .orgId(OrgId.ofRepoId(shipment.getAD_Org_ID())) .shipmentId(shipmentId) // .docStatus(IDocument.STATUS_Drafted) .docAction(docAction) // .lines(shipmentDeclarationLines) // .build();
shipmentDeclaration.updateLineNos(); return shipmentDeclaration; } private ShipmentDeclarationLine createShipmentDeclarationLine(final InOutAndLineId shipmentAndLineId) { final InOutLineId shipmentLineId = shipmentAndLineId.getInOutLineId(); final I_M_InOutLine shipmentLineRecord = Services.get(IInOutDAO.class).getLineByIdInTrx(shipmentLineId); final ProductId productId = ProductId.ofRepoId(shipmentLineRecord.getM_Product_ID()); final I_M_Product product = Services.get(IProductDAO.class).getById(productId); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(shipmentLineRecord.getC_UOM_ID()); return ShipmentDeclarationLine.builder() .orgId(OrgId.ofRepoId(shipmentLineRecord.getAD_Org_ID())) .packageSize(product.getPackageSize()) .productId(productId) .quantity(Quantity.of(shipmentLineRecord.getMovementQty(), uom)) .shipmentLineId(shipmentLineId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\service\ShipmentDeclarationCreator.java
2
请在Spring Boot框架中完成以下Java代码
static RsaKeyConversionServicePostProcessor conversionServicePostProcessor() { return new RsaKeyConversionServicePostProcessor(); } private List<SecurityWebFilterChain> getSecurityWebFilterChains() { List<SecurityWebFilterChain> result = this.securityWebFilterChains; if (ObjectUtils.isEmpty(result)) { return Arrays.asList(springSecurityFilterChain()); } return result; } private SecurityWebFilterChain springSecurityFilterChain() { ServerHttpSecurity http = this.context.getBean(ServerHttpSecurity.class); return springSecurityFilterChain(http); } /** * The default {@link ServerHttpSecurity} configuration. * @param http * @return */ private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults());
http.formLogin(withDefaults()); } SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard { static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultSecurPharmUserNotifications implements SecurPharmUserNotifications { private static final String MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE = "SecurpharmActionResultErrorNotificationMessage"; @Override public void notifyProductDecodeAndVerifyError( @NonNull final UserId responsibleId, @NonNull final SecurPharmProduct product) { sendNotification( responsibleId, MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE, TableRecordReference.of(I_M_Securpharm_Productdata_Result.Table_Name, product.getId())); } @Override public void notifyDecommissionFailed( @NonNull final UserId responsibleId, @NonNull final DecommissionResponse response) { sendNotification( responsibleId, MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE, TableRecordReference.of(org.compiere.model.I_M_Inventory.Table_Name, response.getInventoryId())); } @Override public void notifyUndoDecommissionFailed( @NonNull final UserId responsibleId, @NonNull final UndoDecommissionResponse response) { sendNotification( responsibleId, MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE, TableRecordReference.of(org.compiere.model.I_M_Inventory.Table_Name, response.getInventoryId())); }
private void sendNotification( @NonNull final UserId recipientUserId, @NonNull final String notificationADMessage, @NonNull final TableRecordReference recordRef) { final String message = Services.get(IMsgBL.class).getMsg(Env.getCtx(), notificationADMessage); final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .recipientUserId(recipientUserId) .contentPlain(message) .targetAction(UserNotificationRequest.TargetRecordAction.of(recordRef)) .build(); Services.get(INotificationBL.class).sendAfterCommit(userNotificationRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\notifications\DefaultSecurPharmUserNotifications.java
2
请在Spring Boot框架中完成以下Java代码
public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public boolean isIgnoreContentIfUnsuccess() { return ignoreContentIfUnsuccess; } public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) { this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess; } public String getPostData() { return postData; } public void setPostData(String postData) { this.postData = postData; } public ClientKeyStore getClientKeyStore() { return clientKeyStore;
} public void setClientKeyStore(ClientKeyStore clientKeyStore) { this.clientKeyStore = clientKeyStore; } public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() { return TrustKeyStore; } public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) { TrustKeyStore = trustKeyStore; } public boolean isHostnameVerify() { return hostnameVerify; } public void setHostnameVerify(boolean hostnameVerify) { this.hostnameVerify = hostnameVerify; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
2
请完成以下Java代码
private static JsonCountStatus computeCountStatus(final InventoryLineHU lineHU) { return JsonCountStatus.ofIsCountedFlag(lineHU.isCounted()); } public List<JsonInventoryLineHU> toJsonInventoryLineHUs(@NonNull final InventoryLine line) { return line.getInventoryLineHUs() .stream() .filter(lineHU -> lineHU.getId() != null) .map(lineHU -> toJson(lineHU, line)) .collect(ImmutableList.toImmutableList()); } public JsonInventoryLineHU toJson(final InventoryLineHU lineHU, InventoryLine line) { final ProductInfo product = products.getById(line.getProductId()); final HuId huId = lineHU.getHuId(); final String productName = product.getProductName().translate(adLanguage); final String huDisplayName = huId != null ? handlingUnits.getDisplayName(huId) : null; return JsonInventoryLineHU.builder() .id(lineHU.getIdNotNull()) .caption(CoalesceUtil.firstNotBlank(huDisplayName, productName)) .productId(product.getProductId()) .productNo(product.getProductNo()) .productName(productName) .locatorId(line.getLocatorId().getRepoId())
.locatorName(warehouses.getLocatorName(line.getLocatorId())) .huId(huId) .huDisplayName(huDisplayName) .uom(lineHU.getUOMSymbol()) .qtyBooked(lineHU.getQtyBook().toBigDecimal()) .qtyCount(lineHU.getQtyCount().toBigDecimal()) .countStatus(computeCountStatus(lineHU)) .attributes(loadAllDetails ? JsonAttribute.of(asis.getById(lineHU.getAsiId()), adLanguage) : null) .build(); } public JsonInventoryLineHU toJson(final InventoryLine line, final InventoryLineHUId lineHUId) { final InventoryLineHU lineHU = line.getInventoryLineHUById(lineHUId); return toJson(lineHU, line); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\mappers\JsonInventoryJobMapper.java
1
请完成以下Java代码
public <D> Mono<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseMono.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } private static class DefaultRetrieveSubscriptionSpec extends RetrieveSpecSupport implements RetrieveSubscriptionSpec { private final Flux<ClientGraphQlResponse> responseFlux; DefaultRetrieveSubscriptionSpec(Flux<ClientGraphQlResponse> responseFlux, String path) { super(path); this.responseFlux = responseFlux; } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Flux<D> toEntity(Class<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Flux<D> toEntity(ParameterizedTypeReference<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @Override public <D> Flux<List<D>> toEntityList(Class<D> elementType) { return this.responseFlux.map((response) -> {
ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } @Override public <D> Flux<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseFlux.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultGraphQlClient.java
1
请完成以下Java代码
public class C_Invoice { private static final Logger logger = LogManager.getLogger(C_Invoice.class); @DocValidate(timings = { ModelValidator.TIMING_AFTER_PREPARE }) public void setDunningGraceIfAutomatic(final I_C_Invoice invoice) { Services.get(IInvoiceSourceBL.class).setDunningGraceIfManaged(invoice); InterfaceWrapperHelper.save(invoice); } /** * This method is triggered when DunningGrace field is changed. * * NOTE: to developer: please keep this method with only ifColumnsChanged=DunningGrace because we want to avoid update cycles between invoice and dunning candidate * * @param invoice */ @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE , ifColumnsChanged = I_C_Invoice.COLUMNNAME_DunningGrace) public void validateCandidatesOnDunningGraceChange(final I_C_Invoice invoice) { final Timestamp dunningGraceDate = invoice.getDunningGrace(); logger.debug("DunningGraceDate: {}", dunningGraceDate); final IDunningDAO dunningDAO = Services.get(IDunningDAO.class); final IDunningBL dunningBL = Services.get(IDunningBL.class); final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); final String trxName = InterfaceWrapperHelper.getTrxName(invoice); final IDunningContext context = dunningBL.createDunningContext(ctx, null, // dunningLevel null, // dunningDate trxName); final I_C_Dunning_Candidate callerCandidate = InterfaceWrapperHelper.getDynAttribute(invoice, C_Dunning_Candidate.POATTR_CallerPO); // // Gets dunning candidates for specific invoice, to check if they are still viable. final List<I_C_Dunning_Candidate> candidates = dunningDAO.retrieveDunningCandidates( context, getTableId(I_C_Invoice.class),
invoice.getC_Invoice_ID()); for (final I_C_Dunning_Candidate candidate : candidates) { if (callerCandidate != null && callerCandidate.getC_Dunning_Candidate_ID() == candidate.getC_Dunning_Candidate_ID()) { // skip the caller candidate to avoid cycles continue; } if (candidate.isProcessed()) { logger.debug("Skip processed candidate: {}", candidate); continue; } if (dunningBL.isExpired(candidate, dunningGraceDate)) { logger.debug("Deleting expired candidate: {}", candidate); InterfaceWrapperHelper.delete(candidate); } else { logger.debug("Updating DunningGrace for candidate: {}", candidate); candidate.setDunningGrace(invoice.getDunningGrace()); InterfaceWrapperHelper.save(candidate); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\model\validator\C_Invoice.java
1
请完成以下Java代码
public Integer getFactoryStatus() { return factoryStatus; } public void setFactoryStatus(Integer factoryStatus) { this.factoryStatus = factoryStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public Integer getProductCommentCount() { return productCommentCount; } public void setProductCommentCount(Integer productCommentCount) { this.productCommentCount = productCommentCount; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getBigPic() {
return bigPic; } public void setBigPic(String bigPic) { this.bigPic = bigPic; } public String getBrandStory() { return brandStory; } public void setBrandStory(String brandStory) { this.brandStory = brandStory; } @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(", firstLetter=").append(firstLetter); sb.append(", sort=").append(sort); sb.append(", factoryStatus=").append(factoryStatus); sb.append(", showStatus=").append(showStatus); sb.append(", productCount=").append(productCount); sb.append(", productCommentCount=").append(productCommentCount); sb.append(", logo=").append(logo); sb.append(", bigPic=").append(bigPic); sb.append(", brandStory=").append(brandStory); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java
1
请完成以下Java代码
protected <ReqT> Listener<ReqT> noOpCallListener() { return new Listener<ReqT>() {}; } /** * Close the call with {@link Status#UNAUTHENTICATED}. * * @param call The call to close. * @param aex The exception that was the cause. */ protected void closeCallUnauthenticated(final ServerCall<?, ?> call, final AuthenticationException aex) { log.debug(UNAUTHENTICATED_DESCRIPTION, aex); call.close(Status.UNAUTHENTICATED.withCause(aex).withDescription(UNAUTHENTICATED_DESCRIPTION), new Metadata()); } /** * Close the call with {@link Status#PERMISSION_DENIED}. * * @param call The call to close. * @param aex The exception that was the cause. */ protected void closeCallAccessDenied(final ServerCall<?, ?> call, final AccessDeniedException aex) { log.debug(ACCESS_DENIED_DESCRIPTION, aex); call.close(Status.PERMISSION_DENIED.withCause(aex).withDescription(ACCESS_DENIED_DESCRIPTION), new Metadata()); } /** * Server call listener that catches and handles exceptions in {@link #onHalfClose()}. * * @param <ReqT> The type of the request. * @param <RespT> The type of the response. */
private class ExceptionTranslatorServerCallListener<ReqT, RespT> extends SimpleForwardingServerCallListener<ReqT> { private final ServerCall<ReqT, RespT> call; protected ExceptionTranslatorServerCallListener(final Listener<ReqT> delegate, final ServerCall<ReqT, RespT> call) { super(delegate); this.call = call; } @Override // Unary calls error out here public void onHalfClose() { try { super.onHalfClose(); } catch (final AuthenticationException aex) { closeCallUnauthenticated(this.call, aex); } catch (final AccessDeniedException aex) { closeCallAccessDenied(this.call, aex); } } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\ExceptionTranslatingServerInterceptor.java
1
请完成以下Java代码
public void save(@NonNull final I_PP_Order_BOM orderBOM) { saveRecord(orderBOM); } @Override public void save(@NonNull final I_PP_Order_BOMLine orderBOMLine) { saveRecord(orderBOMLine); } @Override public void deleteByOrderId(@NonNull final PPOrderId orderId) { final I_PP_Order_BOM orderBOM = getByOrderIdOrNull(orderId); if (orderBOM != null) { InterfaceWrapperHelper.delete(orderBOM); } } @Override public void markBOMLinesAsProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(true);
save(orderBOMLine); } } @Override public void markBOMLinesAsNotProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(false); save(orderBOMLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMDAO.java
1
请完成以下Java代码
public void setPayload(PayloadType value) { this.payload = value; } /** * Gets the value of the signature property. * * @return * possible object is * {@link SignatureType } * */ public SignatureType getSignature() { return signature; } /** * Sets the value of the signature property. * * @param value * allowed object is * {@link SignatureType } * */ public void setSignature(SignatureType value) { this.signature = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } /** * Gets the value of the modus property. * * @return * possible object is * {@link String } * */ public String getModus() { if (modus == null) { return "production"; } else { return modus; } }
/** * Sets the value of the modus property. * * @param value * allowed object is * {@link String } * */ public void setModus(String value) { this.modus = value; } /** * Gets the value of the validationStatus property. * * @return * possible object is * {@link Long } * */ public Long getValidationStatus() { return validationStatus; } /** * Sets the value of the validationStatus property. * * @param value * allowed object is * {@link Long } * */ public void setValidationStatus(Long value) { this.validationStatus = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RequestType.java
1
请完成以下Java代码
public MobileApp findMobileAppById(TenantId tenantId, MobileAppId mobileAppId) { log.trace("Executing findMobileAppById [{}] [{}]", tenantId, mobileAppId); return mobileAppDao.findById(tenantId, mobileAppId.getId()); } @Override public PageData<MobileApp> findMobileAppsByTenantId(TenantId tenantId, PlatformType platformType, PageLink pageLink) { log.trace("Executing findMobileAppInfosByTenantId [{}]", tenantId); return mobileAppDao.findByTenantId(tenantId, platformType, pageLink); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findMobileAppById(tenantId, new MobileAppId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(mobileAppDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteMobileAppById(tenantId, (MobileAppId) id); } @Override public MobileApp findByBundleIdAndPlatformType(TenantId tenantId, MobileAppBundleId mobileAppBundleId, PlatformType platformType) { log.trace("Executing findAndroidQrConfig, tenantId [{}], mobileAppBundleId [{}]", tenantId, mobileAppBundleId); return mobileAppDao.findByBundleIdAndPlatformType(tenantId, mobileAppBundleId, platformType); } @Override public MobileApp findMobileAppByPkgNameAndPlatformType(String pkgName, PlatformType platformType) {
log.trace("Executing findMobileAppByPkgNameAndPlatformType, pkgName [{}], platform [{}]", pkgName, platformType); Validator.checkNotNull(platformType, PLATFORM_TYPE_IS_REQUIRED); return mobileAppDao.findByPkgNameAndPlatformType(TenantId.SYS_TENANT_ID, pkgName, platformType); } @Override public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId); mobileAppDao.deleteByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
final class OrgImageLocalFileLoader { private final IOrgDAO orgsRepo = Services.get(IOrgDAO.class); private final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class); private final IClientDAO clientsRepo = Services.get(IClientDAO.class); private final OrgLogoResourceNameMatcher orgLogoResourceNameMatcher; public OrgImageLocalFileLoader() { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); this.orgLogoResourceNameMatcher = new OrgLogoResourceNameMatcher(sysConfigBL); } public Optional<File> getImageLocalFile(@NonNull final OrgResourceNameContext context) { return retrieveImageId(context).flatMap(ImageUtils::createTempImageFile); } public boolean isLogoOrImageResourceName(final OrgResourceNameContext context) { return orgLogoResourceNameMatcher.matches(context.getResourceName()) || OrgImageResourceNameMatcher.instance.matches(context.getResourceName()); } private Optional<AdImageId> retrieveImageId(@NonNull final OrgResourceNameContext context) { final OrgId adOrgId = context.getOrgId(); if (adOrgId.isAny()) { return Optional.empty(); } if (orgLogoResourceNameMatcher.matches(context.getResourceName())) { return Optional.ofNullable(retrieveLogoImageId(adOrgId)); } final String imageColumnName = OrgImageResourceNameMatcher.instance.getImageColumnName(context.getResourceName()).orElse(null); if (imageColumnName == null) { return Optional.empty(); } return orgsRepo.getOrgInfoById(adOrgId) .getImagesMap() .getImageId(imageColumnName); } @Nullable private AdImageId retrieveLogoImageId(@NonNull final OrgId adOrgId) { // // Get Logo from Organization's BPartner // task FRESH-356: get logo also from organization's bpartner if is set
final Properties ctx = Env.getCtx(); final I_AD_Org org = orgsRepo.getById(adOrgId); if (org != null) { final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(org); if (orgBPartner != null) { final AdImageId orgBPartnerLogoId = AdImageId.ofRepoIdOrNull(orgBPartner.getLogo_ID()); if (orgBPartnerLogoId != null) { return orgBPartnerLogoId; } } } // // Get Org Logo final OrgInfo orgInfo = orgsRepo.getOrgInfoById(adOrgId); final AdImageId logoImageId = orgInfo.getImagesMap().getLogoId().orElse(null); if (logoImageId != null) { return logoImageId; } // // Get Tenant level Logo final ClientId adClientId = orgInfo.getClientId(); final I_AD_ClientInfo clientInfo = clientsRepo.retrieveClientInfo(ctx, adClientId.getRepoId()); AdImageId clientLogoId = AdImageId.ofRepoIdOrNull(clientInfo.getLogoReport_ID()); if (clientLogoId == null) { clientLogoId = AdImageId.ofRepoIdOrNull(clientInfo.getLogo_ID()); } return clientLogoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\images\org\OrgImageLocalFileLoader.java
2
请完成以下Java代码
public HistoryManager getHistoryManager() { return getSession(HistoryManager.class); } // getters and setters ////////////////////////////////////////////////////// public TransactionContext getTransactionContext() { return transactionContext; } public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; }
public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public FlowableEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请在Spring Boot框架中完成以下Java代码
public void initFileClient() { FileUtil.mkdir(filePath); } @Override public String initTask(String filename) { // 分块文件存储路径 String tempFilePath = filePath + filename + UUID.randomUUID(); FileUtil.mkdir(tempFilePath); return tempFilePath; } @Override public String chunk(Chunk chunk, String uploadId) { String filename = chunk.getFilename(); String chunkFilePath = uploadId + "/" + chunk.getChunkNumber(); try (InputStream in = chunk.getFile().getInputStream(); OutputStream out = Files.newOutputStream(Paths.get(chunkFilePath))) { FileCopyUtils.copy(in, out); } catch (IOException e) { log.error("File [{}] upload failed", filename, e); throw new RuntimeException(e); } return chunkFilePath; } @Override public void merge(ChunkProcess chunkProcess) { String filename = chunkProcess.getFilename(); // 需要合并的文件所在的文件夹 File chunkFolder = new File(chunkProcess.getUploadId()); // 合并后的文件 File mergeFile = new File(filePath + filename); try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergeFile.toPath()))) { byte[] bytes = new byte[1024]; File[] fileArray = Optional.ofNullable(chunkFolder.listFiles()) .orElseThrow(() -> new IllegalArgumentException("Folder is empty"));
List<File> fileList = Arrays.stream(fileArray).sorted(Comparator.comparing(File::getName)).collect(Collectors.toList()); fileList.forEach(file -> { try (BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) { int len; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } } catch (IOException e) { log.info("File [{}] chunk [{}] write failed", filename, file.getName(), e); throw new RuntimeException(e); } }); } catch (IOException e) { log.info("File [{}] merge failed", filename, e); throw new RuntimeException(e); } finally { FileUtil.del(chunkProcess.getUploadId()); } } @Override public Resource getFile(String filename) { File file = new File(filePath + filename); return new FileSystemResource(file); } }
repos\springboot-demo-master\file\src\main\java\com\et\service\impl\LocalFileSystemClient.java
2
请完成以下Java代码
public void configure(String beanName, ClientRegionFactoryBean<?, ?> bean) { if (getRegionBeanName().test(beanName)) { bean.setCacheLoader(newRepositoryCacheLoader()); } } @Override @SuppressWarnings("unchecked") public void configure(String beanName, PeerRegionFactoryBean<?, ?> bean) { if (getRegionBeanName().test(beanName)) { bean.setCacheLoader(newRepositoryCacheLoader()); } }
/** * Constructs a new instance of {@link RepositoryCacheLoader} adapting the {@link CrudRepository} * as an instance of a {@link CacheLoader}. * * @return a new {@link RepositoryCacheLoader}. * @see org.springframework.geode.cache.RepositoryCacheLoader * @see org.springframework.data.repository.CrudRepository * @see org.apache.geode.cache.CacheLoader * @see #getRepository() */ @SuppressWarnings("rawtypes") protected RepositoryCacheLoader newRepositoryCacheLoader() { return new RepositoryCacheLoader<>(getRepository()); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryCacheLoaderRegionConfigurer.java
1
请完成以下Java代码
public int doStartTag() throws JspException { return super.doStartTag(); } @Override public int doEndTag() throws JspException { Object result = null; // determine the value by... if (this.property != null) { SecurityContext context = this.securityContextHolderStrategy.getContext(); if ((context == null) || !(context instanceof SecurityContext) || (context.getAuthentication() == null)) { return Tag.EVAL_PAGE; } Authentication auth = context.getAuthentication(); if (auth.getPrincipal() == null) { return Tag.EVAL_PAGE; } try { BeanWrapperImpl wrapper = new BeanWrapperImpl(auth); result = wrapper.getPropertyValue(this.property); } catch (BeansException ex) { throw new JspException(ex); } } if (this.var != null) { /* * Store the result, letting an IllegalArgumentException propagate back if the * scope is invalid (e.g., if an attempt is made to store something in the * session without any HttpSession existing). */ if (result != null) { this.pageContext.setAttribute(this.var, result, this.scope); } else { if (this.scopeSpecified) { this.pageContext.removeAttribute(this.var, this.scope); } else { this.pageContext.removeAttribute(this.var); } } } else { if (this.htmlEscape) { writeMessage(TextEscapeUtils.escapeEntities(String.valueOf(result))); } else { writeMessage(String.valueOf(result)); } } return EVAL_PAGE; } protected void writeMessage(String msg) throws JspException {
try { this.pageContext.getOut().write(String.valueOf(msg)); } catch (IOException ioe) { throw new JspException(ioe); } } /** * Set HTML escaping for this tag, as boolean value. */ public void setHtmlEscape(String htmlEscape) { this.htmlEscape = Boolean.parseBoolean(htmlEscape); } /** * Return the HTML escaping setting for this tag, or the default setting if not * overridden. */ protected boolean isHtmlEscape() { return this.htmlEscape; } }
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AuthenticationTag.java
1
请完成以下Java代码
public final ScriptExecutor createExecutor(final String scriptEngineType, final String scriptEngineName) { if (X_AD_Rule.RULETYPE_JSR223ScriptingAPIs.equals(scriptEngineType)) { final ScriptEngine scriptEngine = createScriptEngine_JSR223(scriptEngineName); return new ScriptExecutor(scriptEngine); } else { throw new AdempiereException("Script engine type not supported: " + scriptEngineType); } } public final ScriptExecutor createExecutor(final I_AD_Rule rule) { Check.assumeNotNull(rule, "Parameter rule is not null"); final String scriptEngineType = rule.getRuleType(); final String scriptEngineName = extractEngineNameFromRuleValue(rule.getValue()); return createExecutor(scriptEngineType, scriptEngineName); } public final Supplier<ScriptExecutor> createExecutorSupplier(final I_AD_Rule rule) { Check.assumeNotNull(rule, "Parameter rule is not null"); final String scriptEngineType = rule.getRuleType(); final String scriptEngineName = extractEngineNameFromRuleValue(rule.getValue()); return () -> createExecutor(scriptEngineType, scriptEngineName); } public final void assertScriptEngineExists(final I_AD_Rule rule) { try { final ScriptExecutor executor = createExecutor(rule); Check.assumeNotNull(executor, "executor is not null"); // shall not happen } catch (final Throwable e) { throw new AdempiereException("@WrongScriptValue@", e); } } public static final String extractEngineNameFromRuleValue(final String ruleValue) { if (ruleValue == null) { return null; } final int colonPosition = ruleValue.indexOf(":"); if (colonPosition < 0)
{ return null; } return ruleValue.substring(0, colonPosition); } public static final Optional<String> extractRuleValueFromClassname(final String classname) { if (classname == null || classname.isEmpty()) { return Optional.empty(); } if (!classname.toLowerCase().startsWith(SCRIPT_PREFIX)) { return Optional.empty(); } final String ruleValue = classname.substring(SCRIPT_PREFIX.length()).trim(); return Optional.of(ruleValue); } private final ScriptEngine createScriptEngine_JSR223(final String engineName) { Check.assumeNotEmpty(engineName, "engineName is not empty"); final ScriptEngineManager factory = getScriptEngineManager(); final ScriptEngine engine = factory.getEngineByName(engineName); if (engine == null) { throw new AdempiereException("Script engine was not found for engine name: '" + engineName + "'"); } return engine; } private final ScriptEngineManager getScriptEngineManager() { return scriptEngineManager.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptEngineFactory.java
1
请完成以下Java代码
protected void loadConfiguration(String location, @Nullable LogFile logFile) { Assert.notNull(location, "'location' must not be null"); try { Resource resource = ApplicationResourceLoader.get().getResource(location); String configuration = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); if (logFile != null) { configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(configuration.getBytes())); } catch (Exception ex) { throw new IllegalStateException("Could not initialize Java logging from " + location, ex); } } @Override public Set<LogLevel> getSupportedLogLevels() { return LEVELS.getSupported(); } @Override public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) { if (loggerName == null || ROOT_LOGGER_NAME.equals(loggerName)) { loggerName = ""; } Logger logger = Logger.getLogger(loggerName); if (logger != null) { this.configuredLoggers.add(logger); logger.setLevel(LEVELS.convertSystemToNative(level)); } } @Override public List<LoggerConfiguration> getLoggerConfigurations() { List<LoggerConfiguration> result = new ArrayList<>(); Enumeration<String> names = LogManager.getLogManager().getLoggerNames(); while (names.hasMoreElements()) { result.add(getLoggerConfiguration(names.nextElement())); } result.sort(CONFIGURATION_COMPARATOR); return Collections.unmodifiableList(result); } @Override public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) { Logger logger = Logger.getLogger(loggerName); if (logger == null) { return null; } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger)); String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME); Assert.state(effectiveLevel != null, "effectiveLevel must not be null"); return new LoggerConfiguration(name, level, effectiveLevel); } private Level getEffectiveLevel(Logger root) { Logger logger = root; while (logger.getLevel() == null) { logger = logger.getParent(); } return logger.getLevel();
} @Override public Runnable getShutdownHandler() { return () -> LogManager.getLogManager().reset(); } @Override public void cleanUp() { this.configuredLoggers.clear(); } /** * {@link LoggingSystemFactory} that returns {@link JavaLoggingSystem} if possible. */ @Order(Ordered.LOWEST_PRECEDENCE - 1024) public static class Factory implements LoggingSystemFactory { private static final boolean PRESENT = ClassUtils.isPresent("java.util.logging.LogManager", Factory.class.getClassLoader()); @Override public @Nullable LoggingSystem getLoggingSystem(ClassLoader classLoader) { if (PRESENT) { return new JavaLoggingSystem(classLoader); } return null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\JavaLoggingSystem.java
1
请完成以下Java代码
public Receive createReceive() { return receiveBuilder() .match(CountWords.class, r -> { try { log.info("Received CountWords message from " + getSender()); int numberOfWords = countWordsFromLine(r.line); getSender().tell(numberOfWords, getSelf()); } catch (Exception ex) { getSender().tell(new akka.actor.Status.Failure(ex), getSelf()); throw ex; } }) .build(); }
private int countWordsFromLine(String line) throws Exception { if (line == null) { throw new IllegalArgumentException("The text to process can't be null!"); } int numberOfWords = 0; String[] words = line.split(" "); for (String possibleWord : words) { if (possibleWord.trim().length() > 0) { numberOfWords++; } } return numberOfWords; } }
repos\tutorials-master\akka-modules\akka-actors\src\main\java\com\baeldung\akkaactors\WordCounterActor.java
1
请完成以下Java代码
private <T> IQueryBuilder<T> toQueryBuilder(final Class<T> clazz, final String trxName) { final String tableName = InterfaceWrapperHelper.getTableName(clazz); final POInfo poInfo = POInfo.getPOInfo(tableName); final IQueryBuilder<T> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(clazz, Env.getCtx(), trxName); queryBuilder.addEqualsFilter(COLUMNNAME_AD_Client_ID, this.clientId); queryBuilder.addEqualsFilter(COLUMNNAME_M_Product_ID, this.productId); queryBuilder.addEqualsFilter(COLUMNNAME_M_AttributeSetInstance_ID, attributeSetInstanceId); queryBuilder.addEqualsFilter(COLUMNNAME_C_AcctSchema_ID, this.acctSchemaId); // // Filter by organization, only if it's set and we are querying the M_Cost table. // Else, you can get no results. // e.g. querying PP_Order_Cost, have this.AD_Org_ID=0 but PP_Order_Costs are created using PP_Order's AD_Org_ID // see http://dewiki908/mediawiki/index.php/07741_Rate_Variance_%28103334042334%29. if (!this.orgId.isAny() || I_M_Cost.Table_Name.equals(tableName)) { queryBuilder.addEqualsFilter(COLUMNNAME_AD_Org_ID, orgId); }
if (this.costElementId != null) { queryBuilder.addEqualsFilter(COLUMNNAME_M_CostElement_ID, costElementId); } if (this.costTypeId != null && poInfo.hasColumnName(COLUMNNAME_M_CostType_ID)) { queryBuilder.addEqualsFilter(COLUMNNAME_M_CostType_ID, this.costTypeId); } return queryBuilder; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CopyPriceToStandard.java
1
请完成以下Java代码
private Set<String> getAuthoritySet() { if (roles == null) { Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities(); if (roleHierarchy != null) { userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities); } roles = AuthorityUtils.authorityListToSet(userAuthorities); } return roles; } @Override public boolean hasPermission(Object target, Object permission) { return permissionEvaluator.hasPermission(authentication, target, permission); } @Override public boolean hasPermission(Object targetId, String targetType, Object permission) { return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission); } public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) { this.permissionEvaluator = permissionEvaluator; } private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) { if (role == null) { return role; } if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) { return role; } if (role.startsWith(defaultRolePrefix)) { return role; } return defaultRolePrefix + role; }
@Override public Object getFilterObject() { return this.filterObject; } @Override public Object getReturnObject() { return this.returnObject; } @Override public Object getThis() { return this; } @Override public void setFilterObject(Object obj) { this.filterObject = obj; } @Override public void setReturnObject(Object obj) { this.returnObject = obj; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java
1
请完成以下Java代码
public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue) { if (jsonValue == null || JSONNullValue.isNull(jsonValue)) { values.remove(fieldName); } else { values.put(fieldName, jsonValue); } return this; } private Map<String, Object> getValues() { return values; } public LookupValue getFieldValueAsLookupValue(final String fieldName) { return LookupValue.cast(values.get(fieldName)); } public Builder addIncludedRow(final IViewRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow);
return this; } private List<IViewRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
1
请完成以下Java代码
public boolean isOrdered() { return true; } }, READY(2) { @Override public boolean isReady() { return true; } }, DELIVERED(0) { @Override public boolean isDelivered() { return true; } }; private int timeToDelivery; public boolean isOrdered() { return false; } public boolean isReady() { return false; } public boolean isDelivered() { return false; } public int getTimeToDelivery() { return timeToDelivery; } PizzaStatusEnum(int timeToDelivery) { this.timeToDelivery = timeToDelivery; } } public PizzaStatusEnum getStatus() { return status; }
public void setStatus(PizzaStatusEnum status) { this.status = status; } public boolean isDeliverable() { return this.status.isReady(); } public void printTimeToDeliver() { System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); } public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) { return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); } public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) { return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); } public void deliver() { if (isDeliverable()) { PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); this.setStatus(PizzaStatusEnum.DELIVERED); } } public int getDeliveryTimeInDays() { switch (status) { case ORDERED: return 5; case READY: return 2; case DELIVERED: return 0; } return 0; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Pizza.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringController { private static List<Car> carList = new ArrayList<Car>(); @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { return "redirect:/cars"; } static { carList.add(new Car("Honda", "Civic")); carList.add(new Car("Toyota", "Camry")); carList.add(new Car("Nissan", "Altima")); } @RequestMapping(value = "/cars", method = RequestMethod.GET) public String init(@ModelAttribute("model") ModelMap model) { model.addAttribute("carList", carList); return "index"; }
@RequestMapping(value = "/add", method = RequestMethod.POST) public String addCar(@ModelAttribute("car") Car car) { if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) { carList.add(car); } return "redirect:/cars"; } @RequestMapping(value = "/commons", method = RequestMethod.GET) public String showCommonsPage(Model model) { model.addAttribute("statuses", Arrays.asList("200 OK", "404 Not Found", "500 Internal Server Error")); model.addAttribute("lastChar", new LastCharMethod()); model.addAttribute("random", new Random()); model.addAttribute("statics", new DefaultObjectWrapperBuilder(new Version("2.3.28")).build().getStaticModels()); return "commons"; } }
repos\tutorials-master\spring-web-modules\spring-freemarker\src\main\java\com\baeldung\freemarker\controller\SpringController.java
2
请完成以下Java代码
public class MigrationPlanReportDto { protected List<MigrationInstructionValidationReportDto> instructionReports; protected Map<String, MigrationVariableValidationReportDto> variableReports; public List<MigrationInstructionValidationReportDto> getInstructionReports() { return instructionReports; } public void setInstructionReports(List<MigrationInstructionValidationReportDto> instructionReports) { this.instructionReports = instructionReports; } public Map<String, MigrationVariableValidationReportDto> getVariableReports() { return variableReports; } public void setVariableReports(Map<String, MigrationVariableValidationReportDto> variableReports) { this.variableReports = variableReports; }
public static MigrationPlanReportDto form(MigrationPlanValidationReport validationReport) { MigrationPlanReportDto dto = new MigrationPlanReportDto(); dto.setInstructionReports(MigrationInstructionValidationReportDto.from(validationReport.getInstructionReports())); dto.setVariableReports(MigrationVariableValidationReportDto.from(validationReport.getVariableReports())); return dto; } public static MigrationPlanReportDto emptyReport() { MigrationPlanReportDto dto = new MigrationPlanReportDto(); dto.setInstructionReports(Collections.emptyList()); dto.setVariableReports(Collections.emptyMap()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationPlanReportDto.java
1
请完成以下Java代码
protected String getId() { return id; } protected ProcessEngine getEngine() { return engine; } /** * Create the query we need for fetching the desired result. Setting * properties in the query like disableCustomObjectDeserialization() or * disableBinaryFetching() should be done in this method. */ protected abstract Query<T, U> baseQueryForBinaryVariable(); /**
* TODO change comment Create the query we need for fetching the desired * result. Setting properties in the query like * disableCustomObjectDeserialization() or disableBinaryFetching() should be * done in this method. * * @param deserializeObjectValue */ protected abstract Query<T, U> baseQueryForVariable(boolean deserializeObjectValue); protected abstract TypedValue transformQueryResultIntoTypedValue(U queryResult); protected abstract DTO transformToDto(U queryResult); protected abstract String getResourceNameForErrorMessage(); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\AbstractResourceProvider.java
1
请在Spring Boot框架中完成以下Java代码
public String doLoginGet(@PathVariable("username") String username,@PathVariable("password") String password) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password)); System.out.println("登录成功!"); return "redirect:/getIndex.html"; } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("登录失败!"); } return "redirect:/login"; } @PostMapping("/doLogin") public String doLogin(String username, String password) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password)); System.out.println("登录成功!"); return "redirect:/index"; } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("登录失败!"); } return "redirect:/login"; } @GetMapping("/hello") @ResponseBody public String hello() { return "hello"; } @GetMapping("/index") @ResponseBody public String index() { String wel = "hello ~ "; // Subject subject = SecurityUtils.getSubject(); // System.out.println(subject.hasRole("admin")); // String s = testService.vipPrint(); // wel = wel + s;
return wel; } @GetMapping("/login") @ResponseBody public String login() { return "please login!"; } @GetMapping("/vip") @ResponseBody public String vip() { return "hello vip"; } @GetMapping("/common") @ResponseBody public String common() { return "hello common"; } }
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\controller\LoginController.java
2
请完成以下Java代码
private void pushTimeRing(int ringSecond, int jobId){ // push async ring List<Integer> ringItemData = ringData.get(ringSecond); if (ringItemData == null) { ringItemData = new ArrayList<Integer>(); ringData.put(ringSecond, ringItemData); } ringItemData.add(jobId); logger.debug(">>>>>>>>>>> xxl-job, schedule push time-ring : " + ringSecond + " = " + Arrays.asList(ringItemData) ); } public void toStop(){ // 1、stop schedule scheduleThreadToStop = true; try { TimeUnit.SECONDS.sleep(1); // wait } catch (InterruptedException e) { logger.error(e.getMessage(), e); } if (scheduleThread.getState() != Thread.State.TERMINATED){ // interrupt and wait scheduleThread.interrupt(); try { scheduleThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } // if has ring data boolean hasRingData = false; if (!ringData.isEmpty()) { for (int second : ringData.keySet()) { List<Integer> tmpData = ringData.get(second); if (tmpData!=null && tmpData.size()>0) { hasRingData = true; break; } } } if (hasRingData) { try { TimeUnit.SECONDS.sleep(8); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } // stop ring (wait job-in-memory stop)
ringThreadToStop = true; try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } if (ringThread.getState() != Thread.State.TERMINATED){ // interrupt and wait ringThread.interrupt(); try { ringThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } logger.info(">>>>>>>>>>> xxl-job, JobScheduleHelper stop"); } // ---------------------- tools ---------------------- public static Date generateNextValidTime(XxlJobInfo jobInfo, Date fromTime) throws Exception { ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null); if (ScheduleTypeEnum.CRON == scheduleTypeEnum) { Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime); return nextValidTime; } else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) { return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf())*1000 ); } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobScheduleHelper.java
1
请在Spring Boot框架中完成以下Java代码
public Date getTime() { return createTime; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getScopeId() { return scopeId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getMetaInfo() { return metaInfo; } @Override public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } @Override public ByteArrayRef getByteArrayRef() { return byteArrayRef; } // common methods ////////////////////////////////////////////////////////// protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
private FutureCallback<ValidationResult> on(Consumer<Void> success, Consumer<Throwable> failure) { return new FutureCallback<ValidationResult>() { @Override public void onSuccess(@Nullable ValidationResult result) { ValidationResultCode resultCode = result.getResultCode(); if (resultCode == ValidationResultCode.OK) { success.accept(null); } else { onFailure(ValidationCallback.getException(result)); } } @Override public void onFailure(Throwable t) { failure.accept(t); } }; } public static Aggregation getAggregation(String agg) { return StringUtils.isEmpty(agg) ? DEFAULT_AGGREGATION : Aggregation.valueOf(agg); } private int getLimit(int limit) {
return limit == 0 ? DEFAULT_LIMIT : limit; } private DefaultTenantProfileConfiguration getTenantProfileConfiguration(WebSocketSessionRef sessionRef) { return Optional.ofNullable(tenantProfileCache.get(sessionRef.getSecurityCtx().getTenantId())) .map(TenantProfile::getDefaultProfileConfiguration).orElse(null); } public static <C extends WsCmd> WsCmdHandler<C> newCmdHandler(BiConsumer<WebSocketSessionRef, C> handler) { return new WsCmdHandler<>(handler); } @RequiredArgsConstructor @Getter @SuppressWarnings("unchecked") public static class WsCmdHandler<C extends WsCmd> { protected final BiConsumer<WebSocketSessionRef, C> handler; public void handle(WebSocketSessionRef sessionRef, WsCmd cmd) { handler.accept(sessionRef, (C) cmd); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\DefaultWebSocketService.java
2
请完成以下Java代码
public class DmnEngineImpl implements DmnEngine { private static final Logger LOGGER = LoggerFactory.getLogger(DmnEngineImpl.class); protected String name; protected DmnManagementService dmnManagementService; protected DmnRepositoryService dmnRepositoryService; protected DmnDecisionService dmnDecisionService; protected DmnHistoryService dmnHistoryService; protected DmnEngineConfiguration dmnEngineConfiguration; public DmnEngineImpl(DmnEngineConfiguration dmnEngineConfiguration) { this.dmnEngineConfiguration = dmnEngineConfiguration; this.name = dmnEngineConfiguration.getEngineName(); this.dmnManagementService = dmnEngineConfiguration.getDmnManagementService(); this.dmnRepositoryService = dmnEngineConfiguration.getDmnRepositoryService(); this.dmnDecisionService = dmnEngineConfiguration.getDmnDecisionService(); this.dmnHistoryService = dmnEngineConfiguration.getDmnHistoryService(); if (dmnEngineConfiguration.getSchemaManagementCmd() != null) { dmnEngineConfiguration.getCommandExecutor().execute(dmnEngineConfiguration.getSchemaCommandConfig(), dmnEngineConfiguration.getSchemaManagementCmd()); } if (name == null) { LOGGER.info("default flowable DmnEngine created"); } else { LOGGER.info("DmnEngine {} created", name); } DmnEngines.registerDmnEngine(this); if (dmnEngineConfiguration.getEngineLifecycleListeners() != null) { for (EngineLifecycleListener engineLifecycleListener : dmnEngineConfiguration.getEngineLifecycleListeners()) { engineLifecycleListener.onEngineBuilt(this); } } } @Override public void close() { DmnEngines.unregister(this); dmnEngineConfiguration.close(); if (dmnEngineConfiguration.getEngineLifecycleListeners() != null) { for (EngineLifecycleListener engineLifecycleListener : dmnEngineConfiguration.getEngineLifecycleListeners()) { engineLifecycleListener.onEngineClosed(this); } } } // getters and setters // ////////////////////////////////////////////////////// @Override public String getName() {
return name; } @Override public DmnManagementService getDmnManagementService() { return dmnManagementService; } @Override public DmnRepositoryService getDmnRepositoryService() { return dmnRepositoryService; } @Override public DmnDecisionService getDmnDecisionService() { return dmnDecisionService; } @Override public DmnHistoryService getDmnHistoryService() { return dmnHistoryService; } @Override public DmnEngineConfiguration getDmnEngineConfiguration() { return dmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnEngineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoicePayScheduleService { @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); @NonNull private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); @NonNull private final InvoicePayScheduleRepository invoicePayScheduleRepository; @NonNull private final OrderPayScheduleService orderPayScheduleService; @NonNull private final PaymentTermService paymentTermService; public Optional<InvoicePaySchedule> getByInvoiceId(@NonNull final InvoiceId invoiceId) { return invoicePayScheduleRepository.getByInvoiceId(invoiceId); } public void createInvoicePaySchedules(final I_C_Invoice invoice) { InvoicePayScheduleCreateCommand.builder() .invoicePayScheduleRepository(invoicePayScheduleRepository) .orderPayScheduleService(orderPayScheduleService) .paymentTermService(paymentTermService) .invoiceRecord(invoice) .build() .execute(); } public void validateInvoiceBeforeCommit(@NonNull final InvoiceId invoiceId) { trxManager.accumulateAndProcessBeforeCommit( "InvoicePayScheduleService.validateInvoiceBeforeCommit", Collections.singleton(invoiceId), invoiceIds -> validateInvoicesNow(ImmutableSet.copyOf(invoiceIds))
); } private void validateInvoicesNow(final Set<InvoiceId> invoiceIds) { if (invoiceIds.isEmpty()) {return;} final ImmutableMap<InvoiceId, I_C_Invoice> invoicesById = Maps.uniqueIndex( invoiceBL.getByIds(invoiceIds), invoice -> InvoiceId.ofRepoId(invoice.getC_Invoice_ID()) ); invoicePayScheduleRepository.updateByIds(invoicesById.keySet(), invoicePaySchedule -> { final I_C_Invoice invoice = invoicesById.get(invoicePaySchedule.getInvoiceId()); final Money grandTotal = invoiceBL.extractGrandTotal(invoice).toMoney(); boolean isValid = invoicePaySchedule.validate(grandTotal); invoice.setIsPayScheduleValid(isValid); invoiceBL.save(invoice); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\service\InvoicePayScheduleService.java
2
请完成以下Java代码
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 Overtime Amount. @param OvertimeAmt Hourly Overtime Rate */ public void setOvertimeAmt (BigDecimal OvertimeAmt) { set_Value (COLUMNNAME_OvertimeAmt, OvertimeAmt); } /** Get Overtime Amount. @return Hourly Overtime Rate */ public BigDecimal getOvertimeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Overtime Cost. @param OvertimeCost Hourly Overtime Cost */ public void setOvertimeCost (BigDecimal OvertimeCost) { set_Value (COLUMNNAME_OvertimeCost, OvertimeCost); } /** Get Overtime Cost. @return Hourly Overtime Cost */ public BigDecimal getOvertimeCost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost); if (bd == null) return Env.ZERO; return bd; } /** RemunerationType AD_Reference_ID=346 */ public static final int REMUNERATIONTYPE_AD_Reference_ID=346; /** Hourly = H */ public static final String REMUNERATIONTYPE_Hourly = "H"; /** Daily = D */ public static final String REMUNERATIONTYPE_Daily = "D"; /** Weekly = W */ public static final String REMUNERATIONTYPE_Weekly = "W"; /** Monthly = M */ public static final String REMUNERATIONTYPE_Monthly = "M"; /** Twice Monthly = T */ public static final String REMUNERATIONTYPE_TwiceMonthly = "T";
/** Bi-Weekly = B */ public static final String REMUNERATIONTYPE_Bi_Weekly = "B"; /** Set Remuneration Type. @param RemunerationType Type of Remuneration */ public void setRemunerationType (String RemunerationType) { set_Value (COLUMNNAME_RemunerationType, RemunerationType); } /** Get Remuneration Type. @return Type of Remuneration */ public String getRemunerationType () { return (String)get_Value(COLUMNNAME_RemunerationType); } /** Set Standard Hours. @param StandardHours Standard Work Hours based on Remuneration Type */ public void setStandardHours (int StandardHours) { set_Value (COLUMNNAME_StandardHours, Integer.valueOf(StandardHours)); } /** Get Standard Hours. @return Standard Work Hours based on Remuneration Type */ public int getStandardHours () { Integer ii = (Integer)get_Value(COLUMNNAME_StandardHours); 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_Remuneration.java
1
请完成以下Java代码
public class CmsSubjectProductRelation implements Serializable { private Long id; private Long subjectId; private Long productId; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getSubjectId() { return subjectId; } public void setSubjectId(Long subjectId) { this.subjectId = subjectId; }
public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } @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(", subjectId=").append(subjectId); sb.append(", productId=").append(productId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectProductRelation.java
1
请完成以下Java代码
private void exportIfAlreadyExportedOnce(@NonNull final I_M_HU_Trace huTrace) { final ExportHUCandidate exportHUCandidate = ExportHUCandidate.builder() .huId(HuId.ofRepoId(huTrace.getM_HU_ID())) .linkedSourceVHuId(HuId.ofRepoIdOrNull(huTrace.getVHU_Source_ID())) .build(); enqueueHUExport(exportHUCandidate); } private void directlyExportToAllMatchingConfigs(@NonNull final I_M_HU_Trace huTrace) { final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum); for (final ExternalSystemParentConfig config : configs) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig()); if (!shouldExportToExternalSystem(grsConfig, HUTraceType.ofCode(huTrace.getHUTraceType()))) { continue; } final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParent(HuId.ofRepoId(huTrace.getM_HU_ID())); final TableRecordReference topLevelHURecordRef = TableRecordReference.of(topLevelHU); exportToExternalSystem(grsConfig.getId(), topLevelHURecordRef, null); } } private boolean shouldExportDirectly(@NonNull final I_M_HU_Trace huTrace) { final HUTraceType huTraceType = HUTraceType.ofCode(huTrace.getHUTraceType()); final boolean purchasedOrProduced = huTraceType.equals(MATERIAL_RECEIPT) || huTraceType.equals(PRODUCTION_RECEIPT); final boolean docCompleted = DocStatus.ofCodeOptional(huTrace.getDocStatus()) .map(DocStatus::isCompleted)
.orElse(false); return purchasedOrProduced && docCompleted; } private boolean shouldExportIfAlreadyExportedOnce(@NonNull final HUTraceType huTraceType) { return huTraceType.equals(TRANSFORM_LOAD) || huTraceType.equals(TRANSFORM_PARENT); } private boolean shouldExportToExternalSystem(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig, @NonNull final HUTraceType huTraceType) { switch (huTraceType) { case MATERIAL_RECEIPT: return grsSignumConfig.isSyncHUsOnMaterialReceipt(); case PRODUCTION_RECEIPT: return grsSignumConfig.isSyncHUsOnProductionReceipt(); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportHUToGRSService.java
1
请完成以下Java代码
public final String getModelTableName() { return modelTableName; } @Override protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { engine.addModelChange(modelTableName, this); } @Override public void onModelChange(final Object model, final ModelChangeType changeType) throws Exception { if (!changeType.isAfter()) { return; } // // Model was created on changed if (changeType.isNewOrChange()) { createOrUpdateAllocation(model); } // // Model was deleted else if (changeType.isDelete()) { deleteAllocation(model); } } private void createOrUpdateAllocation(final Object model) { final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable);
if (deliveryDayAlloc == null) { // Case: no delivery day allocation was found and no delivery day on which we could allocate was found return; } deliveryDayBL.getDeliveryDayHandlers() .updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable); InterfaceWrapperHelper.save(deliveryDayAlloc); } private void deleteAllocation(Object model) { final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayDAO.retrieveDeliveryDayAllocForModel(context, deliveryDayAllocable); if (deliveryDayAlloc != null) { InterfaceWrapperHelper.delete(deliveryDayAlloc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\DeliveryDayAllocableInterceptor.java
1
请完成以下Java代码
public synchronized void start() { if (!started) { started = true; cleanerTask = schedExecutor.scheduleAtFixedRate(new TbInMemoryRegistrationStore.Cleaner(), cleanPeriod, cleanPeriod, TimeUnit.SECONDS); } } /** * Stop the underlying cleanup of the registrations. */ @Override public synchronized void stop() { if (started) { started = false; if (cleanerTask != null) { cleanerTask.cancel(false); cleanerTask = null; } } } /** * Destroy "cleanup" scheduler. */ @Override public synchronized void destroy() { started = false; schedExecutor.shutdownNow(); try { schedExecutor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("Destroying InMemoryRegistrationStore was interrupted.", e); } } private class Cleaner implements Runnable { @Override public void run() { try { Collection<Registration> allRegs = new ArrayList<>(); try { lock.readLock().lock(); allRegs.addAll(regsByEp.values()); } finally {
lock.readLock().unlock(); } for (Registration reg : allRegs) { if (!reg.isAlive()) { // force de-registration Deregistration removedRegistration = removeRegistration(reg.getId()); expirationListener.registrationExpired(removedRegistration.getRegistration(), removedRegistration.getObservations()); } } } catch (Exception e) { log.warn("Unexpected Exception while registration cleaning", e); } } } // boolean remove(Object key, Object value) exist only since java8 // So this method is here only while we want to support java 7 protected <K, V> boolean removeFromMap(Map<K, V> map, K key, V value) { if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.remove(key); return true; } else return false; } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemoryRegistrationStore.java
1
请完成以下Java代码
public String getClientInfo() { return getCurrentInstance().getClientInfo(); } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}. */ @Deprecated @Override public void hideBusyDialog() { // nothing } @Override public void showWindow(final Object model) { getCurrentInstance().showWindow(model); } @Override public void executeLongOperation(final Object component, final Runnable runnable) { getCurrentInstance().executeLongOperation(component, runnable); } @Override public IClientUIInvoker invoke() {
return getCurrentInstance().invoke(); } @Override public IClientUIAsyncInvoker invokeAsync() { return getCurrentInstance().invokeAsync(); } @Override public void showURL(String url) { getCurrentInstance().showURL(url); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java
1
请完成以下Java代码
public static void fillTypes( Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) { fillJsonTypes(convertersToBpmnMap); fillBpmnTypes(convertersToJsonMap); } public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) { convertersToBpmnMap.put(STENCIL_TASK_DECISION, DecisionTaskJsonConverter.class); } public static void fillBpmnTypes( Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap ) {} protected String getStencilId(BaseElement baseElement) { return STENCIL_TASK_DECISION; } protected FlowElement convertJsonToElement( JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap ) { ServiceTask serviceTask = new ServiceTask(); serviceTask.setType(ServiceTask.DMN_TASK); JsonNode decisionTableReferenceNode = getProperty(PROPERTY_DECISIONTABLE_REFERENCE, elementNode); if ( decisionTableReferenceNode != null && decisionTableReferenceNode.has("id") && !(decisionTableReferenceNode.get("id").isNull()) ) { String decisionTableId = decisionTableReferenceNode.get("id").asText(); if (decisionTableMap != null) { String decisionTableKey = decisionTableMap.get(decisionTableId); FieldExtension decisionTableKeyField = new FieldExtension(); decisionTableKeyField.setFieldName(PROPERTY_DECISIONTABLE_REFERENCE_KEY); decisionTableKeyField.setStringValue(decisionTableKey); serviceTask.getFieldExtensions().add(decisionTableKeyField);
} } return serviceTask; } @Override protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {} @Override public void setDecisionTableMap(Map<String, String> decisionTableMap) { this.decisionTableMap = decisionTableMap; } protected void addExtensionAttributeToExtension(ExtensionElement element, String attributeName, String value) { ExtensionAttribute extensionAttribute = new ExtensionAttribute(NAMESPACE, attributeName); extensionAttribute.setNamespacePrefix("modeler"); extensionAttribute.setValue(value); element.addAttribute(extensionAttribute); } }
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\DecisionTaskJsonConverter.java
1
请完成以下Java代码
public String getId() { return activit5Comment.getId(); } @Override public String getUserId() { return activit5Comment.getUserId(); } @Override public Date getTime() { return activit5Comment.getTime(); } @Override public String getTaskId() { return activit5Comment.getTaskId(); } @Override public String getProcessInstanceId() { return activit5Comment.getProcessInstanceId(); } @Override public String getType() { return activit5Comment.getType(); } @Override public String getFullMessage() { return activit5Comment.getFullMessage(); } public org.activiti.engine.task.Comment getRawObject() { return activit5Comment; }
@Override public void setUserId(String userId) { ((CommentEntity) activit5Comment).setUserId(userId); } @Override public void setTime(Date time) { ((CommentEntity) activit5Comment).setTime(time); } @Override public void setTaskId(String taskId) { ((CommentEntity) activit5Comment).setTaskId(taskId); } @Override public void setProcessInstanceId(String processInstanceId) { ((CommentEntity) activit5Comment).setProcessInstanceId(processInstanceId); } @Override public void setType(String type) { ((CommentEntity) activit5Comment).setType(type); } @Override public void setFullMessage(String fullMessage) { ((CommentEntity) activit5Comment).setFullMessage(fullMessage); } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5CommentWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public void logFormAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logFormAccess(roleId, id, access); } @Override public void logProcessAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logProcessAccess(roleId, id, access); } @Override public void logTaskAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logTaskAccess(roleId, id, access);
} @Override public void logWorkflowAccess(RoleId roleId, int id, Boolean access) { MRolePermRequest.logWorkflowAccess(roleId, id, access); } @Override public void logDocActionAccess(RoleId roleId, DocTypeId docTypeId, String docAction, Boolean access) { MRolePermRequest.logDocActionAccess(roleId, docTypeId, docAction, access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\service\impl\RolePermLoggingBL.java
2
请在Spring Boot框架中完成以下Java代码
public void setResourceLocation(String resourceLocation) { this.userDetails.setResourceLocation(resourceLocation); } /** * Sets a Resource that is a Properties file in the format defined in * {@link UserDetailsResourceFactoryBean}. * @param resource the Resource to use */ public void setResource(Resource resource) { this.userDetails.setResource(resource); } /** * Create a ReactiveUserDetailsServiceResourceFactoryBean with the location of a * Resource that is a Properties file in the format defined in * {@link UserDetailsResourceFactoryBean}. * @param resourceLocation the location of the properties file that contains the users * (i.e. "classpath:users.properties") * @return the ReactiveUserDetailsServiceResourceFactoryBean */ public static ReactiveUserDetailsServiceResourceFactoryBean fromResourceLocation(String resourceLocation) { ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean(); result.setResourceLocation(resourceLocation); return result; } /** * Create a ReactiveUserDetailsServiceResourceFactoryBean with a Resource that is a * Properties file in the format defined in {@link UserDetailsResourceFactoryBean}. * @param propertiesResource the Resource that is a properties file that contains the * users * @return the ReactiveUserDetailsServiceResourceFactoryBean */ public static ReactiveUserDetailsServiceResourceFactoryBean fromResource(Resource propertiesResource) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean(); result.setResource(propertiesResource); return result; } /** * Create a ReactiveUserDetailsServiceResourceFactoryBean with a String that is in the * format defined in {@link UserDetailsResourceFactoryBean}. * @param users the users in the format defined in * {@link UserDetailsResourceFactoryBean} * @return the ReactiveUserDetailsServiceResourceFactoryBean */ public static ReactiveUserDetailsServiceResourceFactoryBean fromString(String users) { ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean(); result.setResource(new InMemoryResource(users)); return result; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\ReactiveUserDetailsServiceResourceFactoryBean.java
2
请完成以下Java代码
public DecisionServiceExecutionAuditContainer executeDecisionServiceWithAuditTrail() { return decisionService.executeDecisionServiceWithAuditTrail(this); } public String getDecisionKey() { return decisionKey; } public String getParentDeploymentId() { return parentDeploymentId; } public String getInstanceId() { return instanceId; } public String getExecutionId() { return executionId; } public String getActivityId() { return activityId; } public String getScopeType() { return scopeType; } public String getTenantId() { return tenantId; } public boolean isFallbackToDefaultTenant() { return this.fallbackToDefaultTenant; } public Map<String, Object> getVariables() { return variables;
} @Override public ExecuteDecisionContext buildExecuteDecisionContext() { ExecuteDecisionContext executeDecisionContext = new ExecuteDecisionContext(); executeDecisionContext.setDecisionKey(decisionKey); executeDecisionContext.setParentDeploymentId(parentDeploymentId); executeDecisionContext.setInstanceId(instanceId); executeDecisionContext.setExecutionId(executionId); executeDecisionContext.setActivityId(activityId); executeDecisionContext.setScopeType(scopeType); executeDecisionContext.setVariables(variables); executeDecisionContext.setTenantId(tenantId); executeDecisionContext.setFallbackToDefaultTenant(fallbackToDefaultTenant); executeDecisionContext.setDisableHistory(disableHistory); return executeDecisionContext; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\ExecuteDecisionBuilderImpl.java
1
请完成以下Java代码
public EventDefinitionQuery orderByDeploymentId() { return orderBy(EventDefinitionQueryProperty.DEPLOYMENT_ID); } @Override public EventDefinitionQuery orderByEventDefinitionKey() { return orderBy(EventDefinitionQueryProperty.KEY); } @Override public EventDefinitionQuery orderByEventDefinitionCategory() { return orderBy(EventDefinitionQueryProperty.CATEGORY); } @Override public EventDefinitionQuery orderByEventDefinitionId() { return orderBy(EventDefinitionQueryProperty.ID); } @Override public EventDefinitionQuery orderByEventDefinitionName() { return orderBy(EventDefinitionQueryProperty.NAME); } @Override public EventDefinitionQuery orderByTenantId() { return orderBy(EventDefinitionQueryProperty.TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionCountByQueryCriteria(this); } @Override public List<EventDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getParentDeploymentId() { return parentDeploymentId; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; }
public String getNameLike() { return nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getKeyLikeIgnoreCase() { return keyLikeIgnoreCase; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDefinitionQueryImpl.java
1
请完成以下Java代码
public String[] getFileExtensions() { return new String[] { "properties", "xml" }; } @Override public List<PropertySource<?>> load(String name, Resource resource) throws IOException { List<Map<String, ?>> properties = loadProperties(resource); if (properties.isEmpty()) { return Collections.emptyList(); } List<PropertySource<?>> propertySources = new ArrayList<>(properties.size()); for (int i = 0; i < properties.size(); i++) { String documentNumber = (properties.size() != 1) ? " (document #" + i + ")" : ""; propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, Collections.unmodifiableMap(properties.get(i)), true)); } return propertySources; }
@SuppressWarnings({ "unchecked", "rawtypes" }) private List<Map<String, ?>> loadProperties(Resource resource) throws IOException { String filename = resource.getFilename(); List<Map<String, ?>> result = new ArrayList<>(); if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { result.add((Map) PropertiesLoaderUtils.loadProperties(resource)); } else { List<Document> documents = new OriginTrackedPropertiesLoader(resource).load(); documents.forEach((document) -> result.add(document.asMap())); } return result; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\PropertiesPropertySourceLoader.java
1
请完成以下Java代码
public abstract class AbstractPasswordEncoder extends AbstractValidatingPasswordEncoder { private final BytesKeyGenerator saltGenerator; protected AbstractPasswordEncoder() { this.saltGenerator = KeyGenerators.secureRandom(); } @Override protected String encodeNonNullPassword(String rawPassword) { byte[] salt = this.saltGenerator.generateKey(); byte[] encoded = encodeAndConcatenate(rawPassword, salt); return String.valueOf(Hex.encode(encoded)); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { byte[] digested = Hex.decode(encodedPassword);
byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return matchesNonNull(digested, encodeAndConcatenate(rawPassword, salt)); } protected abstract byte[] encodedNonNullPassword(CharSequence rawPassword, byte[] salt); protected byte[] encodeAndConcatenate(CharSequence rawPassword, byte[] salt) { return EncodingUtils.concatenate(salt, encodedNonNullPassword(rawPassword, salt)); } /** * Constant time comparison to prevent against timing attacks. */ protected static boolean matchesNonNull(byte[] expected, byte[] actual) { return MessageDigest.isEqual(expected, actual); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\AbstractPasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
final class TranslationHelper { private static final Joiner languageTagJoiner = Joiner.on('_').skipNulls(); public static <T extends AbstractTranslationEntity<?>> T getTranslation(final Map<String, T> records, final Locale locale) { if(records == null || records.isEmpty()) { return null; } if(locale == null) { return null; } final String language = locale.getLanguage(); final String country = locale.getCountry(); final String variant = locale.getVariant(); if (!Strings.isNullOrEmpty(variant)) { final String languageTag = languageTagJoiner.join(language, country, variant); final T recordTrl = records.get(languageTag); if(recordTrl != null) { return recordTrl; } } if (!Strings.isNullOrEmpty(country)) { final String languageTag = languageTagJoiner.join(language, country);
final T recordTrl = records.get(languageTag); if(recordTrl != null) { return recordTrl; } } if (!Strings.isNullOrEmpty(language)) { final String languageTag = language; final T recordTrl = records.get(languageTag); if(recordTrl != null) { return recordTrl; } } return null; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\TranslationHelper.java
2
请完成以下Java代码
public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyProcessed (final @Nullable BigDecimal QtyProcessed) { set_Value (COLUMNNAME_QtyProcessed, QtyProcessed); } @Override public BigDecimal getQtyProcessed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyProcessed_OnDate (final @Nullable BigDecimal QtyProcessed_OnDate) { set_Value (COLUMNNAME_QtyProcessed_OnDate, QtyProcessed_OnDate); } @Override public BigDecimal getQtyProcessed_OnDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed_OnDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToProcess (final @Nullable BigDecimal QtyToProcess) { set_Value (COLUMNNAME_QtyToProcess, QtyToProcess); } @Override public BigDecimal getQtyToProcess() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) {
if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation); } @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_Value (COLUMNNAME_WorkStation_ID, null); else set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Candidate.java
1
请完成以下Java代码
public static CostingLevel ofNullableCode(final String code) { if (code == null) { return null; } return ofCode(code); } public static CostingLevel ofCode(final String code) { final CostingLevel type = code2type.get(code); if (type == null) { throw new NoSuchElementException("No " + CostingLevel.class + " found for code=" + code); } return type; } private static final ImmutableMap<String, CostingLevel> code2type = Stream.of(values()) .collect(GuavaCollectors.toImmutableMapByKey(CostingLevel::getCode)); public ClientId effectiveValue(@NonNull final ClientId clientId) { if (clientId.isSystem()) { throw new AdempiereException("Invalid: " + clientId); } return clientId; } public OrgId effectiveValue(@NonNull final OrgId orgId) { return effectiveValueOr(orgId, OrgId.ANY); } public OrgId effectiveValueOrNull(@NonNull final OrgId orgId) { return effectiveValueOr(orgId, null); } private OrgId effectiveValueOr(@NonNull final OrgId orgId, final OrgId nullValue) { if (this == Client) { return nullValue; } else if (this == Organization) { if (orgId.isAny()) {
throw new AdempiereException("Regular organization expected when costing level is Organization"); } return orgId; } else if (this == BatchLot) { return nullValue; } else { throw new AdempiereException("Unknown costingLevel: " + this); } } public AttributeSetInstanceId effectiveValue(@NonNull final AttributeSetInstanceId asiId) { return effectiveValueOr(asiId, AttributeSetInstanceId.NONE); } public AttributeSetInstanceId effectiveValueOrNull(@NonNull final AttributeSetInstanceId asiId) { return effectiveValueOr(asiId, null); } private AttributeSetInstanceId effectiveValueOr(@NonNull final AttributeSetInstanceId asiId, final AttributeSetInstanceId nullValue) { if (this == Client) { return nullValue; } else if (this == Organization) { return nullValue; } else if (this == BatchLot) { if (asiId.isNone()) { throw new AdempiereException("Regular ASI expected when costing level is Batch/Lot"); } return asiId; } else { throw new AdempiereException("Unknown costingLevel: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\costing\CostingLevel.java
1
请完成以下Java代码
private void postConstruct() { getEventBus().subscribeOn(SumUpTransactionStatusChangedEvent.class, this::handleEvent); } public static IAutoCloseable temporaryForceSendingChangeEventsIf(final boolean condition) { return forceSendChangeEventsThreadLocal.temporarySetToTrueIf(condition); } private static boolean isForceSendingChangeEvents() { return forceSendChangeEventsThreadLocal.isTrue(); } private IEventBus getEventBus() {return eventBusFactory.getEventBus(EVENTS_TOPIC);} private void handleEvent(@NonNull final SumUpTransactionStatusChangedEvent event) { fireLocalListeners(event); } private void fireLocalListeners(final @NonNull SumUpTransactionStatusChangedEvent event) { try (final IAutoCloseable ignored = Env.switchContext(newTemporaryCtx(event))) { statusChangedListeners.forEach(listener -> listener.onStatusChanged(event)); } } private static Properties newTemporaryCtx(final @NonNull SumUpTransactionStatusChangedEvent event) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, event.getClientId()); Env.setOrgId(ctx, event.getOrgId()); return ctx; } private void fireLocalAndRemoteListenersAfterTrxCommit(final @NonNull SumUpTransactionStatusChangedEvent event) { trxManager.accumulateAndProcessAfterCommit( SumUpEventsDispatcher.class.getSimpleName(), ImmutableList.of(event), this::fireLocalAndRemoteListenersNow); } private void fireLocalAndRemoteListenersNow(@NonNull final List<SumUpTransactionStatusChangedEvent> events) { final IEventBus eventBus = getEventBus(); // NOTE: we don't have to fireLocalListeners
// because we assume we will also get back this event and then we will handle it events.forEach(eventBus::enqueueObject); } public void fireNewTransaction(@NonNull final SumUpTransaction trx) { fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofNewTransaction(trx)); } public void fireStatusChangedIfNeeded( @NonNull final SumUpTransaction trx, @NonNull final SumUpTransaction trxPrev) { if (!isForceSendingChangeEvents() && hasChanges(trx, trxPrev)) { return; } fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofChangedTransaction(trx, trxPrev)); } private static boolean hasChanges(final @NonNull SumUpTransaction trx, final @NonNull SumUpTransaction trxPrev) { return SumUpTransactionStatus.equals(trx.getStatus(), trxPrev.getStatus()) && trx.isRefunded() == trxPrev.isRefunded(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpEventsDispatcher.java
1
请完成以下Java代码
private static AvailableForSalesMergeResult computeAvailableForSalesMergeResult( @NonNull final ImmutableMap<AvailableForSalesId, I_MD_Available_For_Sales> availableForSalesIds2Records, @NonNull final ImmutableList<AvailableForSalesResult> availableForSalesResults) { final ImmutableMap.Builder<AvailableForSalesId, AvailableForSalesResult> recordId2ResultCollector = ImmutableMap.builder(); final ImmutableList.Builder<AvailableForSalesResult> resultsToInsertCollector = ImmutableList.builder(); for (final AvailableForSalesResult availableForSalesResult : availableForSalesResults) { AvailableForSalesId idForCurrentResult = null; final Iterator<AvailableForSalesId> availableForSalesIdIterator = availableForSalesIds2Records.keySet().iterator(); while (availableForSalesIdIterator.hasNext() && idForCurrentResult == null) { final AvailableForSalesId availableForSalesId = availableForSalesIdIterator.next(); final I_MD_Available_For_Sales availableForSalesRecord = availableForSalesIds2Records.get(availableForSalesId); if (availableForSalesRecord.getStorageAttributesKey().equals(availableForSalesResult.getStorageAttributesKey().getAsString()) && availableForSalesRecord.getM_Warehouse_ID() == availableForSalesResult.getWarehouseId().getRepoId()) { idForCurrentResult = AvailableForSalesId.ofRepoId(availableForSalesRecord.getMD_Available_For_Sales_ID()); } } if (idForCurrentResult == null) { resultsToInsertCollector.add(availableForSalesResult); } else { recordId2ResultCollector.put(idForCurrentResult, availableForSalesResult); } } final Map<AvailableForSalesId, AvailableForSalesResult> recordId2Result = recordId2ResultCollector.build(); final List<I_MD_Available_For_Sales> recordsToBeDeleted = availableForSalesIds2Records .entrySet()
.stream() .filter(id2Record -> !recordId2Result.containsKey(id2Record.getKey())) .map(Map.Entry::getValue) .collect(ImmutableList.toImmutableList()); return AvailableForSalesMergeResult.builder() .recordId2Result(recordId2Result) .recordsToDelete(recordsToBeDeleted) .resultsToInsert(resultsToInsertCollector.build()) .build(); } @Value @Builder private static class AvailableForSalesMergeResult { @NonNull Map<AvailableForSalesId, AvailableForSalesResult> recordId2Result; @NonNull List<AvailableForSalesResult> resultsToInsert; @NonNull List<I_MD_Available_For_Sales> recordsToDelete; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesService.java
1
请完成以下Java代码
public void setShutdown(Shutdown shutdown) { this.shutdown = shutdown; } /** * Returns the shutdown configuration that will be applied to the server. * @return the shutdown configuration * @since 2.3.0 */ public Shutdown getShutdown() { return this.shutdown; } /** * Return the {@link SslBundle} that should be used with this server. * @return the SSL bundle */ protected final SslBundle getSslBundle() { return WebServerSslBundle.get(this.ssl, this.sslBundles); } protected final Map<String, SslBundle> getServerNameSslBundles() { Assert.state(this.ssl != null, "'ssl' must not be null"); return this.ssl.getServerNameBundles() .stream() .collect(Collectors.toMap(ServerNameSslBundle::serverName, (serverNameSslBundle) -> { Assert.state(this.sslBundles != null, "'sslBundles' must not be null"); return this.sslBundles.getBundle(serverNameSslBundle.bundle()); }));
} /** * Return the absolute temp dir for given web server. * @param prefix server name * @return the temp dir for given server. */ protected final File createTempDir(String prefix) { try { File tempDir = Files.createTempDirectory(prefix + "." + getPort() + ".").toFile(); tempDir.deleteOnExit(); return tempDir; } catch (IOException ex) { throw new WebServerException( "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\AbstractConfigurableWebServerFactory.java
1
请完成以下Java代码
public int getK_CategoryValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_CategoryValue_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(getK_CategoryValue_ID())); } public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID)
{ if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_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_K_EntryCategory.java
1
请在Spring Boot框架中完成以下Java代码
public String getSearchKey() { return searchKey; } @Override public void setSearchKey(String searchKey) { this.searchKey = searchKey; } @Override public String getSearchKey2() { return searchKey2; } @Override public void setSearchKey2(String searchKey2) { this.searchKey2 = searchKey2; } @Override public String getBatchSearchKey() { return batchSearchKey; } @Override public void setBatchSearchKey(String batchSearchKey) { this.batchSearchKey = batchSearchKey; } @Override public String getBatchSearchKey2() { return batchSearchKey2; } @Override public void setBatchSearchKey2(String batchSearchKey2) { this.batchSearchKey2 = batchSearchKey2; } @Override public String getStatus() { return status; } @Override public void setStatus(String status) { this.status = status; } @Override public ByteArrayRef getResultDocRefId() { return resultDocRefId; } public void setResultDocRefId(ByteArrayRef resultDocRefId) { this.resultDocRefId = resultDocRefId; } @Override public String getResultDocumentJson(String engineType) { if (resultDocRefId != null) { byte[] bytes = resultDocRefId.getBytes(engineType); if (bytes != null) {
return new String(bytes, StandardCharsets.UTF_8); } } return null; } @Override public void setResultDocumentJson(String resultDocumentJson, String engineType) { this.resultDocRefId = setByteArrayRef(this.resultDocRefId, BATCH_RESULT_LABEL, resultDocumentJson, engineType); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } private static ByteArrayRef setByteArrayRef(ByteArrayRef byteArrayRef, String name, String value, String engineType) { if (byteArrayRef == null) { byteArrayRef = new ByteArrayRef(); } byte[] bytes = null; if (value != null) { bytes = value.getBytes(StandardCharsets.UTF_8); } byteArrayRef.setValue(name, bytes, engineType); return byteArrayRef; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchPartEntityImpl.java
2
请完成以下Java代码
public MultiCustomerHUReturnsResult createCustomerReturnInOutForHUs(final Collection<I_M_HU> shippedHUsToReturn) { return MultiCustomerHUReturnsInOutProducer.builder() .shippedHUsToReturn(shippedHUsToReturn) .build() .create(); } public void createVendorReturnInOutForHUs(final List<I_M_HU> hus, final Timestamp movementDate) { MultiVendorHUReturnsInOutProducer.newInstance() .setMovementDate(movementDate) .addHUsToReturn(hus) .create(); } public List<InOutId> createCustomerReturnsFromCandidates(@NonNull final List<CustomerReturnLineCandidate> candidates) { return customerReturnsWithoutHUsProducer.create(candidates); } public I_M_InOutLine createCustomerReturnLine(@NonNull final CreateCustomerReturnLineReq request) { return customerReturnsWithoutHUsProducer.createReturnLine(request); }
public void assignHandlingUnitToHeaderAndLine( @NonNull final org.compiere.model.I_M_InOutLine customerReturnLine, @NonNull final I_M_HU hu) { final ImmutableList<I_M_HU> hus = ImmutableList.of(hu); assignHandlingUnitsToHeaderAndLine(customerReturnLine, hus); } public void assignHandlingUnitsToHeaderAndLine( @NonNull final org.compiere.model.I_M_InOutLine customerReturnLine, @NonNull final List<I_M_HU> hus) { if (hus.isEmpty()) { return; } final InOutId customerReturnId = InOutId.ofRepoId(customerReturnLine.getM_InOut_ID()); final I_M_InOut customerReturn = huInOutBL.getById(customerReturnId, I_M_InOut.class); huInOutBL.addAssignedHandlingUnits(customerReturn, hus); huInOutBL.setAssignedHandlingUnits(customerReturnLine, hus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsServiceFacade.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_BoilerPlate_ID (final int AD_BoilerPlate_ID) { if (AD_BoilerPlate_ID < 1) set_Value (COLUMNNAME_AD_BoilerPlate_ID, null); else set_Value (COLUMNNAME_AD_BoilerPlate_ID, AD_BoilerPlate_ID); } @Override public int getAD_BoilerPlate_ID() { return get_ValueAsInt(COLUMNNAME_AD_BoilerPlate_ID); } @Override public void setC_Async_Batch_Type_ID (final int C_Async_Batch_Type_ID) { if (C_Async_Batch_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, C_Async_Batch_Type_ID); } @Override public int getC_Async_Batch_Type_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_Type_ID); } @Override public void setInternalName (final String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); }
@Override public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours) { set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours); } @Override public String getKeepAliveTimeHours() { return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours); } /** * NotificationType AD_Reference_ID=540643 * Reference name: _NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643; /** Async Batch Processed = ABP */ public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP"; /** Workpackage Processed = WPP */ public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP"; @Override public void setNotificationType (final @Nullable String NotificationType) { set_Value (COLUMNNAME_NotificationType, NotificationType); } @Override public String getNotificationType() { return get_ValueAsString(COLUMNNAME_NotificationType); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java
1
请完成以下Java代码
protected static String standardizeKeyword (String keyword) { if (keyword == null) return null; keyword = keyword.trim(); if (keyword.length() == 0) return null; // keyword = keyword.toUpperCase(); // default locale StringBuffer sb = new StringBuffer(); char[] chars = keyword.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; sb.append(standardizeCharacter(c)); } return sb.toString(); } // standardizeKeyword /** * Standardize Character * @param c character * @return string */ private static String standardizeCharacter (char c) { if (c >= '!' && c <= 'Z') // includes Digits return String.valueOf(c); //
int index = Arrays.binarySearch(s_char, c); if (index < 0) return String.valueOf(c); return s_string[index]; } // standardizeKeyword /** * Foreign upper case characters ascending for binary search. * Make sure that you use native2ascii to convert * (note Eclipse, etc. actually save the content as utf-8 - so the command is * native2ascii -encoding utf-8 filename) */ private static final char[] s_char = new char[] { '\u00c4', '\u00d6', '\u00dc', '\u00df' // ÄÖÜß - German stuff }; /** * Foreign character string linked to s_char position */ private static final String[] s_string = new String[] { "AE", "OE", "UE", "SS" }; } // MIndex
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MIndex.java
1
请在Spring Boot框架中完成以下Java代码
public void publishPartialResults(@NonNull final Collection<JSONDocumentReferencesGroup> groups) { if (groups.isEmpty()) { return; } for (final JSONDocumentReferencesGroup group : groups) { publishPartialResult(group); } } public void publishPartialResult(@NonNull final JSONDocumentReferencesGroup group) { try { sseEmitter.send(JSONDocumentReferencesEvent.partialResult(group), MediaType.APPLICATION_JSON); } catch (final IOException ex) { throw new AdempiereException("Failed sending partial result: " + group, ex); } } public void publishCompleted() { try { sseEmitter.send(JSONDocumentReferencesEvent.COMPLETED, MediaType.APPLICATION_JSON); sseEmitter.complete(); } catch (final IOException ex) { logger.warn("Failed publishing the COMPLETED event. Ignored.", ex); } }
public void publishCompletedWithError(final Throwable ex) { try { sseEmitter.send(JSONDocumentReferencesEvent.COMPLETED, MediaType.APPLICATION_JSON); sseEmitter.completeWithError(ex); } catch (final IOException ioe) { ioe.addSuppressed(ex); logger.warn("Failed publishing the COMPLETED event. Ignored.", ioe); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\controller\JSONDocumentReferencesEventPublisher.java
2
请完成以下Java代码
private void load() { if (isDisposed()) { return; } boolean visible = false; if (!Check.isEmpty(item.getSummary(), true)) { summaryText.setText(StringUtils.maskHTML(item.getSummary().trim(), false)); visible = true; } else { summaryText.setText(""); } if (!Check.isEmpty(item.getDetail(), true)) { // don't escape HTML because assume they are already HTMLs detailText.setText("<html>" + item.getDetail().trim() + "</html>"); visible = true; } else { detailText.setText(""); } setVisible(visible); } private final void onClose() { if (isDisposed()) { return; } if (callback == null) { return;
} callback.notificationClosed(item); } public void dispose() { setVisible(false); disposed = true; } private boolean isDisposed() { return disposed; } /** * Fade away and dispose this notification item. */ public void fadeAwayAndDispose() { // NOTE: atm we are just disposing it. Maybe in future we will really implement a nice fade away behaviour. dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\NotificationItemPanel.java
1
请完成以下Java代码
public java.lang.String getProjectTypeName() { return get_ValueAsString(COLUMNNAME_ProjectTypeName); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_ValueNoCheck (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name) { set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name); } @Override public java.lang.String getSalesRep_Name() { return get_ValueAsString(COLUMNNAME_SalesRep_Name);
} @Override public void setTaxID (final java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java
1
请在Spring Boot框架中完成以下Java代码
public void onSuccess(UUID id) { boolean empty = false; T msg = ackMap.remove(id); if (msg != null) { empty = pendingCount.decrementAndGet() == 0; } if (empty) { processingTimeoutLatch.countDown(); } else { if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T t : ackMap.values()) { log.trace("left item: {}", t); } } } } public void onFailure(UUID id, Throwable t) { boolean empty = false; T msg = ackMap.remove(id); if (msg != null) { empty = pendingCount.decrementAndGet() == 0;
failedMap.put(id, msg); if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T v : ackMap.values()) { log.trace("left item: {}", v); } } } if (empty) { processingTimeoutLatch.countDown(); } } public ConcurrentMap<UUID, T> getAckMap() { return ackMap; } public ConcurrentMap<UUID, T> getFailedMap() { return failedMap; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbPackProcessingContext.java
2
请完成以下Java代码
public void setM_Product_AttachmentEntry_ReferencedRecord_v_ID (final int M_Product_AttachmentEntry_ReferencedRecord_v_ID) { if (M_Product_AttachmentEntry_ReferencedRecord_v_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, M_Product_AttachmentEntry_ReferencedRecord_v_ID); } @Override public int getM_Product_AttachmentEntry_ReferencedRecord_v_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setType (final boolean Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override
public boolean isType() { return get_ValueAsBoolean(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_AttachmentEntry_ReferencedRecord_v.java
1