instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> { private int factoryId; private int toolId; public NonSingleToolFactory() { setSingleton(false); } @Override public Class<?> getObjectType() { return Tool.class; } @Override protected Tool createInstance() throws Exception { return new Tool(toolId); }
public int getFactoryId() { return factoryId; } public void setFactoryId(int factoryId) { this.factoryId = factoryId; } public int getToolId() { return toolId; } public void setToolId(int toolId) { this.toolId = toolId; } }
repos\tutorials-master\spring-core-3\src\main\java\com\baeldung\factorybean\NonSingleToolFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getLocationId() { return locationId; } public void setLocationId(String locationId) { this.locationId = locationId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Map<ProductEntity, Integer> getProdEntityCountMap() { return prodEntityCountMap; } public void setProdEntityCountMap(Map<ProductEntity, Integer> prodEntityCountMap) { this.prodEntityCountMap = prodEntityCountMap; }
public String getProdIdCountJson() { return prodIdCountJson; } public void setProdIdCountJson(String prodIdCountJson) { this.prodIdCountJson = prodIdCountJson; } @Override public String toString() { return "OrderInsertReq{" + "userId='" + userId + '\'' + ", prodIdCountJson='" + prodIdCountJson + '\'' + ", prodIdCountMap=" + prodIdCountMap + ", prodEntityCountMap=" + prodEntityCountMap + ", payModeCode=" + payModeCode + ", receiptId='" + receiptId + '\'' + ", locationId='" + locationId + '\'' + ", remark='" + remark + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderInsertReq.java
2
请完成以下Java代码
public class RequestHeaderSizeGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestHeaderSizeGatewayFilterFactory.Config> { private static String ERROR_PREFIX = "Request Header/s size is larger than permissible limit (%s)."; private static String ERROR = " Request Header/s size for '%s' is %s."; public RequestHeaderSizeGatewayFilterFactory() { super(RequestHeaderSizeGatewayFilterFactory.Config.class); } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList("maxSize"); } @Override public GatewayFilter apply(RequestHeaderSizeGatewayFilterFactory.Config config) { String errorHeaderName = config.getErrorHeaderName() != null ? config.getErrorHeaderName() : "errorMessage"; return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); HashMap<String, Long> longHeaders = new HashMap<>(); for (Map.Entry<String, List<String>> headerEntry : headers.headerSet()) { long headerSizeInBytes = 0L; headerSizeInBytes += headerEntry.getKey().getBytes().length; List<String> values = headerEntry.getValue(); for (String value : values) { headerSizeInBytes += value.getBytes().length; } if (headerSizeInBytes > config.getMaxSize().toBytes()) { longHeaders.put(headerEntry.getKey(), headerSizeInBytes); } } if (!longHeaders.isEmpty()) { exchange.getResponse().setStatusCode(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE); exchange.getResponse() .getHeaders() .add(errorHeaderName, getErrorMessage(longHeaders, config.getMaxSize())); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public String toString() { return filterToStringCreator(RequestHeaderSizeGatewayFilterFactory.this) .append("maxSize", config.getMaxSize()) .toString(); } }; } private static String getErrorMessage(HashMap<String, Long> longHeaders, DataSize maxSize) { StringBuilder msg = new StringBuilder(String.format(ERROR_PREFIX, maxSize)); longHeaders .forEach((header, size) -> msg.append(String.format(ERROR, header, DataSize.of(size, DataUnit.BYTES))));
return msg.toString(); } public static class Config { private DataSize maxSize = DataSize.ofBytes(16000L); private @Nullable String errorHeaderName; public DataSize getMaxSize() { return maxSize; } public void setMaxSize(DataSize maxSize) { this.maxSize = maxSize; } public @Nullable String getErrorHeaderName() { return errorHeaderName; } public void setErrorHeaderName(String errorHeaderName) { this.errorHeaderName = errorHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestHeaderSizeGatewayFilterFactory.java
1
请完成以下Java代码
public class DeviceDescriptorsList { public static final DeviceDescriptorsList EMPTY = new DeviceDescriptorsList(); public static DeviceDescriptorsList ofList(@NonNull final List<DeviceDescriptor> list) { return !list.isEmpty() ? new DeviceDescriptorsList(list) : EMPTY; } private final ImmutableList<DeviceDescriptor> list; private DeviceDescriptorsList() { this.list = ImmutableList.of(); } private DeviceDescriptorsList(@NonNull final List<DeviceDescriptor> list) { this.list = ImmutableList.copyOf(list); }
public boolean isEmpty() { return list.isEmpty(); } public Stream<DeviceDescriptor> stream() { return list.stream(); } public ImmutableList<DeviceDescriptor> toList() { return list; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\device_providers\DeviceDescriptorsList.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final DATEVExportFormat exportFormat = exportFormatRepo.getById(datevExportFormatId); final I_DATEV_Export datevExport = getRecord(I_DATEV_Export.class); final IExportDataSource dataSource = createDataSource(exportFormat, datevExport.getDATEV_Export_ID()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); DATEVCsvExporter.builder() .exportFormat(exportFormat) .dataSource(dataSource) .build() .export(out); getResult().setReportData( new ByteArrayResource(out.toByteArray()), // data buildFilename(datevExport), // filename "text/csv"); // content type return MSG_OK; } private IExportDataSource createDataSource(@NonNull final DATEVExportFormat exportFormat, final int datevExportId) { Check.assume(datevExportId > 0, "datevExportId > 0"); final JdbcExporterBuilder builder = new JdbcExporterBuilder(I_DATEV_ExportLine.Table_Name) .addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_DATEV_Export_ID, datevExportId) .addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_IsActive, true) .addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DocumentNo) .addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DATEV_ExportLine_ID);
exportFormat .getColumns() .forEach(formatColumn -> builder.addField(formatColumn.getCsvHeaderName(), formatColumn.getColumnName())); return builder.createDataSource(); } private static String buildFilename(final I_DATEV_Export datevExport) { final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd"); final Timestamp dateAcctFrom = datevExport.getDateAcctFrom(); final Timestamp dateAcctTo = datevExport.getDateAcctTo(); return Joiner.on("_") .skipNulls() .join("datev", dateAcctFrom != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctFrom)) : null, dateAcctTo != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctTo)) : null) + ".csv"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\process\DATEV_ExportFile.java
1
请完成以下Java代码
class RolloutVersionLoader { public static final String BUILD_INFO_FILENAME = "build-info.properties"; public static final String PROP_VERSION = "build.version"; @NonNull private final PropertiesFileLoader propertiesFileLoader; /** * Invokes our {@link PropertiesFileLoader} to load the {@link #BUILD_INFO_FILENAME} from the given {@code dirName} and returns it. * * @throws CantGetRolloutVersionStringException */ public String loadRolloutVersionString(@NonNull final String dirName) { try { final Properties buildInfo = propertiesFileLoader.loadFromFile(dirName, BUILD_INFO_FILENAME); final String rolloutVersionStr = buildInfo.getProperty(PROP_VERSION); return rolloutVersionStr; } catch (final CantLoadPropertiesException e) { throw new CantGetRolloutVersionStringException(e);
} } public static final class CantGetRolloutVersionStringException extends RuntimeException { private static final long serialVersionUID = -7869876695610886103L; private CantGetRolloutVersionStringException(final CantLoadPropertiesException e) { super("Unable to get our own version.\n" + "Hint: provide the build.version file\n" + "or use -v -u to disable both version-check and the version-update at the start and end of the tool", e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\RolloutVersionLoader.java
1
请完成以下Java代码
public void performDataAuditForRequest(final GenericDataExportAuditRequest genericDataExportAuditRequest) { if (!isHandled(genericDataExportAuditRequest)) { return; } final ExternalSystemParentConfigId externalSystemParentConfigId = genericDataExportAuditRequest.getExternalSystemParentConfigId(); final PInstanceId pInstanceId = genericDataExportAuditRequest.getPInstanceId(); final Object exportedObject = genericDataExportAuditRequest.getExportedObject(); final Optional<JsonGetSingleHUResponse> jsonGetSingleHUResponse = JsonMapperUtil.tryDeserializeToType(exportedObject, JsonGetSingleHUResponse.class); jsonGetSingleHUResponse.ifPresent(getSingleHUResponse -> auditHUResponse(getSingleHUResponse, externalSystemParentConfigId, pInstanceId)); } @Override public boolean isHandled(final GenericDataExportAuditRequest genericDataExportAuditRequest) { final AntPathMatcher antPathMatcher = new AntPathMatcher(); return Arrays.stream(HANDLING_UNITS_RESOURCES) .anyMatch(resource -> antPathMatcher.match(resource, genericDataExportAuditRequest.getRequestURI())); } private void auditHUResponse( @NonNull final JsonGetSingleHUResponse jsonGetSingleHUResponse, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { final JsonHU jsonHU = jsonGetSingleHUResponse.getResult(); auditHU(jsonHU, /*parentExportAuditId*/ null, externalSystemParentConfigId, pInstanceId); } private void auditHU( @NonNull final JsonHU jsonHU, @Nullable final DataExportAuditId parentExportAuditId, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { if(jsonHU.getId() == null) { return;
} final HuId huId = HuId.ofObject(jsonHU.getId()); final Action exportAction = parentExportAuditId != null ? Action.AlongWithParent : Action.Standalone; final DataExportAuditRequest huDataExportAuditRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_M_HU.Table_Name, huId.getRepoId())) .action(exportAction) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(parentExportAuditId) .build(); final DataExportAuditId dataExportAuditId = dataExportAuditService.createExportAudit(huDataExportAuditRequest); if (jsonHU.getIncludedHUs() == null) { return; } jsonHU.getIncludedHUs().forEach(includedHU -> auditHU(includedHU, dataExportAuditId, externalSystemParentConfigId, pInstanceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HUAuditService.java
1
请完成以下Java代码
public long updateLastUplinkTime() { this.lastUplinkTime = System.currentTimeMillis(); this.firstEdrxDownlink = true; return lastUplinkTime; } public boolean checkFirstDownlink() { boolean result = firstEdrxDownlink; firstEdrxDownlink = false; return result; } public LwM2mPath getLwM2mPathFromString(String path) { return new LwM2mPath(fromVersionedIdToObjectId(path)); } public LwM2m.Version getDefaultObjectIDVer() { return this.defaultObjectIDVer == null ? new Version(LWM2M_OBJECT_VERSION_DEFAULT) : this.defaultObjectIDVer; } public LwM2m.Version getSupportedObjectVersion(Integer objectid) { return this.supportedClientObjects != null ? this.supportedClientObjects.get(objectid) : null; } private void setSupportedClientObjects(){ if (this.registration.getSupportedObject() != null && this.registration.getSupportedObject().size() > 0) { this.supportedClientObjects = this.registration.getSupportedObject(); } else { this.supportedClientObjects = new ConcurrentHashMap<>(); for (Link link : this.registration.getSortedObjectLinks()) { if (link instanceof MixedLwM2mLink) {
LwM2mPath path = ((MixedLwM2mLink) link).getPath(); // add supported objects if (path.isObject() || path.isObjectInstance()) { int objectId = path.getObjectId(); LwM2mAttribute<Version> versionParamValue = link.getAttributes().get(LwM2mAttributes.OBJECT_VERSION); if (versionParamValue != null) { // if there is a version attribute then use it as version for this object this.supportedClientObjects.put(objectId, versionParamValue.getValue()); } else { // there is no version attribute attached. // In this case we use the DEFAULT_VERSION only if this object stored as supported object. Version currentVersion = this.supportedClientObjects.get(objectId); if (currentVersion == null) { this.supportedClientObjects.put(objectId, getDefaultObjectIDVer()); } } } } } } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\client\LwM2mClient.java
1
请完成以下Java代码
public static InvoiceReferenceNo parse(@NonNull final String referenceString) { final String bankAccount = referenceString.substring(0, 7); final String org = referenceString.substring(7, 10); final String bPartnerHint = removeLeftZeros(referenceString.substring(10, 18)); final String invoiceHint = removeLeftZeros(referenceString.substring(18, 26)); final int checkDigit = computeCheckDigit(bankAccount, org, bPartnerHint, invoiceHint); return InvoiceReferenceNo.builder() .bankAccount(bankAccount) .org(org) .bPartnerHint(bPartnerHint) .invoiceHint(invoiceHint) .checkDigit(checkDigit) .build(); } /** * Method to remove the left zeros from a string. * * @param value * @return the initial String if it's made of only zeros; the string without the left zeros otherwise. */ private static final String removeLeftZeros(final String value) { final int size = value.length(); int counter; for (counter = 0; counter < size; counter++) { if (value.charAt(counter) != '0') { break; } } if (counter == size) { return value; } else { return value.substring(counter, size);
} } private static int computeCheckDigit( @NonNull final String bankAccount, @NonNull final String org, @NonNull final String bPartner, @NonNull final String invoice) { final StringBuilder sb = new StringBuilder(); sb.append(bankAccount); sb.append(org); sb.append(bPartner); sb.append(invoice); try { final IESRImportBL esrImportBL = Services.get(IESRImportBL.class); final int checkDigit = esrImportBL.calculateESRCheckDigit(sb.toString()); return checkDigit; } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e) .appendParametersToMessage() .setParameter("bankAccount", bankAccount) .setParameter("org", org) .setParameter("bPartner", bPartner) .setParameter("invoice", invoice); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\InvoiceReferenceNos.java
1
请完成以下Java代码
private Resource loadResource(Resource asResource, String asString, String asLocation) { return Optional.ofNullable(asResource) .orElseGet(() -> Optional.ofNullable(asString) .map(pk -> (Resource) new ByteArrayResource(pk.getBytes(StandardCharsets.UTF_8))) .orElseGet(() -> Optional.ofNullable(asLocation) .map(resourceLoader::getResource) .orElseThrow(() -> new IllegalArgumentException("Unable to load secret key. Either resource, key as string, or resource location must be provided")))); } /** * <p>loadSecretKeyResource.</p> * * @return a {@link org.springframework.core.io.Resource} object */ public Resource loadSecretKeyResource() { return loadResource(secretKeyResource, secretKey, secretKeyLocation); } /** * <p>getSecretKeyPasswordChars.</p> * * @return an array of {@link char} objects */ public char[] getSecretKeyPasswordChars() { return secretKeyPassword.toCharArray(); } /** * <p>getSecretKeySaltGenerator.</p> * * @return a {@link org.jasypt.salt.SaltGenerator} object */ public SaltGenerator getSecretKeySaltGenerator() { return saltGenerator != null ? saltGenerator :
(secretKeySalt == null ? new ZeroSaltGenerator() : new FixedBase64ByteArraySaltGenerator(secretKeySalt)); } @SneakyThrows private IvGenerator instantiateIvGenerator() { return (IvGenerator)Class.forName(this.ivGeneratorClassName).newInstance(); } /** * <p>getActualIvGenerator.</p> * * @return a {@link org.jasypt.iv.IvGenerator} object */ public IvGenerator getActualIvGenerator() { return Optional.ofNullable(ivGenerator).orElseGet(this::instantiateIvGenerator); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleGCMConfig.java
1
请完成以下Java代码
public IntentEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public IntentEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public IntentEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public IntentEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public IntentEventListenerInstanceQuery asc() { innerQuery.asc(); return this; } @Override public IntentEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public IntentEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public IntentEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder);
return this; } @Override public long count() { return innerQuery.count(); } @Override public IntentEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return IntentEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<IntentEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<IntentEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<IntentEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(IntentEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
public class Todo { private int id; private String message; private int priority; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMessage() {
return message; } public void setMessage(String message) { this.message = message; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\jsfapplication\model\Todo.java
1
请在Spring Boot框架中完成以下Java代码
public void logLoginAction(User user, Object authenticationDetails, ActionType actionType, Exception e) { logLoginAction(user, authenticationDetails, actionType, null, e); } @Override public void logLoginAction(User user, Object authenticationDetails, ActionType actionType, String provider, Exception e) { String clientAddress = "Unknown"; String browser = "Unknown"; String os = "Unknown"; String device = "Unknown"; if (authenticationDetails instanceof RestAuthenticationDetails) { RestAuthenticationDetails details = (RestAuthenticationDetails) authenticationDetails; clientAddress = details.getClientAddress(); if (details.getUserAgent() != null) { Client userAgent = details.getUserAgent(); if (userAgent.userAgent != null) { browser = userAgent.userAgent.family; if (userAgent.userAgent.major != null) { browser += " " + userAgent.userAgent.major; if (userAgent.userAgent.minor != null) { browser += "." + userAgent.userAgent.minor; if (userAgent.userAgent.patch != null) { browser += "." + userAgent.userAgent.patch; } } } } if (userAgent.os != null) { os = userAgent.os.family; if (userAgent.os.major != null) {
os += " " + userAgent.os.major; if (userAgent.os.minor != null) { os += "." + userAgent.os.minor; if (userAgent.os.patch != null) { os += "." + userAgent.os.patch; if (userAgent.os.patchMinor != null) { os += "." + userAgent.os.patchMinor; } } } } } if (userAgent.device != null) { device = userAgent.device.family; } } } if (actionType == ActionType.LOGIN && e == null) { userService.updateLastLoginTs(user.getTenantId(), user.getId()); } auditLogService.logEntityAction( user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), null, actionType, e, clientAddress, browser, os, device, provider); } private static boolean isPositiveInteger(Integer val) { return val != null && val.intValue() > 0; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\system\DefaultSystemSecurityService.java
2
请完成以下Java代码
public int calculateDurationDays(final int leadTimeDays, @NonNull final ProductPlanning productPlanningData) { Check.assume(leadTimeDays >= 0, "leadTimeDays >= 0"); final int transferTimeDays = productPlanningData.getTransferTimeDays(); Check.assume(transferTimeDays >= 0, "transferTimeDays >= 0"); return leadTimeDays + transferTimeDays; } public Optional<ResourceId> getPlantOfWarehouse(@NonNull final WarehouseId warehouseId) { final I_M_Warehouse warehouse = Services.get(IWarehouseBL.class).getById(warehouseId); return ResourceId.optionalOfRepoId(warehouse.getPP_Plant_ID()); } public Optional<PPRoutingId> getDefaultRoutingId(@NonNull final PPRoutingType type) { return routingRepository.getDefaultRoutingIdByType(type); } public int calculateDurationDays( @NonNull final ProductPlanning productPlanning, @NonNull final BigDecimal qty)
{ final int leadTimeDays = calculateLeadTimeDays(productPlanning, qty); return calculateDurationDays(leadTimeDays, productPlanning); } private int calculateLeadTimeDays( @NonNull final ProductPlanning productPlanningRecord, @NonNull final BigDecimal qty) { final int leadTimeDays = productPlanningRecord.getLeadTimeDays(); if (leadTimeDays > 0) { // LeadTime was set in Product Planning/ take the leadtime as it is return leadTimeDays; } final PPRoutingId routingId = productPlanningRecord.getWorkflowId(); final ResourceId plantId = productPlanningRecord.getPlantId(); final RoutingService routingService = RoutingServiceFactory.get().getRoutingService(); return routingService.calculateDurationDays(routingId, plantId, qty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ProductPlanningService.java
1
请完成以下Java代码
public void setGenerated(boolean generated) { this.generated = generated; } /** * Indicated whether or not the resource has been generated while deploying rather than * being actual part of the deployment. */ public boolean isGenerated() { return generated; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) {
this.createTime = createTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", name=" + name + ", deploymentId=" + deploymentId + ", generated=" + generated + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, IdentityVerificationException { Tokens tokens = authenticationController.handle(request, response); DecodedJWT jwt = JWT.decode(tokens.getIdToken()); TestingAuthenticationToken authToken2 = new TestingAuthenticationToken(jwt.getSubject(), jwt.getToken()); authToken2.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authToken2); response.sendRedirect(config.getContextPath(request) + "/"); } public String getManagementApiToken() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject requestBody = new JSONObject(); requestBody.put("client_id", config.getManagementApiClientId()); requestBody.put("client_secret", config.getManagementApiClientSecret()); requestBody.put("audience", "https://dev-example.auth0.com/api/v2/"); requestBody.put("grant_type", config.getGrantType()); HttpEntity<String> request = new HttpEntity<String>(requestBody.toString(), headers); RestTemplate restTemplate = new RestTemplate(); HashMap<String, String> result = restTemplate.postForObject(AUTH0_TOKEN_URL, request, HashMap.class); return result.get("access_token"); } }
repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\java\com\baeldung\auth0\controller\AuthController.java
2
请在Spring Boot框架中完成以下Java代码
public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities; } public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } @Override public String toString() { return "UserDTO{" +
"login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
2
请完成以下Java代码
private static ImmutableList<SqlLookupFilter> computeActiveFilters( final @NonNull ImmutableList<SqlLookupFilter> allFilters, final @Nullable LookupDescriptorProvider.LookupScope onlyScope, final @Nullable ImmutableSet<String> availableParameterNames) { final ImmutableList.Builder<SqlLookupFilter> result = ImmutableList.builder(); for (SqlLookupFilter filter : allFilters) { if (onlyScope != null && !filter.isMatchingScope(onlyScope)) { continue; } if (!filter.isMatchingForAvailableParameterNames(availableParameterNames)) { continue; } result.add(filter); } return result.build(); } private static IStringExpression computeSqlWhereClause(@NonNull final ImmutableList<SqlLookupFilter> filters) { if (filters.isEmpty()) { return IStringExpression.NULL; } final CompositeStringExpression.Builder builder = IStringExpression.composer(); for (SqlLookupFilter filter : filters) { final IStringExpression sqlWhereClause = filter.getSqlWhereClause(); if (sqlWhereClause != null && !sqlWhereClause.isNullExpression()) { builder.appendIfNotEmpty("\n AND ").append("(").append(sqlWhereClause).append(")"); } } return builder.build(); } private static INamePairPredicate computePostQueryPredicate(@NonNull final ImmutableList<SqlLookupFilter> filters) { if (filters.isEmpty()) { return NamePairPredicates.ACCEPT_ALL;
} final NamePairPredicates.Composer builder = NamePairPredicates.compose(); for (SqlLookupFilter filter : filters) { final INamePairPredicate postQueryPredicate = filter.getPostQueryPredicate(); if (postQueryPredicate != null) { builder.add(postQueryPredicate); } } return builder.build(); } private static ImmutableSet<String> computeDependsOnTableNames(final ImmutableList<SqlLookupFilter> filters) { return filters.stream() .flatMap(filter -> filter.getDependsOnTableNames().stream()) .collect(ImmutableSet.toImmutableSet()); } private static ImmutableSet<String> computeDependsOnFieldNames(final ImmutableList<SqlLookupFilter> filters) { return filters.stream() .flatMap(filter -> filter.getDependsOnFieldNames().stream()) .collect(ImmutableSet.toImmutableSet()); } public CompositeSqlLookupFilter withOnlyScope(@Nullable LookupDescriptorProvider.LookupScope onlyScope) { return !Objects.equals(this.onlyScope, onlyScope) ? new CompositeSqlLookupFilter(this.allFilters, onlyScope, this.onlyForAvailableParameterNames) : this; } public CompositeSqlLookupFilter withOnlyForAvailableParameterNames(@Nullable Set<String> onlyForAvailableParameterNames) { return !Objects.equals(this.onlyForAvailableParameterNames, onlyForAvailableParameterNames) ? new CompositeSqlLookupFilter(this.allFilters, this.onlyScope, onlyForAvailableParameterNames) : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilter.java
1
请完成以下Java代码
public Builder picture(String picture) { return this.claim(StandardClaimNames.PICTURE, picture); } /** * Use this phone number in the resulting {@link OidcUserInfo} * @param phoneNumber The phone number to use * @return the {@link Builder} for further configurations */ public Builder phoneNumber(String phoneNumber) { return this.claim(StandardClaimNames.PHONE_NUMBER, phoneNumber); } /** * Use this verified-phone-number indicator in the resulting {@link OidcUserInfo} * @param phoneNumberVerified The verified-phone-number indicator to use * @return the {@link Builder} for further configurations * @since 5.8 */ public Builder phoneNumberVerified(Boolean phoneNumberVerified) { return this.claim(StandardClaimNames.PHONE_NUMBER_VERIFIED, phoneNumberVerified); } /** * Use this preferred username in the resulting {@link OidcUserInfo} * @param preferredUsername The preferred username to use * @return the {@link Builder} for further configurations */ public Builder preferredUsername(String preferredUsername) { return claim(StandardClaimNames.PREFERRED_USERNAME, preferredUsername); } /** * Use this profile in the resulting {@link OidcUserInfo} * @param profile The profile to use * @return the {@link Builder} for further configurations */ public Builder profile(String profile) { return claim(StandardClaimNames.PROFILE, profile); } /** * Use this subject in the resulting {@link OidcUserInfo} * @param subject The subject to use * @return the {@link Builder} for further configurations */
public Builder subject(String subject) { return this.claim(StandardClaimNames.SUB, subject); } /** * Use this updated-at {@link Instant} in the resulting {@link OidcUserInfo} * @param updatedAt The updated-at {@link Instant} to use * @return the {@link Builder} for further configurations */ public Builder updatedAt(String updatedAt) { return this.claim(StandardClaimNames.UPDATED_AT, updatedAt); } /** * Use this website in the resulting {@link OidcUserInfo} * @param website The website to use * @return the {@link Builder} for further configurations */ public Builder website(String website) { return this.claim(StandardClaimNames.WEBSITE, website); } /** * Use this zoneinfo in the resulting {@link OidcUserInfo} * @param zoneinfo The zoneinfo to use * @return the {@link Builder} for further configurations */ public Builder zoneinfo(String zoneinfo) { return this.claim(StandardClaimNames.ZONEINFO, zoneinfo); } /** * Build the {@link OidcUserInfo} * @return The constructed {@link OidcUserInfo} */ public OidcUserInfo build() { return new OidcUserInfo(this.claims); } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcUserInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class AttributesChangedEventHandler implements MaterialEventHandler<AttributesChangedEvent> { private final CandidateChangeService candidateChangeHandler; public AttributesChangedEventHandler( @NonNull final CandidateChangeService candidateChangeHandler) { this.candidateChangeHandler = candidateChangeHandler; } @Override public Collection<Class<? extends AttributesChangedEvent>> getHandledEventType() { return ImmutableList.of(AttributesChangedEvent.class); } @Override public void handleEvent(final AttributesChangedEvent event) { final Candidate fromCandidate = createCandidate(event, CandidateType.ATTRIBUTES_CHANGED_FROM); final MaterialDispoGroupId groupId = candidateChangeHandler.onCandidateNewOrChange(fromCandidate) .getEffectiveGroupId() .orElseThrow(() -> new AdempiereException("No groupId")); final Candidate toCandidate = createCandidate(event, CandidateType.ATTRIBUTES_CHANGED_TO) .withGroupId(groupId); candidateChangeHandler.onCandidateNewOrChange(toCandidate); } private Candidate createCandidate(final AttributesChangedEvent event, final CandidateType type) { final BigDecimal qty; final AttributesKeyWithASI attributes; if (CandidateType.ATTRIBUTES_CHANGED_FROM.equals(type)) { qty = event.getQty().negate(); attributes = event.getOldStorageAttributes(); } else if (CandidateType.ATTRIBUTES_CHANGED_TO.equals(type)) { qty = event.getQty(); attributes = event.getNewStorageAttributes(); }
else { throw new AdempiereException("Invalid type: " + type); // really shall not happen } return Candidate.builderForEventDescriptor(event.getEventDescriptor()) .type(type) .materialDescriptor(MaterialDescriptor.builder() .warehouseId(event.getWarehouseId()) .quantity(qty) .date(event.getDate()) .productDescriptor(toProductDescriptor(event.getProductId(), attributes)) .build()) .build(); } private static ProductDescriptor toProductDescriptor(final int productId, final AttributesKeyWithASI attributes) { return ProductDescriptor.forProductAndAttributes(productId, CoalesceUtil.coalesceNotNull(attributes.getAttributesKey(), AttributesKey.NONE), attributes.getAttributeSetInstanceId().getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\attributes\AttributesChangedEventHandler.java
2
请在Spring Boot框架中完成以下Java代码
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代码
public ImmutableSet<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } public boolean isPriceEditable() { return isFieldEditable(FIELD_Price); } @SuppressWarnings("SameParameterValue") private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } @Override public DocumentId getId() { return id; } @Override public boolean isProcessed() { return false; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } public ProductId getProductId() { return getProduct().getIdAs(ProductId::ofRepoId); } public String getProductName() { return getProduct().getDisplayName(); } public boolean isQtySet() { final BigDecimal qty = getQty(); return qty != null && qty.signum() != 0; } public ProductsProposalRow withLastShipmentDays(final Integer lastShipmentDays) { if (Objects.equals(this.lastShipmentDays, lastShipmentDays)) { return this; }
else { return toBuilder().lastShipmentDays(lastShipmentDays).build(); } } public boolean isChanged() { return getProductPriceId() == null || !getPrice().isPriceListPriceUsed(); } public boolean isMatching(@NonNull final ProductsProposalViewFilter filter) { return Check.isEmpty(filter.getProductName()) || getProductName().toLowerCase().contains(filter.getProductName().toLowerCase()); } public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine) { if(existingOrderLine == null) { return this; } final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode()); return toBuilder() .qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity() ? existingOrderLine.getQtyEnteredCU() : BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU())) .price(ProductProposalPrice.builder() .priceListPrice(existingPrice) .build()) .existingOrderLineId(existingOrderLine.getOrderLineId()) .description(existingOrderLine.getDescription()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Pharma Product Category. @param M_PharmaProductCategory_ID Pharma Product Category */ @Override public void setM_PharmaProductCategory_ID (int M_PharmaProductCategory_ID) { if (M_PharmaProductCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, Integer.valueOf(M_PharmaProductCategory_ID)); } /** Get Pharma Product Category. @return Pharma Product Category */ @Override public int getM_PharmaProductCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PharmaProductCategory_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_PharmaProductCategory.java
1
请完成以下Java代码
public void setF_SHAREDIREC(String f_SHAREDIREC) { F_SHAREDIREC = f_SHAREDIREC; } public String getF_HISTORYID() { return F_HISTORYID; } public void setF_HISTORYID(String f_HISTORYID) { F_HISTORYID = f_HISTORYID; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_VERSION() { return F_VERSION; } public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } public String getF_ISSTD() { return F_ISSTD; } public void setF_ISSTD(String f_ISSTD) { F_ISSTD = f_ISSTD; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; }
public String getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(String f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISENTERPRISES() { return F_ISENTERPRISES; } public void setF_ISENTERPRISES(String f_ISENTERPRISES) { F_ISENTERPRISES = f_ISENTERPRISES; } public String getF_ISCLEAR() { return F_ISCLEAR; } public void setF_ISCLEAR(String f_ISCLEAR) { F_ISCLEAR = f_ISCLEAR; } public String getF_PARENTID() { return F_PARENTID; } public void setF_PARENTID(String f_PARENTID) { F_PARENTID = f_PARENTID; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return this.name; } public List<ValueHint> getValues() { return Collections.unmodifiableList(this.values); } public List<ValueProvider> getProviders() { return Collections.unmodifiableList(this.providers); } /** * Return an {@link ItemHint} with the given prefix applied. * @param prefix the prefix to apply * @return a new {@link ItemHint} with the same of this instance whose property name * has the prefix applied to it */ public ItemHint applyPrefix(String prefix) { return new ItemHint(ConventionUtils.toDashedCase(prefix) + "." + this.name, this.values, this.providers); } @Override public int compareTo(ItemHint other) { return getName().compareTo(other.getName()); } public static ItemHint newHint(String name, ValueHint... values) { return new ItemHint(name, Arrays.asList(values), Collections.emptyList()); } @Override public String toString() { return "ItemHint{name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}'; } /** * A hint for a value. */ public static class ValueHint { private final Object value; private final String description; public ValueHint(Object value, String description) { this.value = value; this.description = description; } public Object getValue() { return this.value; } public String getDescription() { return this.description; }
@Override public String toString() { return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}'; } } /** * A value provider. */ public static class ValueProvider { private final String name; private final Map<String, Object> parameters; public ValueProvider(String name, Map<String, Object> parameters) { this.name = name; this.parameters = parameters; } public String getName() { return this.name; } public Map<String, Object> getParameters() { return this.parameters; } @Override public String toString() { return "ValueProvider{name='" + this.name + "', parameters=" + this.parameters + '}'; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemHint.java
2
请完成以下Java代码
private SqlDocumentFilterConvertersList buildViewFilterConverters() { return filterConverters.build(); } public Builder filterConverter(@NonNull final SqlDocumentFilterConverter converter) { filterConverters.converter(converter); return this; } public Builder filterConverters(@NonNull final List<SqlDocumentFilterConverter> converters) { filterConverters.converters(converters); return this; } public Builder rowIdsConverter(@NonNull final SqlViewRowIdsConverter rowIdsConverter) { this.rowIdsConverter = rowIdsConverter; return this; } private SqlViewRowIdsConverter getRowIdsConverter() { if (rowIdsConverter != null) { return rowIdsConverter; } if (groupingBinding != null) { return groupingBinding.getRowIdsConverter(); } return SqlViewRowIdsConverters.TO_INT_STRICT; } public Builder groupingBinding(final SqlViewGroupingBinding groupingBinding) { this.groupingBinding = groupingBinding; return this; } public Builder filterConverterDecorator(@NonNull final SqlDocumentFilterConverterDecorator sqlDocumentFilterConverterDecorator) { this.sqlDocumentFilterConverterDecorator = sqlDocumentFilterConverterDecorator; return this; } public Builder rowCustomizer(final ViewRowCustomizer rowCustomizer) {
this.rowCustomizer = rowCustomizer; return this; } private ViewRowCustomizer getRowCustomizer() { return rowCustomizer; } public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor) { this.viewInvalidationAdvisor = viewInvalidationAdvisor; return this; } private IViewInvalidationAdvisor getViewInvalidationAdvisor() { return viewInvalidationAdvisor; } public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this.refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this; } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder includedEntitiesDescriptors(final Map<DetailId, SqlDocumentEntityDataBindingDescriptor> includedEntitiesDescriptors) { this.includedEntitiesDescriptors = includedEntitiesDescriptors; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBinding.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public boolean isCreationLog() { return state == JobState.CREATED.getStateCode(); }
public boolean isFailureLog() { return state == JobState.FAILED.getStateCode(); } public boolean isSuccessLog() { return state == JobState.SUCCESSFUL.getStateCode(); } public boolean isDeletionLog() { return state == JobState.DELETED.getStateCode(); } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java
1
请完成以下Java代码
public int getAD_User_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Alberta_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Gender AD_Reference_ID=541317 * Reference name: Gender_List */ public static final int GENDER_AD_Reference_ID=541317; /** Unbekannt = 0 */ public static final String GENDER_Unbekannt = "0"; /** Weiblich = 1 */ public static final String GENDER_Weiblich = "1"; /** Männlich = 2 */ public static final String GENDER_Maennlich = "2"; /** Divers = 3 */ public static final String GENDER_Divers = "3"; @Override public void setGender (final @Nullable java.lang.String Gender) { set_Value (COLUMNNAME_Gender, Gender); } @Override public java.lang.String getGender() { return get_ValueAsString(COLUMNNAME_Gender); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } /** * Title AD_Reference_ID=541318
* Reference name: Title_List */ public static final int TITLE_AD_Reference_ID=541318; /** Unbekannt = 0 */ public static final String TITLE_Unbekannt = "0"; /** Dr. = 1 */ public static final String TITLE_Dr = "1"; /** Prof. Dr. = 2 */ public static final String TITLE_ProfDr = "2"; /** Dipl. Ing. = 3 */ public static final String TITLE_DiplIng = "3"; /** Dipl. Med. = 4 */ public static final String TITLE_DiplMed = "4"; /** Dipl. Psych. = 5 */ public static final String TITLE_DiplPsych = "5"; /** Dr. Dr. = 6 */ public static final String TITLE_DrDr = "6"; /** Dr. med. = 7 */ public static final String TITLE_DrMed = "7"; /** Prof. Dr. Dr. = 8 */ public static final String TITLE_ProfDrDr = "8"; /** Prof. = 9 */ public static final String TITLE_Prof = "9"; /** Prof. Dr. med. = 10 */ public static final String TITLE_ProfDrMed = "10"; /** Rechtsanwalt = 11 */ public static final String TITLE_Rechtsanwalt = "11"; /** Rechtsanwältin = 12 */ public static final String TITLE_Rechtsanwaeltin = "12"; /** Schwester (Orden) = 13 */ public static final String TITLE_SchwesterOrden = "13"; @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_AD_User_Alberta.java
1
请完成以下Java代码
public class ParticipantMultiplicityImpl extends BaseElementImpl implements ParticipantMultiplicity { protected static Attribute<Integer> minimumAttribute; protected static Attribute<Integer> maximumAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ParticipantMultiplicity.class, BPMN_ELEMENT_PARTICIPANT_MULTIPLICITY) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<ParticipantMultiplicity>() { public ParticipantMultiplicity newInstance(ModelTypeInstanceContext instanceContext) { return new ParticipantMultiplicityImpl(instanceContext); } }); minimumAttribute = typeBuilder.integerAttribute(BPMN_ATTRIBUTE_MINIMUM) .defaultValue(0) .build(); maximumAttribute = typeBuilder.integerAttribute(BPMN_ATTRIBUTE_MAXIMUM) .defaultValue(1) .build();
typeBuilder.build(); } public ParticipantMultiplicityImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public int getMinimum() { return minimumAttribute.getValue(this); } public void setMinimum(int minimum) { minimumAttribute.setValue(this, minimum); } public int getMaximum() { return maximumAttribute.getValue(this); } public void setMaximum(int maximum) { maximumAttribute.setValue(this, maximum); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParticipantMultiplicityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Inventory implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @Min(value = 0) @Max(value = 100) private int quantity; @Version private short version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) {
this.title = title; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public short getVersion() { return version; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHTTPLongConversationDetachedEntity\src\main\java\com\bookstore\entity\Inventory.java
2
请完成以下Java代码
public boolean isYesNo() { if (m_displayType == 0) return m_value instanceof Boolean; return DisplayType.YesNo == m_displayType; } // isYesNo /** * Is Value the primary key of row * @return true if value is the PK */ public boolean isPKey() { return m_isPKey; } // isPKey /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_isPageBreak; } // isPageBreak /*************************************************************************/ /** * HashCode * @return hash code */ public int hashCode() { if (m_value == null) return m_columnName.hashCode(); return m_columnName.hashCode() + m_value.hashCode(); } // hashCode /** * Equals * @param compare compare object * @return true if equals */ public boolean equals (Object compare) { if (compare instanceof PrintDataElement) { PrintDataElement pde = (PrintDataElement)compare; if (pde.getColumnName().equals(m_columnName)) { if (pde.getValue() != null && pde.getValue().equals(m_value)) return true; if (pde.getValue() == null && m_value == null) return true; } } return false; } // equals /** * String representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value); if (m_isPKey)
sb.append("(PK)"); return sb.toString(); } // toString /** * Value Has Key * @return true if value has a key */ public boolean hasKey() { return m_value instanceof NamePair; } // hasKey /** * String representation with key info * @return info */ public String toStringX() { if (m_value instanceof NamePair) { NamePair pp = (NamePair)m_value; StringBuffer sb = new StringBuffer(m_columnName); sb.append("(").append(pp.getID()).append(")") .append("=").append(pp.getName()); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } else return toString(); } // toStringX public String getM_formatPattern() { return m_formatPattern; } public void setM_formatPattern(String pattern) { m_formatPattern = pattern; } } // PrintDataElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
1
请完成以下Java代码
public PostingException setDocLine(final DocLine<?> docLine) { _docLine = docLine; resetMessageBuilt(); return this; } public DocLine<?> getDocLine() { return _docLine; } @SuppressWarnings("unused") public PostingException setLogLevel(@NonNull final Level logLevel) { this._logLevel = logLevel; return this; } /** * @return recommended log level to be used when reporting this issue
*/ public Level getLogLevel() { return _logLevel; } @Override public PostingException setParameter( final @NonNull String parameterName, final @Nullable Object parameterValue) { super.setParameter(parameterName, parameterValue); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\PostingException.java
1
请完成以下Java代码
public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL()
{ return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); } @Override public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
IQueryBuilder<I_AD_User_Record_Access> query(@NonNull final RecordAccessQuery query) { final IQueryBuilder<I_AD_User_Record_Access> queryBuilder = queryBL.createQueryBuilder(I_AD_User_Record_Access.class); // // Records final ImmutableSet<TableRecordReference> recordRefs = query.getRecordRefs(); if (!recordRefs.isEmpty()) { final ICompositeQueryFilter<I_AD_User_Record_Access> recordRefsFilter = queryBuilder.addCompositeQueryFilter() .setJoinOr(); for (final TableRecordReference recordRef : recordRefs) { recordRefsFilter.addCompositeQueryFilter() .setJoinAnd() .addEqualsFilter(I_AD_User_Record_Access.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID()) .addEqualsFilter(I_AD_User_Record_Access.COLUMNNAME_Record_ID, recordRef.getRecord_ID()); } } // // Permissions final ImmutableSet<Access> permissions = query.getPermissions(); if (!permissions.isEmpty()) { queryBuilder.addInArrayFilter(I_AD_User_Record_Access.COLUMNNAME_Access, permissions); } // // Principals if (!query.getPrincipals().isEmpty()) { final Set<UserId> userIds = new HashSet<>(); final Set<UserGroupId> userGroupIds = new HashSet<>(); for (final Principal principal : query.getPrincipals()) { if (principal.getUserId() != null) { userIds.add(principal.getUserId()); } else if (principal.getUserGroupId() != null) { userGroupIds.add(principal.getUserGroupId()); } else {
throw new AdempiereException("Invalid principal: " + principal); // shall not happen } } if (!userIds.isEmpty() || !userGroupIds.isEmpty()) { final ICompositeQueryFilter<I_AD_User_Record_Access> principalsFilter = queryBuilder.addCompositeQueryFilter() .setJoinOr(); if (!userIds.isEmpty()) { principalsFilter.addInArrayFilter(I_AD_User_Record_Access.COLUMNNAME_AD_User_ID, userIds); } if (!userGroupIds.isEmpty()) { principalsFilter.addInArrayFilter(I_AD_User_Record_Access.COLUMNNAME_AD_UserGroup_ID, userGroupIds); } } } // // Issuer if (query.getIssuer() != null) { queryBuilder.addEqualsFilter(I_AD_User_Record_Access.COLUMNNAME_PermissionIssuer, query.getIssuer().getCode()); } // return queryBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessRepository.java
1
请完成以下Java代码
public int getDIM_Dimension_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DIM_Dimension_Type_InternalName. @param DIM_Dimension_Type_InternalName DIM_Dimension_Type_InternalName */ @Override public void setDIM_Dimension_Type_InternalName (java.lang.String DIM_Dimension_Type_InternalName) { throw new IllegalArgumentException ("DIM_Dimension_Type_InternalName is virtual column"); } /** Get DIM_Dimension_Type_InternalName. @return DIM_Dimension_Type_InternalName */ @Override public java.lang.String getDIM_Dimension_Type_InternalName () { return (java.lang.String)get_Value(COLUMNNAME_DIM_Dimension_Type_InternalName); } /** Set Interner Name. @param InternalName Generally used to give records a name that can be safely referenced from code. */ @Override public void setInternalName (java.lang.String InternalName) { set_ValueNoCheck (COLUMNNAME_InternalName, InternalName); } /** Get Interner Name. @return Generally used to give records a name that can be safely referenced from code. */ @Override public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set inkl. "leer"-Eintrag. @param IsIncludeEmpty Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll */ @Override public void setIsIncludeEmpty (boolean IsIncludeEmpty) { set_Value (COLUMNNAME_IsIncludeEmpty, Boolean.valueOf(IsIncludeEmpty)); } /** Get inkl. "leer"-Eintrag. @return Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll */ @Override public boolean isIncludeEmpty () { Object oo = get_Value(COLUMNNAME_IsIncludeEmpty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set inkl. "sonstige"-Eintrag. @param IsIncludeOtherGroup Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll */ @Override public void setIsIncludeOtherGroup (boolean IsIncludeOtherGroup) { set_Value (COLUMNNAME_IsIncludeOtherGroup, Boolean.valueOf(IsIncludeOtherGroup)); } /** Get inkl. "sonstige"-Eintrag. @return Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll */ @Override public boolean isIncludeOtherGroup () { Object oo = get_Value(COLUMNNAME_IsIncludeOtherGroup); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec.java
1
请完成以下Java代码
private static IPricingRule createPricingRule(@Nullable final Supplier<IPricingRule> factory) { if (factory == null) { return null; } final IPricingRule pricingRule = factory.get(); if (pricingRule == null) { // shall not happen throw new AdempiereException("Got no pricing rule instance from " + factory); } return pricingRule; } @Override public boolean applies(final IPricingContext pricingCtx, final IPricingResult result) { return includedPricingRules.applies(pricingCtx, result); } /** * Iterates the ctx's {@code pricingCtx}'s priceList's PLVs from a PLV to its respective base-PLV * and applies the sub-pricing-rules until a price is found or all PLvs were tried. */ @Override public void calculate(final IPricingContext pricingCtx, final IPricingResult result) { final ZonedDateTime date = extractPriceDate(pricingCtx); final HashSet<PriceListVersionId> seenPriceListVersionIds = new HashSet<>(); PriceListVersionId currentPriceListVersionId = getPriceListVersionIdEffective(pricingCtx, date); do { if (currentPriceListVersionId != null && !seenPriceListVersionIds.add(currentPriceListVersionId)) { // loop detected, we already tried to compute using that price list version break; } final IEditablePricingContext pricingCtxEffective = pricingCtx.copy(); pricingCtxEffective.setPriceListVersionId(currentPriceListVersionId); includedPricingRules.calculate(pricingCtxEffective, result); if (result.isCalculated()) {
return; } currentPriceListVersionId = getBasePriceListVersionId(currentPriceListVersionId, date); } while (currentPriceListVersionId != null); } @Nullable private PriceListVersionId getPriceListVersionIdEffective(final IPricingContext pricingCtx, @NonNull final ZonedDateTime date) { final I_M_PriceList_Version contextPLV = pricingCtx.getM_PriceList_Version(); if (contextPLV != null) { return contextPLV.isActive() ? PriceListVersionId.ofRepoId(contextPLV.getM_PriceList_Version_ID()) : null; } final I_M_PriceList_Version plv = priceListDAO.retrievePriceListVersionOrNull( pricingCtx.getPriceListId(), date, null // processed ); return plv != null && plv.isActive() ? PriceListVersionId.ofRepoId(plv.getM_PriceList_Version_ID()) : null; } @Nullable private PriceListVersionId getBasePriceListVersionId(@Nullable final PriceListVersionId priceListVersionId, @NonNull final ZonedDateTime date) { if (priceListVersionId == null) { return null; } return priceListDAO.getBasePriceListVersionIdForPricingCalculationOrNull(priceListVersionId, date); } @NonNull private static ZonedDateTime extractPriceDate(@NonNull final IPricingContext pricingCtx) { return pricingCtx.getPriceDate().atStartOfDay(SystemTime.zoneId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\PriceListVersionPricingRule.java
1
请完成以下Java代码
public class BaseAttributeKvEntry implements AttributeKvEntry { private static final long serialVersionUID = -6460767583563159407L; private final long lastUpdateTs; @Valid private final KvEntry kv; private final Long version; public BaseAttributeKvEntry(KvEntry kv, long lastUpdateTs) { this.kv = kv; this.lastUpdateTs = lastUpdateTs; this.version = null; } public BaseAttributeKvEntry(KvEntry kv, long lastUpdateTs, Long version) { this.kv = kv; this.lastUpdateTs = lastUpdateTs; this.version = version; } public BaseAttributeKvEntry(long lastUpdateTs, KvEntry kv) { this(kv, lastUpdateTs); } @Override public String getKey() { return kv.getKey(); } @Override public DataType getDataType() { return kv.getDataType(); } @Override public Optional<String> getStrValue() { return kv.getStrValue(); }
@Override public Optional<Long> getLongValue() { return kv.getLongValue(); } @Override public Optional<Boolean> getBooleanValue() { return kv.getBooleanValue(); } @Override public Optional<Double> getDoubleValue() { return kv.getDoubleValue(); } @Override public Optional<String> getJsonValue() { return kv.getJsonValue(); } @Override public String getValueAsString() { return kv.getValueAsString(); } @Override public Object getValue() { return kv.getValue(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BaseAttributeKvEntry.java
1
请完成以下Java代码
public void setM_ReceiptSchedule_ID (int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, Integer.valueOf(M_ReceiptSchedule_ID)); } @Override public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setPlannedQty (java.math.BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public java.math.BigDecimal getPlannedQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPP_Product_Planning_ID (int PP_Product_Planning_ID)
{ if (PP_Product_Planning_ID < 1) set_Value (COLUMNNAME_PP_Product_Planning_ID, null); else set_Value (COLUMNNAME_PP_Product_Planning_ID, Integer.valueOf(PP_Product_Planning_ID)); } @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public java.math.BigDecimal getQtyOrdered() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Purchase_Detail.java
1
请完成以下Java代码
public void setLengthInCm (final int LengthInCm) { set_Value (COLUMNNAME_LengthInCm, LengthInCm); } @Override public int getLengthInCm() { return get_ValueAsInt(COLUMNNAME_LengthInCm); } @Override public void setM_Package_ID (final int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, M_Package_ID); } @Override public int getM_Package_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_ID); } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); }
@Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); } @Override public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
public int getAD_WF_ActivityResult_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_ActivityResult_ID); } @Override public void setAttributeName (final java.lang.String AttributeName) { set_Value (COLUMNNAME_AttributeName, AttributeName); } @Override public java.lang.String getAttributeName() { return get_ValueAsString(COLUMNNAME_AttributeName); } @Override public void setAttributeValue (final java.lang.String AttributeValue) { set_Value (COLUMNNAME_AttributeValue, AttributeValue); } @Override public java.lang.String getAttributeValue() { return get_ValueAsString(COLUMNNAME_AttributeValue); }
@Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_ActivityResult.java
1
请完成以下Java代码
public class DefaultHUStorageFactory implements IHUStorageFactory { private final IHUStorageDAO storageDAO; public DefaultHUStorageFactory() { this(new HUStorageDAO()); } public DefaultHUStorageFactory(@NonNull final IHUStorageDAO storageDAO) { this.storageDAO = storageDAO; } @Override public IHUStorage getStorage(@NonNull final I_M_HU hu) { return new HUStorage(this, hu); } @Override public IHUItemStorage getStorage(final I_M_HU_Item item) { return new HUItemStorage(this, item); } @Override public IHUStorageDAO getHUStorageDAO() { return storageDAO; } @Override @NonNull public List<IHUProductStorage> getHUProductStorages(@NonNull final List<I_M_HU> hus, final ProductId productId) { return hus.stream() .map(this::getStorage) .map(huStorage -> huStorage.getProductStorageOrNull(productId)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Override public Stream<IHUProductStorage> streamHUProductStorages(@NonNull final List<I_M_HU> hus) { return hus.stream() .map(this::getStorage) .flatMap(IHUStorage::streamProductStorages); } @Override public boolean isSingleProductWithQtyEqualsTo(@NonNull final I_M_HU hu, @NonNull final ProductId productId, @NonNull final Quantity qty) {
return getStorage(hu).isSingleProductWithQtyEqualsTo(productId, qty); } @Override public boolean isSingleProductStorageMatching(@NonNull final I_M_HU hu, @NonNull final ProductId productId) { return getStorage(hu).isSingleProductStorageMatching(productId); } @NonNull public IHUProductStorage getSingleHUProductStorage(@NonNull final I_M_HU hu) { return getStorage(hu).getSingleHUProductStorage(); } @Override public List<IHUProductStorage> getProductStorages(@NonNull final I_M_HU hu) { return getStorage(hu).getProductStorages(); } @Override public IHUProductStorage getProductStorage(@NonNull final I_M_HU hu, @NonNull ProductId productId) { return getStorage(hu).getProductStorage(productId); } @Override public @NonNull ImmutableMap<HuId, Set<ProductId>> getHUProductIds(@NonNull final List<I_M_HU> hus) { final Map<HuId, Set<ProductId>> huId2ProductIds = new HashMap<>(); streamHUProductStorages(hus) .forEach(productStorage -> { final Set<ProductId> productIds = new HashSet<>(); productIds.add(productStorage.getProductId()); huId2ProductIds.merge(productStorage.getHuId(), productIds, (oldValues, newValues) -> { oldValues.addAll(newValues); return oldValues; }); }); return ImmutableMap.copyOf(huId2ProductIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\DefaultHUStorageFactory.java
1
请完成以下Java代码
private boolean isReserved() { return reservationDocRef != null; } public boolean isReservedOnlyFor(@NonNull final AllocablePackageable allocable) { return isReservedOnlyFor(allocable.getReservationRef().orElse(null)); } public boolean isReservedOnlyFor(@Nullable final HUReservationDocRef reservationDocRef) { return this.reservationDocRef != null && HUReservationDocRef.equals(this.reservationDocRef, reservationDocRef); } private void assertSameProductId(final AllocablePackageable allocable) { if (!ProductId.equals(productId, allocable.getProductId())) { throw new AdempiereException("ProductId not matching") .appendParametersToMessage() .setParameter("allocable", allocable) .setParameter("storage", this); }
} private static Quantity computeEffectiveQtyToAllocate( @NonNull final Quantity requestedQtyToAllocate, @NonNull final Quantity qtyFreeToAllocate) { if (requestedQtyToAllocate.signum() <= 0) { return requestedQtyToAllocate.toZero(); } else if (qtyFreeToAllocate.signum() <= 0) { return requestedQtyToAllocate.toZero(); } else { return requestedQtyToAllocate.min(qtyFreeToAllocate); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\allocableHUStorages\VHUAllocableStorage.java
1
请完成以下Java代码
public class Execute { void executeSync() { GraphQlClient graphQlClient = null; String document = ""; // tag::executeSync[] ClientGraphQlResponse response = graphQlClient.document(document).executeSync(); if (!response.isValid()) { // Request failure... <1> } ClientResponseField field = response.field("project"); if (field.getValue() == null) { if (field.getErrors().isEmpty()) { // Optional field set to null... <2> } else { // Field failure... <3> } } Project project = field.toEntity(Project.class); // <4> // end::executeSync[] } void execute() { GraphQlClient graphQlClient = null; String document = ""; // tag::execute[] Mono<Project> projectMono = graphQlClient.document(document) .execute() .map((response) -> { if (!response.isValid()) { // Request failure... <1> }
ClientResponseField field = response.field("project"); if (field.getValue() == null) { if (field.getErrors().isEmpty()) { // Optional field set to null... <2> } else { // Field failure... <3> } } return field.toEntity(Project.class); // <4> }); // end::execute[] } record Project() { } }
repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\requests\execute\Execute.java
1
请完成以下Java代码
public void setC_ReferenceNo_ID (int C_ReferenceNo_ID) { if (C_ReferenceNo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID)); } /** Get Reference No. @return Reference No */ @Override public int getC_ReferenceNo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Doc.java
1
请完成以下Java代码
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代码
public class BodyMassIndex { private String name; private double height; private double weight; public BodyMassIndex(String name, double height, double weight) { this.name = name; this.height = height; this.weight = weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; }
public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double calculate() { double bmi = weight / (height * height); String formattedBmi = String.format("%.2f", bmi); return Double.parseDouble(formattedBmi); } }
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\consoletableoutput\BodyMassIndex.java
1
请完成以下Java代码
public ConditionRestService getConditionRestService() { return super.getConditionRestService(null); } @Path(OptimizeRestService.PATH) public OptimizeRestService getOptimizeRestService() { return super.getOptimizeRestService(null); } @Path(VersionRestService.PATH) public VersionRestService getVersionRestService() { return super.getVersionRestService(null); } @Path(SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService() { return super.getSchemaLogRestService(null);
} @Path(EventSubscriptionRestService.PATH) public EventSubscriptionRestService getEventSubscriptionRestService() { return super.getEventSubscriptionRestService(null); } @Path(TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService() { return super.getTelemetryRestService(null); } @Override protected URI getRelativeEngineUri(String engineName) { // the default engine return URI.create("/"); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorId other = (AuthorId) obj; if (this.age != other.age) {
return false; } if (!Objects.equals(this.name, other.name)) { return false; } return true; } @Override public String toString() { return "AuthorId{" + "name=" + name + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\entity\AuthorId.java
1
请完成以下Java代码
protected List<URL> getProcessesXmlUrls(String[] deploymentDescriptors, AbstractProcessApplication processApplication) { ClassLoader processApplicationClassloader = processApplication.getProcessApplicationClassloader(); List<URL> result = new ArrayList<URL>(); // load all deployment descriptor files using the classloader of the process application for (String deploymentDescriptor : deploymentDescriptors) { Enumeration<URL> processesXmlFileLocations = null; try { processesXmlFileLocations = processApplicationClassloader.getResources(deploymentDescriptor); } catch (IOException e) { throw LOG.exceptionWhileReadingProcessesXml(deploymentDescriptor, e); } while (processesXmlFileLocations.hasMoreElements()) { result.add(processesXmlFileLocations.nextElement()); } } return result; } protected String[] getDeploymentDescriptorLocations(AbstractProcessApplication processApplication) { ProcessApplication annotation = processApplication.getClass().getAnnotation(ProcessApplication.class); if(annotation == null) { return new String[] {ProcessApplication.DEFAULT_META_INF_PROCESSES_XML}; } else { return annotation.deploymentDescriptors(); } }
protected boolean isEmptyFile(URL url) { InputStream inputStream = null; try { inputStream = url.openStream(); return inputStream.available() == 0; } catch (IOException e) { throw LOG.exceptionWhileReadingProcessesXml(url.toString(), e); } finally { IoUtil.closeSilently(inputStream); } } protected ProcessesXml parseProcessesXml(URL url) { final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser(); ProcessesXml processesXml = processesXmlParser.createParse() .sourceUrl(url) .execute() .getProcessesXml(); return processesXml; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\ParseProcessesXmlStep.java
1
请完成以下Java代码
public boolean containsExpression(final Object source) { if (source == null) { return false; } else if (source instanceof String) { return containsExpressionString((String) source); } else if (source instanceof ObjectNode) { return containsExpressionMap(mapper.convertValue(source, MAP_STRING_OBJECT_TYPE)); } else if (source instanceof Map<?, ?>) { return containsExpressionMap((Map<String, ?>) source); } else if (source instanceof List<?>) { return containsExpressionList((List<?>) source); } else { return false; } } private boolean containsExpressionString(final String sourceString) { return EXPRESSION_PATTERN.matcher(sourceString).find(); } private boolean containsExpressionMap(final Map<String, ?> source) { for (Entry<String, ?> entry : source.entrySet()) {
if (containsExpression(entry.getValue())) { return true; } } return false; } private boolean containsExpressionList(List<?> source) { for (Object item : source) { if (containsExpression(item)) { return true; } } return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ExpressionResolver.java
1
请完成以下Java代码
public LockManager getLockManager(String lockName) { return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey()); } @Override public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution)); } @Override public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) { return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize)); } @Override public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) { return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId)); } @Override public void deleteEventLogEntry(long logNr) { commandExecutor.execute(new DeleteEventLogEntry(logNr)); } @Override public ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder() { return new ExternalWorkerJobAcquireBuilderImpl(commandExecutor, configuration.getJobServiceConfiguration()); } @Override public ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId) { return new ExternalWorkerJobFailureBuilderImpl(externalJobId, workerId, commandExecutor, configuration.getJobServiceConfiguration());
} @Override public ExternalWorkerCompletionBuilder createExternalWorkerCompletionBuilder(String externalJobId, String workerId) { return new ExternalWorkerCompletionBuilderImpl(commandExecutor, externalJobId, workerId, configuration.getJobServiceConfiguration()); } @Override public void unacquireExternalWorkerJob(String jobId, String workerId) { commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration())); } @Override public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) { commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration())); } @Override public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) { return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager()); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ManagementServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderBasedAggregation { @NonNull private final OrderBasedAggregationKey key; private boolean partiallyPickedBefore = false; @NonNull private final PickingJobCandidateProductsCollector productsCollector = new PickingJobCandidateProductsCollector(); @NonNull private final HashSet<ShipmentScheduleAndJobScheduleId> scheduleIds = new HashSet<>(); public OrderBasedAggregation(@NonNull final OrderBasedAggregationKey key) { this.key = key; } public void add(@NonNull final ScheduledPackageable item) { if (item.isPartiallyPickedOrDelivered()) { partiallyPickedBefore = true; } productsCollector.collect(item); scheduleIds.add(item.getId()); }
public PickingJobCandidate toPickingJobCandidate() { return PickingJobCandidate.builder() .aggregationType(PickingJobAggregationType.SALES_ORDER) .preparationDate(key.getPreparationDate()) .salesOrderId(key.getSalesOrderId()) .salesOrderDocumentNo(key.getSalesOrderDocumentNo()) .customerName(key.getCustomerName()) .deliveryBPLocationId(key.getDeliveryBPLocationId()) .warehouseTypeId(key.getWarehouseTypeId()) .partiallyPickedBefore(partiallyPickedBefore) .products(productsCollector.toProducts()) .scheduleIds(ShipmentScheduleAndJobScheduleIdSet.ofCollection(scheduleIds)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\retrieve\OrderBasedAggregation.java
2
请完成以下Java代码
private boolean matches( @NonNull final IdentifierString contactIdentifier, @NonNull final BPartnerContact contact) { switch (contactIdentifier.getType()) { case EXTERNAL_ID: return contactIdentifier.asExternalId().equals(contact.getExternalId()); case GLN: throw new AdempiereException("IdentifierStrings with type=" + Type.GLN + " are not supported for contacts") .appendParametersToMessage() .setParameter("contactIdentifier", contactIdentifier); case METASFRESH_ID: return contactIdentifier.asMetasfreshId().equals(MetasfreshId.of(contact.getId())); case VALUE: return contactIdentifier.asValue().equals(contact.getValue()); default: throw new AdempiereException("Unexpected type; contactIdentifier=" + contactIdentifier); } } @Nullable public static InvoiceRule getInvoiceRule(@Nullable final JsonInvoiceRule jsonInvoiceRule) { if (jsonInvoiceRule == null) { return null;
} switch (jsonInvoiceRule) { case AfterDelivery: return InvoiceRule.AfterDelivery; case CustomerScheduleAfterDelivery: return InvoiceRule.CustomerScheduleAfterDelivery; case Immediate: return InvoiceRule.Immediate; case OrderCompletelyDelivered: return InvoiceRule.OrderCompletelyDelivered; case AfterPick: return InvoiceRule.AfterPick; default: throw new AdempiereException("Unsupported JsonInvliceRule " + jsonInvoiceRule); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\BPartnerCompositeRestUtils.java
1
请完成以下Java代码
private BPartnerBankAccountId getBPartnerBankAccountId(@NonNull final BPartnerId bPartnerId) { final I_C_BP_BankAccount sourceBPartnerBankAccount = bankAccountDAO.retrieveDefaultBankAccountInTrx(bPartnerId) .orElseThrow(() -> new AdempiereException("No BPartnerBankAccount found for BPartnerId") .appendParametersToMessage() .setParameter("BPartnerId", bPartnerId)); return BPartnerBankAccountId.ofRepoId(BPartnerId.toRepoId(bPartnerId), sourceBPartnerBankAccount.getC_BP_BankAccount_ID()); } @NonNull private DocTypeId getDocTypeIdByType( @NonNull final String type, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { final DocTypeQuery docTypeQuery = DocTypeQuery.builder() .docBaseType(type) .adClientId(clientId.getRepoId()) .adOrgId(orgId.getRepoId()) .build(); return docTypeDAO.getDocTypeId(docTypeQuery); } private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier) { final IdentifierString.Type type = bpartnerIdentifier.getType(); final BPartnerQuery query; switch (type) { case METASFRESH_ID: query = BPartnerQuery.builder() .bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId)) .build(); break; case EXTERNAL_ID: query = BPartnerQuery.builder() .externalId(bpartnerIdentifier.asExternalId()) .build(); break; case GLN: query = BPartnerQuery.builder()
.gln(bpartnerIdentifier.asGLN()) .build(); break; case VALUE: query = BPartnerQuery.builder() .bpartnerValue(bpartnerIdentifier.asValue()) .build(); break; default: throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier); } return query; } @VisibleForTesting public String buildDocumentNo(@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) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\remittanceadvice\impl\CreateRemittanceAdviceService.java
1
请完成以下Java代码
public class LimitedFileDownloadWebClient { private LimitedFileDownloadWebClient() { } public static long fetch(WebClient client, String destination) throws IOException { Mono<byte[]> mono = client.get() .retrieve() .bodyToMono(byte[].class) .onErrorMap(RuntimeException::new); byte[] bytes = mono.block(); Path path = Paths.get(destination); Files.write(path, bytes); return bytes.length; } public static void main(String... args) throws IOException { String baseUrl = args[0]; String destination = args[1]; WebClient client = WebClient.builder() .baseUrl(baseUrl) .exchangeStrategies(useMaxMemory())
.build(); long bytes = fetch(client, destination); System.out.printf("downloaded %d bytes to %s", bytes, destination); } public static ExchangeStrategies useMaxMemory() { long totalMemory = Runtime.getRuntime() .maxMemory(); return ExchangeStrategies.builder() .codecs(configurer -> configurer.defaultCodecs() .maxInMemorySize((int) totalMemory)) .build(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\streamlargefile\client\LimitedFileDownloadWebClient.java
1
请完成以下Java代码
protected String doIt() { final BatchProcessBOMCostCalculatorRepository bomCostCalculatorRepo = BatchProcessBOMCostCalculatorRepository.builder() .clientId(clientId) .orgId(orgId) .acctSchema(acctSchema) .costTypeId(costTypeId) .costingMethod(costingMethod) .build(); final BOMCostCalculator calculator = BOMCostCalculator.builder() .repository(bomCostCalculatorRepo) .build(); //@TODO the process is not used in WEB UI, need to be updated in necessary /* final int maxLowLevel = getMaxLowLevel(); for (int lowLevel = maxLowLevel; lowLevel >= 0; lowLevel--) { for (final ProductId productId : getProductIdsByLowLevel(lowLevel)) { calculator.rollup(productId); } }*/ throw new UnsupportedOperationException("Process not implemented"); } //@TODO the process is not used in WEB UI, need to be updated in necessary /* private int getMaxLowLevel() { return createProductsQuery() .addNotNull(I_M_Product.COLUMNNAME_LowLevel) .create() .maxInt(I_M_Product.COLUMNNAME_LowLevel); } private Set<ProductId> getProductIdsByLowLevel(final int lowLevel) { return createProductsQuery() .addEqualsFilter(I_M_Product.COLUMN_LowLevel, lowLevel) .create() .idsAsSet(ProductId::ofRepoId); }*/ private IQueryBuilder<I_M_Product> createProductsQuery() { final IQueryBuilder<I_M_Product> queryBuilder = queryBL.createQueryBuilder(I_M_Product.class) .addOnlyActiveRecordsFilter()
.orderBy(I_M_Product.COLUMN_M_Product_ID) // just to have a predictable order .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId) .addEqualsFilter(I_M_Product.COLUMNNAME_IsBOM, true); if (productId != null) { queryBuilder.addEqualsFilter(I_M_Product.COLUMN_M_Product_ID, productId); } else if (productCategoryId != null) { queryBuilder.addEqualsFilter(I_M_Product.COLUMNNAME_M_Product_Category_ID, productCategoryId); } if (productId == null && productType != null) { queryBuilder.addEqualsFilter(I_M_Product.COLUMNNAME_ProductType, productType); } // return queryBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\RollupBillOfMaterial.java
1
请完成以下Java代码
public class OrderLineProductQtyGridRowBuilder implements IGridTabRowBuilder { private static final transient Logger logger = LogManager.getLogger(OrderLineProductQtyGridRowBuilder.class); private int productId; private BigDecimal qty; public OrderLineProductQtyGridRowBuilder() { super(); } @Override public void setSource(final Object model) { if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_Order.class)) { logger.trace("Skip setting the source because model does not apply: {}", model); return; } final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class); final int productId = order.getM_Product_ID(); final BigDecimal qty = order.getQty_FastInput(); setSource(productId, qty); } public void setSource(final int productId, final BigDecimal qty) { this.productId = productId; this.qty = qty; } @Override public boolean isValid() { if (productId <= 0) { return false; } if (qty == null || qty.signum() == 0) { return false; } return true; } @Override public void apply(final Object model)
{ if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class)) { logger.debug("Skip applying because it's not an order line: {}", model); return; } final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class); apply(orderLine); } private void apply(final I_C_OrderLine orderLine) { // Note: There is only the product's stocking-UOM.,.the C_UOM can't be changed in the product info UI. // That's why we don't need to convert orderLine.setQtyEntered(qty); orderLine.setQtyOrdered(qty); } @Override public boolean isCreateNewRecord() { return true; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\OrderLineProductQtyGridRowBuilder.java
1
请完成以下Java代码
private IStatementLineWrapper buildBatchReportEntryWrapper(@NonNull final ReportEntry2 reportEntry) { return BatchReportEntry2Wrapper.builder() .currencyRepository(getCurrencyRepository()) .entry(reportEntry) .build(); } @NonNull private Optional<CashBalance3> findOPBDCashBalance() { return accountStatement2.getBal() .stream() .filter(AccountStatement2Wrapper::isOPBDCashBalance) .findFirst(); } @NonNull private Optional<CashBalance3> findPRCDCashBalance() { return accountStatement2.getBal() .stream() .filter(AccountStatement2Wrapper::isPRCDCashBalance) .findFirst();
} private static boolean isPRCDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.PRCD.equals(balanceTypeCode); } private static boolean isOPBDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.OPBD.equals(balanceTypeCode); } private static boolean isCRDTCashBalance(@NonNull final CashBalance3 cashBalance) { return CRDT.equals(cashBalance.getCdtDbtInd()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\AccountStatement2Wrapper.java
1
请完成以下Java代码
public static List<Person> search(List<Person> people, String name, Optional<Integer> age) { // Null checks for people and name return people.stream() .filter(p -> p.getName().equals(name)) .filter(p -> p.getAge().get() >= age.orElse(0)) .collect(Collectors.toList()); } public static List<Person> search(List<Person> people, String name, Integer age) { // Null checks for people and name final Integer ageFilter = age != null ? age : 0; return people.stream() .filter(p -> p.getName().equals(name)) .filter(p -> p.getAge().get() >= ageFilter) .collect(Collectors.toList()); } public static List<Person> search(List<Person> people, String name) {
return doSearch(people, name, 0); } public static List<Person> search(List<Person> people, String name, int age) { return doSearch(people, name, age); } private static List<Person> doSearch(List<Person> people, String name, int age) { // Null checks for people and name return people.stream() .filter(p -> p.getName().equals(name)) .filter(p -> p.getAge().get().intValue() >= age) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\optional\Person.java
1
请完成以下Java代码
public double getY() { return y; } public void setY(double y) { this.y = y; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public Boolean getExpanded() { return expanded; } public void setExpanded(Boolean expanded) { this.expanded = expanded; } public BaseElement getElement() { return element; } public void setElement(BaseElement element) { this.element = element; } @Override public int getXmlRowNumber() { return xmlRowNumber; } @Override public void setXmlRowNumber(int xmlRowNumber) { this.xmlRowNumber = xmlRowNumber; } @Override public int getXmlColumnNumber() { return xmlColumnNumber; } @Override public void setXmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; } public double getRotation() { return rotation; } public void setRotation(double rotation) { this.rotation = rotation; }
public boolean equals(GraphicInfo ginfo) { if (this.getX() != ginfo.getX()) { return false; } if (this.getY() != ginfo.getY()) { return false; } if (this.getHeight() != ginfo.getHeight()) { return false; } if (this.getWidth() != ginfo.getWidth()) { return false; } if (this.getRotation() != ginfo.getRotation()) { return false; } // check for zero value in case we are comparing model value to BPMN DI value // model values do not have xml location information if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) { return false; } if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) { return false; } // only check for elements that support this value if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\GraphicInfo.java
1
请完成以下Java代码
public void setIsReplicated (boolean IsReplicated) { set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated)); } /** Get Replicated. @return The data is successfully replicated */ public boolean isReplicated () { Object oo = get_Value(COLUMNNAME_IsReplicated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Run.java
1
请完成以下Java代码
public long size() { return cache.size(); } // size /** * @see java.util.Map#values() */ public Collection<V> values() { return cache.asMap().values(); } // values @Override protected final void finalize() throws Throwable { // NOTE: to avoid memory leaks we need to programatically clear our internal state try (final IAutoCloseable ignored = CacheMDC.putCache(this)) { logger.debug("Running finalize"); cache.invalidateAll(); } } public CCacheStats stats() { final CacheStats guavaStats = cache.stats();
return CCacheStats.builder() .cacheId(cacheId) .name(cacheName) .labels(labels) .config(config) .debugAcquireStacktrace(debugAcquireStacktrace) // .size(cache.size()) .hitCount(guavaStats.hitCount()) .missCount(guavaStats.missCount()) .build(); } private boolean isNoCache() { return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java
1
请完成以下Java代码
public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, @Nullable final ViewProfileId profileId) { Check.errorUnless(MaterialCockpitUtil.WINDOWID_MaterialCockpitView.equals(windowId), "The parameter windowId needs to be {}, but is {} instead; viewDataType={}; ", MaterialCockpitUtil.WINDOWID_MaterialCockpitView, windowId, viewDataType); final String commaSeparatedFieldNames = sysConfigBL.getValue(SYSCFG_Layout, (String)null); final boolean displayIncludedRows = sysConfigBL.getBooleanValue(SYSCFG_DisplayIncludedRows, true); final ViewLayout.Builder viewlayOutBuilder = ViewLayout.builder() .setWindowId(windowId) .setHasTreeSupport(displayIncludedRows) .setTreeCollapsible(true) .setTreeExpandedDepth(ViewLayout.TreeExpandedDepth_AllCollapsed) .setAllowOpeningRowDetails(false) .addElementsFromViewRowClass(MaterialCockpitRow.class, viewDataType, commaSeparatedFieldNames) .setFilters(materialCockpitFilters.getFilterDescriptors().getAll()); return viewlayOutBuilder.build(); } private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final AdProcessId processId = processDAO.retrieveProcessIdByClass(processClass); if (processId == null) { throw new AdempiereException("No processId found for " + processClass); } return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions) .build();
} private boolean retrieveIsIncludePerPlantDetailRows() { return Services.get(ISysConfigBL.class).getBooleanValue( MaterialCockpitUtil.SYSCONFIG_INCLUDE_PER_PLANT_DETAIL_ROWS, false, Env.getAD_Client_ID(), Env.getAD_Org_ID(Env.getCtx())); } private MaterialCockpitDetailsRowAggregation retrieveDetailsRowAggregation() { if (retrieveIsIncludePerPlantDetailRows()) { return MaterialCockpitDetailsRowAggregation.PLANT; } return MaterialCockpitDetailsRowAggregation.getDefault(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitViewFactory.java
1
请完成以下Java代码
public final class MRole extends X_AD_Role { /** * */ private static final long serialVersionUID = -6722616714353225616L; @SuppressWarnings("unused") public MRole(final Properties ctx, final int AD_Role_ID, final String trxName) { super(ctx, AD_Role_ID, trxName); if (is_new()) { // setName (null); setIsCanExport(true); setIsCanReport(true); setIsManual(false); setIsPersonalAccess(false); setIsPersonalLock(false);
setIsShowAcct(false); setIsAccessAllOrgs(false); setUserLevel(USERLEVEL_Organization); setPreferenceType(PREFERENCETYPE_Organization); setIsChangeLog(false); setOverwritePriceLimit(false); setIsUseUserOrgAccess(false); setMaxQueryRecords(0); setConfirmQueryRecords(0); } } @SuppressWarnings("unused") public MRole(final Properties ctx, final ResultSet rs, final String trxName) { super(ctx, rs, trxName); } } // MRole
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRole.java
1
请完成以下Java代码
public String getNb() { return nb; } /** * Sets the value of the nb property. * * @param value * allowed object is * {@link String } * */ public void setNb(String value) { this.nb = value; } /** * Gets the value of the rltdDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRltdDt() { return rltdDt; } /** * Sets the value of the rltdDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRltdDt(XMLGregorianCalendar value) { this.rltdDt = value;
} /** * Gets the value of the lineDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the lineDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLineDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentLineInformation1 } * * */ public List<DocumentLineInformation1> getLineDtls() { if (lineDtls == null) { lineDtls = new ArrayList<DocumentLineInformation1>(); } return this.lineDtls; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\ReferredDocumentInformation7.java
1
请在Spring Boot框架中完成以下Java代码
public class ChartOfAccountsService { private final IADTableDAO adTreeDAO = Services.get(IADTableDAO.class); private final ChartOfAccountsRepository chartOfAccountsRepository; public ChartOfAccountsService( @NonNull final ChartOfAccountsRepository chartOfAccountsRepository) { this.chartOfAccountsRepository = chartOfAccountsRepository; } public static ChartOfAccountsService newInstanceForUnitTesting() { Adempiere.assertUnitTestMode(); return new ChartOfAccountsService(new ChartOfAccountsRepository()); } public ChartOfAccounts getById(@NonNull final ChartOfAccountsId chartOfAccountsId) { return chartOfAccountsRepository.getById(chartOfAccountsId); } public List<ChartOfAccounts> getByIds(@NonNull final Set<ChartOfAccountsId> chartOfAccountsIds) { return chartOfAccountsRepository.getByIds(chartOfAccountsIds); } public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { return chartOfAccountsRepository.getByName(chartOfAccountsName, clientId, orgId); } public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId) { return chartOfAccountsRepository.getByTreeId(treeId); } public ChartOfAccounts createChartOfAccounts(@NonNull final ChartOfAccountsCreateRequest request)
{ final AdTreeId chartOfAccountsTreeId = createChartOfAccountsTree(request.getName(), request.getOrgId()); return chartOfAccountsRepository.createChartOfAccounts(request.getName(), request.getClientId(), request.getOrgId(), chartOfAccountsTreeId); } private AdTreeId createChartOfAccountsTree(@NonNull final String name, @NonNull final OrgId orgId) { final I_AD_Tree tree = InterfaceWrapperHelper.newInstance(I_AD_Tree.class); tree.setAD_Table_ID(adTreeDAO.retrieveTableId(I_C_ElementValue.Table_Name)); tree.setName(name); tree.setTreeType(X_AD_Tree.TREETYPE_ElementValue); tree.setIsAllNodes(true); tree.setAD_Org_ID(orgId.getRepoId()); InterfaceWrapperHelper.save(tree); return AdTreeId.ofRepoId(tree.getAD_Tree_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsService.java
2
请完成以下Java代码
public static class Sbom { /** * Location to the SBOM. If null, the location will be auto-detected. */ private @Nullable String location; /** * Media type of the SBOM. If null, the media type will be auto-detected. */ private @Nullable MimeType mediaType; public @Nullable String getLocation() { return this.location; }
public void setLocation(@Nullable String location) { this.location = location; } public @Nullable MimeType getMediaType() { return this.mediaType; } public void setMediaType(@Nullable MimeType mediaType) { this.mediaType = mediaType; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomProperties.java
1
请完成以下Java代码
private static String extractCsvFieldDelimiter(final I_DATEV_ExportFormat formatPO) { String delimiter = formatPO.getCSVFieldDelimiter(); if (delimiter == null) { return ""; } return delimiter .replace("\\t", "\t") .replace("\\r", "\r") .replace("\\n", "\n"); } private static String extractCsvFieldQuote(final I_DATEV_ExportFormat formatPO) {
final String quote = formatPO.getCSVFieldQuote(); if (quote == null) { return ""; } else if ("-".equals(quote)) { return ""; } else { return quote; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVExportFormatRepository.java
1
请完成以下Java代码
public DmnDecisionTableResult evaluateDecisionTableById(String decisionDefinitionId, Map<String, Object> variables) { return evaluateDecisionTableById(decisionDefinitionId) .variables(variables) .evaluate(); } public DmnDecisionTableResult evaluateDecisionTableByKey(String decisionDefinitionKey, Map<String, Object> variables) { return evaluateDecisionTableByKey(decisionDefinitionKey) .variables(variables) .evaluate(); } public DmnDecisionTableResult evaluateDecisionTableByKeyAndVersion(String decisionDefinitionKey, Integer version, Map<String, Object> variables) { return evaluateDecisionTableByKey(decisionDefinitionKey) .version(version) .variables(variables) .evaluate(); } public DecisionEvaluationBuilder evaluateDecisionTableByKey(String decisionDefinitionKey) {
return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableByKey(commandExecutor, decisionDefinitionKey); } public DecisionEvaluationBuilder evaluateDecisionTableById(String decisionDefinitionId) { return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableById(commandExecutor, decisionDefinitionId); } public DecisionsEvaluationBuilder evaluateDecisionByKey(String decisionDefinitionKey) { return DecisionEvaluationBuilderImpl.evaluateDecisionByKey(commandExecutor, decisionDefinitionKey); } public DecisionsEvaluationBuilder evaluateDecisionById(String decisionDefinitionId) { return DecisionEvaluationBuilderImpl.evaluateDecisionById(commandExecutor, decisionDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DecisionServiceImpl.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getCountrycode() { return countrycode; } public void setCountrycode(String countrycode) { this.countrycode = countrycode == null ? null : countrycode.trim(); }
public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district == null ? null : district.trim(); } public Integer getPopulation() { return population; } public void setPopulation(Integer population) { this.population = population; } }
repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\City.java
1
请在Spring Boot框架中完成以下Java代码
HazelcastPropertiesCustomizer hazelcastPropertiesCustomizer(ObjectProvider<HazelcastInstance> hazelcastInstance, CacheProperties cacheProperties) { return new HazelcastPropertiesCustomizer(hazelcastInstance.getIfUnique(), cacheProperties); } static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer { private final @Nullable HazelcastInstance hazelcastInstance; private final CacheProperties cacheProperties; HazelcastPropertiesCustomizer(@Nullable HazelcastInstance hazelcastInstance, CacheProperties cacheProperties) { this.hazelcastInstance = hazelcastInstance; this.cacheProperties = cacheProperties; } @Override public void customize(Properties properties) { Resource configLocation = this.cacheProperties .resolveConfigLocation(this.cacheProperties.getJcache().getConfig()); if (configLocation != null) { // Hazelcast does not use the URI as a mean to specify a custom config.
properties.setProperty("hazelcast.config.location", toUri(configLocation).toString()); } else if (this.hazelcastInstance != null) { properties.put("hazelcast.instance.itself", this.hazelcastInstance); } } private static URI toUri(Resource config) { try { return config.getURI(); } catch (IOException ex) { throw new IllegalArgumentException("Could not get URI from " + config, ex); } } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\HazelcastJCacheCustomizationConfiguration.java
2
请完成以下Java代码
public abstract class PackingHUsViewBasedProcess extends HUEditorProcessTemplate { private final transient IQueryBL queryBL = Services.get(IQueryBL.class); protected final List<I_M_HU> retrieveEligibleHUs() { final Set<HuId> huIds = streamEligibleHURows() .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); Check.assumeNotEmpty(huIds, "huIds is not empty"); // shall not happen final List<I_M_HU> hus = queryBL .createQueryBuilder(I_M_HU.class) .addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds)
.addOnlyActiveRecordsFilter() .create() .list(I_M_HU.class); Check.assumeNotEmpty(hus, "hus is not empty"); // shall not happen return hus; } protected final Stream<HUEditorRow> streamEligibleHURows() { return streamSelectedRows(HUEditorRowFilter.select(Select.ONLY_TOPLEVEL)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\PackingHUsViewBasedProcess.java
1
请完成以下Java代码
public void delete() { Context.getCommandContext() .getDbSqlSession() .delete(this); // Also delete the job's exception and the custom values byte array exceptionByteArrayRef.delete(); customValuesByteArrayRef.delete(); // remove link to execution if (executionId != null) { ExecutionEntity execution = Context.getCommandContext() .getExecutionEntityManager() .findExecutionById(executionId); execution.removeJob(this); } if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } @Override public void setExecution(ExecutionEntity execution) { super.setExecution(execution); execution.addJob(this); } @Override @SuppressWarnings("unchecked") public Object getPersistentState() { Map<String, Object> persistentState = (Map<String, Object>) super.getPersistentState(); persistentState.put("lockOwner", lockOwner); persistentState.put("lockExpirationTime", lockExpirationTime); return persistentState; }
public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } @Override public String toString() { return "JobEntity [id=" + id + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntity.java
1
请完成以下Java代码
public void stateChanged(ChangeEvent e) { if (tabbedPane.getSelectedIndex() == 1) // switch to HTML textPane.setText(textArea.getText()); } // stateChanged @Override public void keyTyped (KeyEvent e) { } @Override public void keyPressed (KeyEvent e) { } @Override public void keyReleased (KeyEvent e) { updateStatusBar(); } // metas: begin public Editor(Frame frame, String header, String text, boolean editable, int maxSize, GridField gridField) { this(frame, header, text, editable, maxSize); BoilerPlateMenu.createFieldMenu(textArea, null, gridField); } private static final GridField getGridField(Container c) { if (c == null) { return null; }
GridField field = null; if (c instanceof VEditor) { VEditor editor = (VEditor)c; field = editor.getField(); } else { try { field = (GridField)c.getClass().getMethod("getField").invoke(c); } catch (Exception e) { final AdempiereException ex = new AdempiereException("Cannot get GridField from " + c, e); log.warn(ex.getLocalizedMessage(), ex); } } return field; } // metas: end } // Editor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Editor.java
1
请完成以下Java代码
public static GlobalQRCode ofNullableString(@Nullable final String string) { return StringUtils.trimBlankToNullAndMap(string, GlobalQRCode::ofString); } public static GlobalQRCode ofString(@NonNull final String string) { return parse(string).orThrow(); } public static GlobalQRCode ofBase64Encoded(@NonNull final String string) { final byte[] bytes = BaseEncoding.base64().decode(string); return ofString(new String(bytes, StandardCharsets.UTF_8)); } public static GlobalQRCodeParseResult parse(@NonNull final String string) { String remainingString = string; // // Extract type final GlobalQRCodeType type; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(1): " + string); } type = GlobalQRCodeType.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Extract version final GlobalQRCodeVersion version; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(2): " + string); } version = GlobalQRCodeVersion.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Payload final String payloadAsJson = remainingString; // return GlobalQRCodeParseResult.ok(builder()
.type(type) .version(version) .payloadAsJson(payloadAsJson) .build()); } public <T> T getPayloadAs(@NonNull final Class<T> type) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(payloadAsJson, type); } catch (JsonProcessingException e) { throw Check.mkEx("Failed converting payload to `" + type + "`: " + payloadAsJson, e); } } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return type.toJson() + SEPARATOR + version + SEPARATOR + payloadAsJson; } public static boolean equals(@Nullable GlobalQRCode o1, @Nullable GlobalQRCode o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCode.java
1
请完成以下Java代码
public class SysPermission implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId(type = IdType.ASSIGN_ID) private String id; /** * 父id */ private String parentId; /** * 菜单名称 */ private String name; /** * 菜单权限编码,例如:“sys:schedule:list,sys:schedule:info”,多个逗号隔开 */ private String perms; /** * 权限策略1显示2禁用 */ private String permsType; /** * 菜单图标 */ private String icon; /** * 组件 */ private String component; /** * 组件名字 */ private String componentName; /** * 路径 */ private String url; /** * 一级菜单跳转地址 */ private String redirect; /** * 菜单排序 */ private Double sortNo; /** * 类型(0:一级菜单;1:子菜单 ;2:按钮权限) */ @Dict(dicCode = "menu_type") private Integer menuType; /** * 是否叶子节点: 1:是 0:不是 */ @TableField(value="is_leaf") private boolean leaf; /** * 是否路由菜单: 0:不是 1:是(默认值1) */ @TableField(value="is_route") private boolean route; /** * 是否缓存页面: 0:不是 1:是(默认值1) */ @TableField(value="keep_alive") private boolean keepAlive; /** * 描述 */ private String description; /** * 创建人 */ private String createBy; /** * 删除状态 0正常 1已删除 */ private Integer delFlag; /** * 是否配置菜单的数据权限 1是0否 默认0 */ private Integer ruleFlag; /**
* 是否隐藏路由菜单: 0否,1是(默认值0) */ private boolean hidden; /** * 是否隐藏Tab: 0否,1是(默认值0) */ private boolean hideTab; /** * 创建时间 */ private Date createTime; /** * 更新人 */ private String updateBy; /** * 更新时间 */ private Date updateTime; /**按钮权限状态(0无效1有效)*/ private java.lang.String status; /**alwaysShow*/ private boolean alwaysShow; /*update_begin author:wuxianquan date:20190908 for:实体增加字段 */ /** 外链菜单打开方式 0/内部打开 1/外部打开 */ private boolean internalOrExternal; /*update_end author:wuxianquan date:20190908 for:实体增加字段 */ public SysPermission() { } public SysPermission(boolean index) { if(index) { this.id = "9502685863ab87f0ad1134142788a385"; this.name = DefIndexConst.DEF_INDEX_NAME; this.component = DefIndexConst.DEF_INDEX_COMPONENT; this.componentName = "dashboard-analysis"; this.url = DefIndexConst.DEF_INDEX_URL; this.icon="home"; this.menuType=0; this.sortNo=0.0; this.ruleFlag=0; this.delFlag=0; this.alwaysShow=false; this.route=true; this.keepAlive=true; this.leaf=true; this.hidden=false; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysPermission.java
1
请完成以下Java代码
public class DecisionTaskJsonConverter extends BaseBpmnJsonConverter implements DecisionTableAwareConverter { protected Map<String, String> decisionTableMap; 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 class KafkaConsumerRecordInformationPayloadExtractor<T> implements InboundEventInfoAwarePayloadExtractor<T> { @Override public Collection<EventPayloadInstance> extractPayload(EventModel eventModel, FlowableEventInfo<T> event) { InboundChannelModel inboundChannel = event.getInboundChannel(); Object rawEvent = event.getRawEvent(); if (inboundChannel instanceof KafkaInboundChannelModel && rawEvent instanceof ConsumerRecord) { return extractPayload(eventModel, (KafkaInboundChannelModel) inboundChannel, (ConsumerRecord<?, ?>) rawEvent); } return Collections.emptyList(); } protected Collection<EventPayloadInstance> extractPayload(EventModel eventModel, KafkaInboundChannelModel inboundChannel, ConsumerRecord<?, ?> consumerRecord) { Collection<EventPayloadInstance> payloadInstances = new ArrayList<>(); addPayloadIfAvailable(inboundChannel.getTopicOutputName(), eventModel, consumerRecord::topic, payloadInstances::add);
addPayloadIfAvailable(inboundChannel.getPartitionOutputName(), eventModel, consumerRecord::partition, payloadInstances::add); addPayloadIfAvailable(inboundChannel.getOffsetOutputName(), eventModel, consumerRecord::offset, payloadInstances::add); return payloadInstances; } protected void addPayloadIfAvailable(String payloadName, EventModel model, Supplier<?> valueSupplier, Consumer<EventPayloadInstance> payloadInstanceConsumer) { if (StringUtils.isNotBlank(payloadName)) { EventPayload payloadDefinition = model.getPayload(payloadName); if (payloadDefinition != null) { payloadInstanceConsumer.accept(new EventPayloadInstanceImpl(payloadDefinition, valueSupplier.get())); } } } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\payload\KafkaConsumerRecordInformationPayloadExtractor.java
1
请完成以下Java代码
protected POInfo initPO(final Properties ctx) { return POInfo.getPOInfo(Table_Name); } @Override public void setBase_url (final String Base_url) { set_Value (COLUMNNAME_Base_url, Base_url); } @Override public String getBase_url() { return get_ValueAsString(COLUMNNAME_Base_url); } @Override public void setConnection_timeout (final int Connection_timeout) { set_Value (COLUMNNAME_Connection_timeout, Connection_timeout); } @Override public int getConnection_timeout() { return get_ValueAsInt(COLUMNNAME_Connection_timeout); } @Override public void setPostgREST_ResultDirectory (final String PostgREST_ResultDirectory) { set_Value (COLUMNNAME_PostgREST_ResultDirectory, PostgREST_ResultDirectory); } @Override public String getPostgREST_ResultDirectory() { return get_ValueAsString(COLUMNNAME_PostgREST_ResultDirectory); }
@Override public void setRead_timeout (final int Read_timeout) { set_Value (COLUMNNAME_Read_timeout, Read_timeout); } @Override public int getRead_timeout() { return get_ValueAsInt(COLUMNNAME_Read_timeout); } @Override public void setS_PostgREST_Config_ID (final int S_PostgREST_Config_ID) { if (S_PostgREST_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, S_PostgREST_Config_ID); } @Override public int getS_PostgREST_Config_ID() { return get_ValueAsInt(COLUMNNAME_S_PostgREST_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_PostgREST_Config.java
1
请完成以下Java代码
public abstract class AbstractEntityNoRevision implements Entity { protected String id; protected boolean isInserted; protected boolean isUpdated; protected boolean isDeleted; @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public boolean isInserted() { return isInserted; }
public void setInserted(boolean isInserted) { this.isInserted = isInserted; } public boolean isUpdated() { return isUpdated; } public void setUpdated(boolean isUpdated) { this.isUpdated = isUpdated; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntityNoRevision.java
1
请完成以下Java代码
public java.lang.String getIncludeLogic () { return (java.lang.String)get_Value(COLUMNNAME_IncludeLogic); } /** * Type AD_Reference_ID=540532 * Reference name: C_AggregationItem_Type */ public static final int TYPE_AD_Reference_ID=540532; /** Column = COL */ public static final String TYPE_Column = "COL"; /** IncludedAggregation = INC */ public static final String TYPE_IncludedAggregation = "INC"; /** Attribute = ATR */ public static final String TYPE_Attribute = "ATR"; /** Set Art. @param Type
Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_AggregationItem.java
1
请完成以下Java代码
public class X_C_ConversionRate_Rule extends org.compiere.model.PO implements I_C_ConversionRate_Rule, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1651076087L; /** Standard Constructor */ public X_C_ConversionRate_Rule (final Properties ctx, final int C_ConversionRate_Rule_ID, @Nullable final String trxName) { super (ctx, C_ConversionRate_Rule_ID, trxName); } /** Load Constructor */ public X_C_ConversionRate_Rule (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_ConversionRate_Rule_ID (final int C_ConversionRate_Rule_ID) { if (C_ConversionRate_Rule_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, C_ConversionRate_Rule_ID); } @Override public int getC_ConversionRate_Rule_ID() { return get_ValueAsInt(COLUMNNAME_C_ConversionRate_Rule_ID); } @Override public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setC_Currency_To_ID (final int C_Currency_To_ID) { if (C_Currency_To_ID < 1) set_Value (COLUMNNAME_C_Currency_To_ID, null); else set_Value (COLUMNNAME_C_Currency_To_ID, C_Currency_To_ID); }
@Override public int getC_Currency_To_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_To_ID); } @Override public void setMultiplyRate_Max (final @Nullable BigDecimal MultiplyRate_Max) { set_Value (COLUMNNAME_MultiplyRate_Max, MultiplyRate_Max); } @Override public BigDecimal getMultiplyRate_Max() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Max); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMultiplyRate_Min (final @Nullable BigDecimal MultiplyRate_Min) { set_Value (COLUMNNAME_MultiplyRate_Min, MultiplyRate_Min); } @Override public BigDecimal getMultiplyRate_Min() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Min); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionRate_Rule.java
1
请在Spring Boot框架中完成以下Java代码
public List<RestIdentityLink> getIdentityLinks(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); if (restApiInterceptor != null) { restApiInterceptor.accessTaskIdentityLinks(task); } return restResponseFactory.createRestIdentityLinks(taskService.getIdentityLinksForTask(task.getId())); } @ApiOperation(value = "Create an identity link on a task", tags = { "Task Identity Links" }, nickname = "createTaskInstanceIdentityLinks", notes = "It is possible to add either a user or a group.", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the task was found and the identity link was created."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have the requested identityLink. The status contains additional information about this error.") }) @PostMapping(value = "/cmmn-runtime/tasks/{taskId}/identitylinks", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public RestIdentityLink createIdentityLink(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @RequestBody RestIdentityLink identityLink) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); if (identityLink.getGroup() == null && identityLink.getUser() == null) { throw new FlowableIllegalArgumentException("A group or a user is required to create an identity link."); } if (identityLink.getGroup() != null && identityLink.getUser() != null) {
throw new FlowableIllegalArgumentException("Only one of user or group can be used to create an identity link."); } if (identityLink.getType() == null) { throw new FlowableIllegalArgumentException("The identity link type is required."); } if (restApiInterceptor != null) { restApiInterceptor.createTaskIdentityLink(task, identityLink); } if (identityLink.getGroup() != null) { taskService.addGroupIdentityLink(task.getId(), identityLink.getGroup(), identityLink.getType()); } else { taskService.addUserIdentityLink(task.getId(), identityLink.getUser(), identityLink.getType()); } return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), task.getId(), null, null); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskIdentityLinkCollectionResource.java
2
请完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public Map<String, Object> getVariables() { return modificationBuilder.getProcessVariables(); } public String getTenantId() { return tenantId; } public String getProcessDefinitionTenantId() { return processDefinitionTenantId; } public boolean isProcessDefinitionTenantIdSet() { return isProcessDefinitionTenantIdSet; } public void setModificationBuilder(ProcessInstanceModificationBuilderImpl modificationBuilder) { this.modificationBuilder = modificationBuilder; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId){ this.restartedProcessInstanceId = restartedProcessInstanceId; }
public String getRestartedProcessInstanceId(){ return restartedProcessInstanceId; } public static ProcessInstantiationBuilder createProcessInstanceById(CommandExecutor commandExecutor, String processDefinitionId) { ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor); builder.processDefinitionId = processDefinitionId; return builder; } public static ProcessInstantiationBuilder createProcessInstanceByKey(CommandExecutor commandExecutor, String processDefinitionKey) { ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor); builder.processDefinitionKey = processDefinitionKey; return builder; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstantiationBuilderImpl.java
1
请完成以下Java代码
public FactLineBuilder toLocation(final Optional<LocationId> optionalLocationId) { optionalLocationId.ifPresent(locationId -> this.toLocationId = locationId); return this; } public FactLineBuilder toLocationOfBPartner(@Nullable final BPartnerLocationId bpartnerLocationId) { return toLocation(getServices().getLocationId(bpartnerLocationId)); } public FactLineBuilder toLocationOfLocator(final int locatorRepoId) { return toLocation(getServices().getLocationIdByLocatorRepoId(locatorRepoId)); } public FactLineBuilder costElement(@Nullable final CostElementId costElementId) { assertNotBuild(); this.costElementId = costElementId; return this; } public FactLineBuilder costElement(@Nullable final CostElement costElement) { return costElement(costElement != null ? costElement.getId() : null); } public FactLineBuilder description(@Nullable final String description) { assertNotBuild(); this.description = StringUtils.trimBlankToOptional(description); return this; } public FactLineBuilder additionalDescription(@Nullable final String additionalDescription) { assertNotBuild(); this.additionalDescription = StringUtils.trimBlankToNull(additionalDescription); return this; } public FactLineBuilder openItemKey(@Nullable FAOpenItemTrxInfo openItemTrxInfo) { assertNotBuild(); this.openItemTrxInfo = openItemTrxInfo;
return this; } public FactLineBuilder productId(@Nullable ProductId productId) { assertNotBuild(); this.productId = Optional.ofNullable(productId); return this; } public FactLineBuilder userElementString1(@Nullable final String userElementString1) { assertNotBuild(); this.userElementString1 = StringUtils.trimBlankToOptional(userElementString1); return this; } public FactLineBuilder salesOrderId(@Nullable final OrderId salesOrderId) { assertNotBuild(); this.salesOrderId = Optional.ofNullable(salesOrderId); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLineBuilder.java
1
请完成以下Java代码
public java.lang.String getServiceFeeExternalInvoiceDocumentNo() { return get_ValueAsString(COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo); } @Override public void setServiceFeeInvoicedDate (final @Nullable java.sql.Timestamp ServiceFeeInvoicedDate) { set_Value (COLUMNNAME_ServiceFeeInvoicedDate, ServiceFeeInvoicedDate); } @Override public java.sql.Timestamp getServiceFeeInvoicedDate() { return get_ValueAsTimestamp(COLUMNNAME_ServiceFeeInvoicedDate); } @Override public void setSource_BP_BankAccount_ID (final int Source_BP_BankAccount_ID) { if (Source_BP_BankAccount_ID < 1) set_Value (COLUMNNAME_Source_BP_BankAccount_ID, null); else set_Value (COLUMNNAME_Source_BP_BankAccount_ID, Source_BP_BankAccount_ID); } @Override
public int getSource_BP_BankAccount_ID() { return get_ValueAsInt(COLUMNNAME_Source_BP_BankAccount_ID); } @Override public void setSource_BPartner_ID (final int Source_BPartner_ID) { if (Source_BPartner_ID < 1) set_Value (COLUMNNAME_Source_BPartner_ID, null); else set_Value (COLUMNNAME_Source_BPartner_ID, Source_BPartner_ID); } @Override public int getSource_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Source_BPartner_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice.java
1
请完成以下Java代码
public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) { this.tenantIdProvider = tenantIdProvider; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) { if (tenantIdProvider != null) { return (String) tenantIdProvider.getValue(variableScope); } else { return defaultTenantId; } } public ParameterValueProvider getTenantIdProvider() { return tenantIdProvider;
} /** * @return true if any of the references that specify the callable element are non-literal and need to be resolved with * potential side effects to determine the process or case definition that is to be called. */ public boolean hasDynamicReferences() { return (tenantIdProvider != null && tenantIdProvider.isDynamic()) || definitionKeyValueProvider.isDynamic() || versionValueProvider.isDynamic() || versionTagValueProvider.isDynamic(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java
1
请在Spring Boot框架中完成以下Java代码
public class CampaignId implements RepoIdAware { int repoId; @JsonCreator public static CampaignId ofRepoId(final int repoId) { return new CampaignId(repoId); } @Nullable public static CampaignId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; }
private CampaignId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "MKTG_Campaign_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final de.metas.marketing.base.model.CampaignId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\marketing\base\model\CampaignId.java
2
请完成以下Java代码
private static void updateRecord(final I_C_Order_Cost record, final OrderCost from) { record.setIsActive(true); record.setC_Order_ID(from.getOrderId().getRepoId()); record.setIsSOTrx(from.getSoTrx().toBoolean()); record.setAD_Org_ID(from.getOrgId().getRepoId()); record.setC_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); record.setM_CostElement_ID(from.getCostElementId().getRepoId()); record.setC_Cost_Type_ID(from.getCostTypeId().getRepoId()); final CostCalculationMethod calculationMethod = from.getCalculationMethod(); record.setCostCalculationMethod(calculationMethod.getCode()); calculationMethod.mapOnParams( from.getCalculationMethodParams(), new CostCalculationMethod.ParamsMapper<Object>() { @Override public Object fixedAmount(final FixedAmountCostCalculationMethodParams params) { record.setCostCalculation_FixedAmount(params.getFixedAmount().toBigDecimal()); return null; } @Override public Object percentageOfAmount(final PercentageCostCalculationMethodParams params) { record.setCostCalculation_Percentage(params.getPercentage().toBigDecimal()); return null; } }); record.setCostDistributionMethod(from.getDistributionMethod().getCode()); record.setC_Currency_ID(from.getCostAmount().getCurrencyId().getRepoId()); record.setCostAmount(from.getCostAmount().toBigDecimal()); record.setCreated_OrderLine_ID(OrderLineId.toRepoId(from.getCreatedOrderLineId())); } private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetail from) { record.setIsActive(true); updateRecord(record, from.getOrderLineInfo()); record.setCostAmount(from.getCostAmount().toBigDecimal());
record.setQtyReceived(from.getInoutQty().toBigDecimal()); record.setCostAmountReceived(from.getInoutCostAmount().toBigDecimal()); } private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetailOrderLinePart from) { record.setC_OrderLine_ID(from.getOrderLineId().getRepoId()); record.setM_Product_ID(from.getProductId().getRepoId()); record.setC_UOM_ID(from.getUomId().getRepoId()); record.setQtyOrdered(from.getQtyOrdered().toBigDecimal()); record.setC_Currency_ID(from.getCurrencyId().getRepoId()); record.setLineNetAmt(from.getOrderLineNetAmt().toBigDecimal()); } public void changeByOrderLineId( @NonNull final OrderLineId orderLineId, @NonNull Consumer<OrderCost> consumer) { final List<OrderCost> orderCosts = getByOrderLineIds(ImmutableSet.of(orderLineId)); orderCosts.forEach(orderCost -> { consumer.accept(orderCost); saveUsingCache(orderCost); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepositorySession.java
1
请完成以下Java代码
public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper) { final T businessCaseDetail = getBusinessCaseDetailNotNull(type); final T businessCaseDetailChanged = mapper.apply(businessCaseDetail); if (Objects.equals(businessCaseDetail, businessCaseDetailChanged)) { return this; } return withBusinessCaseDetail(businessCaseDetailChanged); } @Nullable public String getTraceId() { final DemandDetail demandDetail = getDemandDetail(); return demandDetail != null ? demandDetail.getTraceId() : null; } /** * This is enabled by the current usage of {@link #parentId} */ public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate) { if (potentialStockCandidate.type != CandidateType.STOCK) { return false; } switch (type)
{ case DEMAND: return potentialStockCandidate.getParentId().equals(id); case SUPPLY: return potentialStockCandidate.getId().equals(parentId); default: return false; } } /** * The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock. */ public BigDecimal getStockImpactPlannedQuantity() { switch (getType()) { case DEMAND: case UNEXPECTED_DECREASE: case INVENTORY_DOWN: return getQuantity().negate(); default: return getQuantity(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java
1
请完成以下Java代码
public void setDeadLineUnit (final java.lang.String DeadLineUnit) { set_Value (COLUMNNAME_DeadLineUnit, DeadLineUnit); } @Override public java.lang.String getDeadLineUnit() { return get_ValueAsString(COLUMNNAME_DeadLineUnit); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Change.java
1
请完成以下Java代码
public Optional<Quantity> toNoneOrSingleValue() { if (map.isEmpty()) { return Optional.empty(); } else if (map.size() == 1) { return map.values().stream().findFirst(); } else { throw new AdempiereException("Expected none or single value but got many: " + map.values()); } } public MixedQuantity add(@NonNull final Quantity qtyToAdd)
{ if (qtyToAdd.isZero()) { return this; } return new MixedQuantity( CollectionUtils.merge(map, qtyToAdd.getUomId(), qtyToAdd, Quantity::add) ); } public Quantity getByUOM(@NonNull final UomId uomId) { final Quantity qty = map.get(uomId); return qty != null ? qty : Quantitys.zero(uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\MixedQuantity.java
1
请完成以下Java代码
public boolean cancel(boolean mayInterruptIfRunning) { // unsupported return false; } public boolean isCancelled() { // unsupported return cancelled; } public boolean isDone() { return value != null; } public V get() throws InterruptedException, ExecutionException { if (!failed && !cancelled && value == null) { synchronized (this) { if (!failed && !cancelled && value == null) { this.wait(); } } } return value; }
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!failed && !cancelled && value == null) { synchronized (this) { if (!failed && !cancelled && value == null) { this.wait(unit.convert(timeout, TimeUnit.MILLISECONDS)); } synchronized (this) { if (value == null) { throw new TimeoutException(); } } } } return value; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\util\ServiceListenerFuture.java
1
请完成以下Java代码
public BPartnerId getBpartnerId() { return BPartnerId.ofRepoIdOrNull(getContextAsInt("C_BPartner_ID")); } @Override public ProductId getProductId() { return ProductId.ofRepoIdOrNull(getContextAsInt("M_Product_ID")); } @Override public boolean isSOTrx() { return SOTrx.toBoolean(getSoTrx()); } @Override public SOTrx getSoTrx() { final Boolean soTrx = Env.getSOTrxOrNull(ctx, windowNo); return SOTrx.ofBoolean(soTrx); } @Override
public WarehouseId getWarehouseId() { return WarehouseId.ofRepoIdOrNull(getContextAsInt("M_Warehouse_ID")); } @Override public int getM_Locator_ID() { return getContextAsInt("M_Locator_ID"); } @Override public DocTypeId getDocTypeId() { return DocTypeId.ofRepoIdOrNull(getContextAsInt("C_DocType_ID")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VPAttributeWindowContext.java
1
请完成以下Java代码
public boolean isReceipt() { return isInboundPayment(); } public boolean isInboundPayment() { return this == INBOUND; } public boolean isOutboundPayment() { return this == OUTBOUND; }
public Amount convertPayAmtToStatementAmt(@NonNull final Amount payAmt) { return payAmt.negateIf(isOutboundPayment()); } public Money convertPayAmtToStatementAmt(@NonNull final Money payAmt) { return payAmt.negateIf(isOutboundPayment()); } public Money convertStatementAmtToPayAmt(@NonNull final Money bankStatementAmt) { return bankStatementAmt.negateIf(isOutboundPayment()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\PaymentDirection.java
1
请完成以下Java代码
public void failure(String taskId, String errorMessage, String errorDetails, int retries, long retryTimeout, Map<String, Object> variables, Map<String, Object> localVariables) { Map<String, TypedValueField> typedValueDtoMap = typedValues.serializeVariables(variables); Map<String, TypedValueField> localTypedValueDtoMap = typedValues.serializeVariables(localVariables); FailureRequestDto payload = new FailureRequestDto(workerId, errorMessage, errorDetails, retries, retryTimeout, typedValueDtoMap, localTypedValueDtoMap); String resourcePath = FAILURE_RESOURCE_PATH.replace("{id}", taskId); String resourceUrl = getBaseUrl() + resourcePath; engineInteraction.postRequest(resourceUrl, payload, Void.class); } public void bpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) { Map<String, TypedValueField> typeValueDtoMap = typedValues.serializeVariables(variables); BpmnErrorRequestDto payload = new BpmnErrorRequestDto(workerId, errorCode, errorMessage, typeValueDtoMap); String resourcePath = BPMN_ERROR_RESOURCE_PATH.replace("{id}", taskId); String resourceUrl = getBaseUrl() + resourcePath; engineInteraction.postRequest(resourceUrl, payload, Void.class); } public void extendLock(String taskId, long newDuration) { ExtendLockRequestDto payload = new ExtendLockRequestDto(workerId, newDuration); String resourcePath = EXTEND_LOCK_RESOURCE_PATH.replace("{id}", taskId); String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class); } public byte[] getLocalBinaryVariable(String variableName, String executionId) { String resourcePath = getBaseUrl() + GET_BINARY_VARIABLE .replace(ID_PATH_PARAM, executionId) .replace(NAME_PATH_PARAM, variableName); return engineInteraction.getRequest(resourcePath); } public String getBaseUrl() { return urlResolver.getBaseUrl(); } public String getWorkerId() { return workerId; } public void setTypedValues(TypedValues typedValues) { this.typedValues = typedValues; } public boolean isUsePriority() { return usePriority; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClient.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteNotificationTemplateById(@PathVariable UUID id) throws Exception { NotificationTemplateId notificationTemplateId = new NotificationTemplateId(id); NotificationTemplate notificationTemplate = checkEntityId(notificationTemplateId, notificationTemplateService::findNotificationTemplateById, Operation.DELETE); doDeleteAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::deleteNotificationTemplateById); } @ApiOperation(value = "List Slack conversations (listSlackConversations)", notes = "List available Slack conversations by type." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @GetMapping("/slack/conversations") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") public List<SlackConversation> listSlackConversations(@RequestParam SlackConversationType type, @Parameter(description = "Slack bot token. If absent - system Slack settings will be used") @RequestParam(required = false) String token, @AuthenticationPrincipal SecurityUser user) {
// PE: generic permission if (StringUtils.isEmpty(token)) { NotificationSettings settings = notificationSettingsService.findNotificationSettings(user.getTenantId()); SlackNotificationDeliveryMethodConfig slackConfig = (SlackNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK); if (slackConfig == null) { throw new IllegalArgumentException("Slack is not configured"); } token = slackConfig.getBotToken(); } return slackService.listConversations(user.getTenantId(), token, type); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\NotificationTemplateController.java
2
请完成以下Java代码
public String getGebuehrenbetragWaehrung() { return gebuehrenbetragWaehrung; } public void setGebuehrenbetragWaehrung(String gebuehrenbetragWaehrung) { this.gebuehrenbetragWaehrung = gebuehrenbetragWaehrung; } public String getMehrzweckfeld() { return mehrzweckfeld; } public void setMehrzweckfeld(String mehrzweckfeld) { this.mehrzweckfeld = mehrzweckfeld; } public BigInteger getGeschaeftsvorfallCode() { return geschaeftsvorfallCode; } public void setGeschaeftsvorfallCode(BigInteger geschaeftsvorfallCode) { this.geschaeftsvorfallCode = geschaeftsvorfallCode; } public String getBuchungstext() { return buchungstext; } public void setBuchungstext(String buchungstext) { this.buchungstext = buchungstext; } public String getPrimanotennummer() { return primanotennummer; } public void setPrimanotennummer(String primanotennummer) { this.primanotennummer = primanotennummer; } public String getVerwendungszweck() { return verwendungszweck; }
public void setVerwendungszweck(String verwendungszweck) { this.verwendungszweck = verwendungszweck; } public String getPartnerBlz() { return partnerBlz; } public void setPartnerBlz(String partnerBlz) { this.partnerBlz = partnerBlz; } public String getPartnerKtoNr() { return partnerKtoNr; } public void setPartnerKtoNr(String partnerKtoNr) { this.partnerKtoNr = partnerKtoNr; } public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public String getTextschluessel() { return textschluessel; } public void setTextschluessel(String textschluessel) { this.textschluessel = textschluessel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getQtyCUsPerTUInInvoiceUOM() { return qtyCUsPerTUInInvoiceUOM; } /** * Sets the value of the qtyCUsPerTUInInvoiceUOM property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setQtyCUsPerTUInInvoiceUOM(BigDecimal value) { this.qtyCUsPerTUInInvoiceUOM = value; } /** * Gets the value of the qtyTU property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getQtyTU() { return qtyTU; } /** * Sets the value of the qtyTU property. * * @param value * allowed object is * {@link BigInteger } * */ public void setQtyTU(BigInteger value) { this.qtyTU = value; } /** * Gets the value of the ediDesadvLineID property. * * @return * possible object is * {@link EDIExpDesadvLineType } * */ public EDIExpDesadvLineType getEDIDesadvLineID() { return ediDesadvLineID; } /** * Sets the value of the ediDesadvLineID property. * * @param value * allowed object is * {@link EDIExpDesadvLineType } * */ public void setEDIDesadvLineID(EDIExpDesadvLineType value) { this.ediDesadvLineID = value; } /** * Gets the value of the gtintuPackingMaterial property. * * @return * possible object is * {@link String } * */ public String getGTINTUPackingMaterial() { return gtintuPackingMaterial; } /** * Sets the value of the gtintuPackingMaterial property. * * @param value * allowed object is * {@link String } * */ public void setGTINTUPackingMaterial(String value) { this.gtintuPackingMaterial = value;
} /** * Gets the value of the mhuPackagingCodeTUText property. * * @return * possible object is * {@link String } * */ public String getMHUPackagingCodeTUText() { return mhuPackagingCodeTUText; } /** * Sets the value of the mhuPackagingCodeTUText property. * * @param value * allowed object is * {@link String } * */ public void setMHUPackagingCodeTUText(String value) { this.mhuPackagingCodeTUText = value; } /** * Gets the value of the line property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getLine() { return line; } /** * Sets the value of the line property. * * @param value * allowed object is * {@link BigInteger } * */ public void setLine(BigInteger value) { this.line = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackItemType.java
2
请完成以下Java代码
public void setStmtAmt (final @Nullable BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final @Nullable BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Sales = S */ public static final String TRXTYPE_Sales = "S"; /** DelayedCapture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** CreditPayment = C */ public static final String TRXTYPE_CreditPayment = "C"; /** VoiceAuthorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F";
/** Authorization = A */ public static final String TRXTYPE_Authorization = "A"; /** Void = V */ public static final String TRXTYPE_Void = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; @Override public void setTrxType (final @Nullable java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java
1