instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class GeodeGatewayReceiversHealthIndicator extends AbstractGeodeHealthIndicator { /** * Default constructor to construct an uninitialized instance of {@link GeodeGatewayReceiversHealthIndicator}, * which will not provide any health information. */ public GeodeGatewayReceiversHealthIndicator() { super("Gateway Receivers health check failed"); } /** * Constructs an instance of the {@link GeodeGatewayReceiversHealthIndicator} initialized with a reference to * the {@link GemFireCache} instance. * * @param gemfireCache reference to the {@link GemFireCache} instance used to collect health information. * @throws IllegalArgumentException if {@link GemFireCache} is {@literal null}. * @see org.apache.geode.cache.GemFireCache */ public GeodeGatewayReceiversHealthIndicator(GemFireCache gemfireCache) { super(gemfireCache); } @Override protected void doHealthCheck(Health.Builder builder) { if (getGemFireCache().filter(CacheUtils::isPeer).isPresent()) { AtomicInteger globalIndex = new AtomicInteger(0); Set<GatewayReceiver> gatewayReceivers = getGemFireCache() .map(Cache.class::cast) .map(Cache::getGatewayReceivers) .orElseGet(Collections::emptySet); builder.withDetail("geode.gateway-receiver.count", gatewayReceivers.size());
gatewayReceivers.stream() .filter(Objects::nonNull) .forEach(gatewayReceiver -> { int index = globalIndex.getAndIncrement(); builder.withDetail(gatewayReceiverKey(index, "bind-address"), gatewayReceiver.getBindAddress()) .withDetail(gatewayReceiverKey(index, "end-port"), gatewayReceiver.getEndPort()) .withDetail(gatewayReceiverKey(index, "host"), gatewayReceiver.getHost()) .withDetail(gatewayReceiverKey(index, "max-time-between-pings"), gatewayReceiver.getMaximumTimeBetweenPings()) .withDetail(gatewayReceiverKey(index, "port"), gatewayReceiver.getPort()) .withDetail(gatewayReceiverKey(index, "running"), toYesNoString(gatewayReceiver.isRunning())) .withDetail(gatewayReceiverKey(index, "socket-buffer-size"), gatewayReceiver.getSocketBufferSize()) .withDetail(gatewayReceiverKey(index, "start-port"), gatewayReceiver.getStartPort()); }); builder.up(); return; } builder.unknown(); } private String gatewayReceiverKey(int index, String suffix) { return String.format("geode.gateway-receiver.%d.%s", index, suffix); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeGatewayReceiversHealthIndicator.java
1
请完成以下Java代码
public final void setAuthorizationRequestRepository( ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) { Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null"); this.authorizationRequestRepository = authorizationRequestRepository; } /** * The request cache to use to save the request before sending a redirect. * @param requestCache the cache to redirect to. */ public void setRequestCache(ServerRequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // @formatter:off return this.authorizationRequestResolver.resolve(exchange) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .onErrorResume(ClientAuthorizationRequiredException.class, (ex) -> this.requestCache.saveRequest(exchange).then( this.authorizationRequestResolver.resolve(exchange, ex.getClientRegistrationId())) ) .flatMap((clientRegistration) -> sendRedirectForAuthorization(exchange, clientRegistration)); // @formatter:on } private Mono<Void> sendRedirectForAuthorization(ServerWebExchange exchange, OAuth2AuthorizationRequest authorizationRequest) { return Mono.defer(() -> {
Mono<Void> saveAuthorizationRequest = Mono.empty(); if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) { saveAuthorizationRequest = this.authorizationRequestRepository .saveAuthorizationRequest(authorizationRequest, exchange); } // @formatter:off URI redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getAuthorizationRequestUri()) .build(true) .toUri(); // @formatter:on return saveAuthorizationRequest .then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri)); }); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationRequestRedirectWebFilter.java
1
请完成以下Java代码
public List<Rating> findRatingsByBookId(Long bookId) { return ratingRepository.findRatingsByBookId(bookId); } public List<Rating> findCachedRatingsByBookId(Long bookId, Exception exception) { return cacheRepository.findCachedRatingsByBookId(bookId); } @CircuitBreaker(name = "ratingsFromDB", fallbackMethod = "findAllCachedRatings") public List<Rating> findAllRatings() { return ratingRepository.findAll(); } public List<Rating> findAllCachedRatings(Exception exception) { return cacheRepository.findAllCachedRatings(); } @CircuitBreaker(name = "ratingsByIdFromDB", fallbackMethod = "findCachedRatingById") public Rating findRatingById(Long ratingId) { return ratingRepository.findById(ratingId) .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); } public Rating findCachedRatingById(Long ratingId, Exception exception) { return cacheRepository.findCachedRatingById(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating createRating(Rating rating) { Rating newRating = new Rating(); newRating.setBookId(rating.getBookId()); newRating.setStars(rating.getStars()); Rating persisted = ratingRepository.save(newRating); cacheRepository.createRating(persisted); return persisted;
} @Transactional(propagation = Propagation.REQUIRED) public void deleteRating(Long ratingId) { ratingRepository.deleteById(ratingId); cacheRepository.deleteRating(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Map<String, String> updates, Long ratingId) { final Rating rating = findRatingById(ratingId); updates.keySet() .forEach(key -> { switch (key) { case "stars": rating.setStars(Integer.parseInt(updates.get(key))); break; } }); Rating persisted = ratingRepository.save(rating); cacheRepository.updateRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Rating rating, Long ratingId) { Preconditions.checkNotNull(rating); Preconditions.checkState(rating.getId() == ratingId); Preconditions.checkNotNull(ratingRepository.findById(ratingId)); return ratingRepository.save(rating); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingService.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set URL3.
@param URL3 Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public void setURL3 (java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } /** Get URL3. @return Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public java.lang.String getURL3 () { return (java.lang.String)get_Value(COLUMNNAME_URL3); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner_GlobalID.java
1
请在Spring Boot框架中完成以下Java代码
private String getSysconfigValueWithHostNameFallback(final String prefix, final String suffix, final @Nullable String defaultValue) { // // Try by hostname final String deviceKeyWithHostName = prefix + "." + clientHost.getHostName() + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithHostName, clientAndOrgId); if (value != null) { return value; } } // // Try by host's IP final String deviceKeyWithIP = prefix + "." + clientHost.getIP() + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithIP, clientAndOrgId); if (value != null) { return value; } } // // Try by any host (i.e. 0.0.0.0) final String deviceKeyWithWildCard = prefix + "." + IPADDRESS_ANY + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithWildCard, clientAndOrgId);
if (value != null) { return value; } } // // Fallback to default if (defaultValue != null) { return defaultValue; } // // Throw exception throw new DeviceConfigException("@NotFound@: @AD_SysConfig@ " + deviceKeyWithHostName + ", " + deviceKeyWithIP + ", " + deviceKeyWithWildCard + "; @AD_Client_ID@=" + clientAndOrgId.getClientId() + " @AD_Org_ID@=" + clientAndOrgId.getOrgId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\SysConfigDeviceConfigPool.java
2
请在Spring Boot框架中完成以下Java代码
public OrderBOMLineQuantities getQuantities(@NonNull final I_PP_Order_BOMLine orderBOMLine) {return ppOrderBOMBL.getQuantities(orderBOMLine);} public ImmutableListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> getIssueSchedules(@NonNull final PPOrderId ppOrderId) { return Multimaps.index(ppOrderIssueScheduleService.getByOrderId(ppOrderId), PPOrderIssueSchedule::getPpOrderBOMLineId); } public ImmutableAttributeSet getImmutableAttributeSet(final AttributeSetInstanceId asiId) { return asiBL.getImmutableAttributeSetById(asiId); } public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode) { return huQRCodeService.getHuIdByQRCodeIfExists(qrCode); } public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId) { final boolean ensureSingleAssignment = true; huQRCodeService.assign(qrCode, huId, ensureSingleAssignment); } public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId) { return huQRCodeService.getFirstQRCodeByHuId(huId); } public Quantity getHUCapacity( @NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final I_C_UOM uom) { final I_M_HU hu = handlingUnitsBL.getById(huId); return handlingUnitsBL .getStorageFactory() .getStorage(hu) .getQuantity(productId, uom); } @NonNull public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId) { final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId) .stream()
.map(locatorId -> { final String caption = getLocatorName(locatorId); return LocatorInfo.builder() .id(locatorId) .caption(caption) .qrCode(LocatorQRCode.builder() .locatorId(locatorId) .caption(caption) .build()) .build(); }) .collect(ImmutableList.toImmutableList()); return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList); } @NonNull public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId) { return productBL.getCatchUOMId(productId); } @NonNull private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId) { final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId); return handlingUnitsBL.getLocatorIds(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
2
请完成以下Java代码
public class ResourceEntityImpl extends AbstractEntityNoRevision implements ResourceEntity, Serializable { private static final long serialVersionUID = 1L; protected String name; protected byte[] bytes; protected String deploymentId; protected boolean generated; public ResourceEntityImpl() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Object getPersistentState() { return ResourceEntityImpl.class;
} 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; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ResourceEntityImpl.java
1
请完成以下Java代码
public class M_ReceiptSchedule { /** * Updates the M_Material_Tracking attribute of the assigned HUs which are still in the planning status. * * @param rs */ @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = I_M_ReceiptSchedule.COLUMNNAME_M_AttributeSetInstance_ID) public void onMaterialTrackingASIChange(final I_M_ReceiptSchedule rs) { final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class); // get the old and current material tracking (if any) and check if there was a change final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(rs.getM_AttributeSetInstance_ID()); final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId); // might be null final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID(); final I_M_ReceiptSchedule rsOld = InterfaceWrapperHelper.createOld(rs, I_M_ReceiptSchedule.class); final AttributeSetInstanceId asiOldId = AttributeSetInstanceId.ofRepoIdOrNone(rsOld.getM_AttributeSetInstance_ID());
final I_M_Material_Tracking materialTrackingOld = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiOldId); final int materialTrackingOldId = materialTrackingOld == null ? -1 : materialTrackingOld.getM_Material_Tracking_ID(); if (materialTrackingOldId == materialTrackingId) { return; // the M_Material_Tracking part of the ASI was not changed; nothing to do } // update the HUs that are still in the planning stage final List<I_M_HU> topLevelHUs = huAssignmentDAO.retrieveTopLevelHUsForModel(rs); for (final I_M_HU hu : topLevelHUs) { // we only want to update HUs that are still in the planning stage. For the others, this rs is not in charge anymore final IHUMaterialTrackingBL huMaterialTrackingBL = Services.get(IHUMaterialTrackingBL.class); huMaterialTrackingBL.updateHUAttributeRecursive(hu, materialTracking, X_M_HU.HUSTATUS_Planning); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\model\validator\M_ReceiptSchedule.java
1
请完成以下Java代码
public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.useAnnotationTemplate = templateDefaults != null; this.scanner = SecurityAnnotationScanners.requireUnique(CurrentSecurityContext.class, templateDefaults); } private @Nullable Object resolveSecurityContextFromAnnotation(MethodParameter parameter, CurrentSecurityContext annotation, SecurityContext securityContext) { Object securityContextResult = securityContext; String expressionToParse = annotation.expression(); if (StringUtils.hasLength(expressionToParse)) { StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(securityContext); context.setVariable("this", securityContext); // https://github.com/spring-projects/spring-framework/issues/35371 if (this.beanResolver != null) { context.setBeanResolver(this.beanResolver); } Expression expression = this.parser.parseExpression(expressionToParse); securityContextResult = expression.getValue(context); } if (securityContextResult != null && !parameter.getParameterType().isAssignableFrom(securityContextResult.getClass())) { if (annotation.errorOnInvalidType()) { throw new ClassCastException( securityContextResult + " is not assignable to " + parameter.getParameterType()); } return null; } return securityContextResult; } /** * Obtain the specified {@link Annotation} on the specified {@link MethodParameter}. * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */
private @Nullable CurrentSecurityContext findMethodAnnotation(MethodParameter parameter) { if (this.useAnnotationTemplate) { return this.scanner.scan(parameter.getParameter()); } CurrentSecurityContext annotation = parameter.getParameterAnnotation(this.annotationType); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType); if (annotation != null) { return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize(); } } return null; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\method\annotation\CurrentSecurityContextArgumentResolver.java
1
请完成以下Java代码
protected final boolean isInitialized() { return initialized; } protected final String getDbType() { return _dbType; } protected final String getJdbcDriverClassname() { return _jdbcDriverClassname; } private final void init() { if (initialized) { return; } try { final String jdbcDriverClassname = getJdbcDriverClassname(); Class.forName(jdbcDriverClassname); } catch (final ClassNotFoundException e) { throw new RuntimeException("Cannot initialize postgresql database driver", e); }
initialized = true; } @Override public final Connection getConnection(final String hostname, final String port, final String dbName, final String user, final String password) throws SQLException { init(); final String passwordToUse = getPasswordToUse(hostname, port, dbName, user, password); final String dbType = getDbType(); final StringBuilder url = new StringBuilder(); url.append("jdbc:").append(dbType).append("://").append(hostname); if (port != null && port.trim().length() > 0) { url.append(":").append(port.trim()); } url.append("/").append(dbName); return DriverManager.getConnection(url.toString(), user, passwordToUse); } protected String getPasswordToUse(final String hostname, final String port, final String dbName, final String user, final String password) throws SQLException { return password; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\GenericSQLDatabaseDriver.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getAssignee() { return assignee; } @Override public void setAssignee(String assignee) { this.assignee = assignee; } @Override public String getCompletedBy() { return completedBy; } @Override public void setCompletedBy(String completedBy) { this.completedBy = completedBy; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getCalledProcessInstanceId() { return calledProcessInstanceId; } @Override public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Date getTime() { return getStartTime(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ActivityInstanceEntity[id=").append(id) .append(", activityId=").append(activityId); if (activityName != null) { sb.append(", activityName=").append(activityName); } sb.append(", executionId=").append(executionId) .append(", definitionId=").append(processDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java
1
请完成以下Java代码
public int getEDI_Desadv_Parent_Pack_ID() { return get_ValueAsInt(COLUMNNAME_EDI_Desadv_Parent_Pack_ID); } @Override public void setGTIN_PackingMaterial (final @Nullable java.lang.String GTIN_PackingMaterial) { set_Value (COLUMNNAME_GTIN_PackingMaterial, GTIN_PackingMaterial); } @Override public java.lang.String getGTIN_PackingMaterial() { return get_ValueAsString(COLUMNNAME_GTIN_PackingMaterial); } @Override public void setIPA_SSCC18 (final java.lang.String IPA_SSCC18) { set_Value (COLUMNNAME_IPA_SSCC18, IPA_SSCC18); } @Override public java.lang.String getIPA_SSCC18() { return get_ValueAsString(COLUMNNAME_IPA_SSCC18); } @Override public void setIsManual_IPA_SSCC18 (final boolean IsManual_IPA_SSCC18) { set_Value (COLUMNNAME_IsManual_IPA_SSCC18, IsManual_IPA_SSCC18); } @Override public boolean isManual_IPA_SSCC18() { return get_ValueAsBoolean(COLUMNNAME_IsManual_IPA_SSCC18); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID) { if (M_HU_PackagingCode_ID < 1) set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null); else set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID); } @Override public int getM_HU_PackagingCode_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text) { throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); } @Override public java.lang.String getM_HU_PackagingCode_Text() { return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { throw new IllegalArgumentException ("M_InOut_ID is virtual column"); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java
1
请完成以下Java代码
public void setQtyTUFromQtyLU(final IHUPackingAware record) { final BigDecimal qtyLUs = record.getQtyLU(); if (qtyLUs == null) { return; } final BigDecimal capacity = calculateLUCapacity(record); if (capacity == null) { return; } final BigDecimal qtyTUs = qtyLUs.multiply(capacity); record.setQtyTU(qtyTUs); } @Override public void setQtyLUFromQtyTU(final IHUPackingAware record) { final BigDecimal qtyTUs = record.getQtyTU(); if (qtyTUs == null) { return; } final BigDecimal capacity = calculateLUCapacity(record); if (capacity == null) { return; }
final BigDecimal qtyLUs = qtyTUs.divide(capacity, RoundingMode.UP); record.setQtyLU(qtyLUs); } @Override public void validateLUQty(final BigDecimal luQty) { final int maxLUQty = sysConfigBL.getIntValue(SYS_CONFIG_MAXQTYLU, SYS_CONFIG_MAXQTYLU_DEFAULT_VALUE); if (luQty != null && luQty.compareTo(BigDecimal.valueOf(maxLUQty)) > 0) { throw new AdempiereException(MSG_MAX_LUS_EXCEEDED); } } private I_C_UOM extractUOMOrNull(final IHUPackingAware huPackingAware) { final int uomId = huPackingAware.getC_UOM_ID(); return uomId > 0 ? uomDAO.getById(uomId) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareBL.java
1
请在Spring Boot框架中完成以下Java代码
public class JobEntityImpl extends AbstractJobEntityImpl implements JobEntity { private static final long serialVersionUID = 1L; protected String lockOwner; protected Date lockExpirationTime; @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; } // getters and setters //////////////////////////////////////////////////////// @Override
public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String claimedBy) { this.lockOwner = claimedBy; } @Override public Date getLockExpirationTime() { return lockExpirationTime; } @Override public void setLockExpirationTime(Date claimedUntil) { this.lockExpirationTime = claimedUntil; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobEntityImpl.java
2
请完成以下Java代码
public static ILoggable get() { return ThreadLocalLoggableHolder.instance.getLoggable(); } /** * @return current thread's {@link ILoggable} instance or a loggable which is forwarding to given logger instance if there was no thread level {@link ILoggable} */ public static ILoggable getLoggableOrLogger(@NonNull final Logger logger, @NonNull final Level logLevel) { final ILoggable loggable = ThreadLocalLoggableHolder.instance.getLoggableOr(null); return loggable != null ? loggable : logback(logger, logLevel); } public static ILoggable console() { return ConsoleLoggable.withPrefix(null); } public static ILoggable console(@Nullable final String prefix) { return ConsoleLoggable.withPrefix(prefix); } public static ILoggable logback(@NonNull final Logger logger, @NonNull final Level logLevel) { return new LogbackLoggable(logger, logLevel); } public static IAutoCloseable temporarySetLoggable(final ILoggable loggable) { return ThreadLocalLoggableHolder.instance.temporarySetLoggable(composeWithDebuggingLoggable(loggable)); } public static void setDebuggingLoggable(@Nullable final ILoggable debuggingLoggable) { Loggables.debuggingLoggable = debuggingLoggable; } private static ILoggable composeWithDebuggingLoggable(@Nullable final ILoggable loggable) { return CompositeLoggable2.compose(loggable, debuggingLoggable); } /** * @return The null loggable which can be used without NPE, but doesn't do anything */ @NonNull public static ILoggable nop() { return NullLoggable.instance; } public static boolean isNull(@Nullable final ILoggable loggable) { return NullLoggable.isNull(loggable); } /** * Create a new {@link ILoggable} instance that delegates {@link #addLog(String, Object...)} invocations to the thread-local instance and in addition logs to the given logger. */ public static ILoggable withLogger(@NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(get(), logger, level); } @NonNull public static ILoggable withFallbackToLogger(@NonNull final Logger logger, @NonNull final Level level) {
final ILoggable threadLocalLoggable = get(); if (NullLoggable.isNull(threadLocalLoggable)) { return new LoggableWithLogger(NullLoggable.instance, logger, level); } else { return threadLocalLoggable; } } public static ILoggable withLogger(@NonNull final ILoggable loggable, @NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(loggable, logger, level); } public static ILoggable withWarnLoggerToo(@NonNull final Logger logger) { return withLogger(logger, Level.WARN); } public static PlainStringLoggable newPlainStringLoggable() { return new PlainStringLoggable(); } public static ILoggable addLog(final String msg, final Object... msgParameters) { return get().addLog(msg, msgParameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Loggables.java
1
请在Spring Boot框架中完成以下Java代码
public void newAuthor() throws IOException { Author mt = new Author(); mt.setName("Martin Ticher"); mt.setAge(43); mt.setGenre("Horror"); mt.setAvatar(BlobProxy.generateProxy( Files.readAllBytes(new File("avatars/mt_avatar.png").toPath()))); mt.setBiography(ClobProxy.generateProxy( Files.readString(new File("biography/mt_bio.txt").toPath()))); authorRepository.save(mt); } public void fetchAuthor() throws SQLException, IOException { Author author = authorRepository.findByName("Martin Ticher"); System.out.println("Author bio: " + readBiography(author.getBiography())); System.out.println("Author avatar: " + Arrays.toString(readAvatar(author.getAvatar())));
} private byte[] readAvatar(Blob avatar) throws SQLException, IOException { try ( InputStream is = avatar.getBinaryStream()) { return is.readAllBytes(); } } private String readBiography(Clob bio) throws SQLException, IOException { StringBuilder sb = new StringBuilder(); try ( Reader reader = bio.getCharacterStream()) { char[] buffer = new char[2048]; for (int i = reader.read(buffer); i > 0; i = reader.read(buffer)) { sb.append(buffer, 0, i); } } return sb.toString(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMappingLobToClobAndBlob\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void handle(ShipOrderCommand command) { if (!orderConfirmed) { throw new UnconfirmedOrderException(); } apply(new OrderShippedEvent(orderId)); } @EventSourcingHandler public void on(OrderCreatedEvent event) { this.orderId = event.getOrderId(); this.orderConfirmed = false; this.orderLines = new HashMap<>(); } @EventSourcingHandler public void on(OrderConfirmedEvent event) { this.orderConfirmed = true; }
@EventSourcingHandler public void on(ProductAddedEvent event) { String productId = event.getProductId(); this.orderLines.put(productId, new OrderLine(productId)); } @EventSourcingHandler public void on(ProductRemovedEvent event) { this.orderLines.remove(event.getProductId()); } protected OrderAggregate() { // Required by Axon to build a default Aggregate prior to Event Sourcing } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\commandmodel\order\OrderAggregate.java
1
请完成以下Java代码
public class HistoricVariableUpdateDto extends HistoricDetailDto { protected String variableName; protected String variableInstanceId; protected String variableType; protected Object value; protected Map<String, Object> valueInfo; protected Boolean initial; protected int revision; protected String errorMessage; public String getVariableName() { return variableName; } public String getVariableInstanceId() { return variableInstanceId; } public String getVariableType() { return variableType; } public Object getValue() { return value; } public Boolean getInitial() { return initial; } public int getRevision() { return revision; } public String getErrorMessage() { return errorMessage; } public Map<String, Object> getValueInfo() { return valueInfo; }
public static HistoricVariableUpdateDto fromHistoricVariableUpdate(HistoricVariableUpdate historicVariableUpdate) { HistoricVariableUpdateDto dto = new HistoricVariableUpdateDto(); fromHistoricVariableUpdate(dto, historicVariableUpdate); return dto; } protected static void fromHistoricVariableUpdate(HistoricVariableUpdateDto dto, HistoricVariableUpdate historicVariableUpdate) { dto.revision = historicVariableUpdate.getRevision(); dto.variableName = historicVariableUpdate.getVariableName(); dto.variableInstanceId = historicVariableUpdate.getVariableInstanceId(); dto.initial = historicVariableUpdate.isInitial(); if (historicVariableUpdate.getErrorMessage() == null) { try { VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(historicVariableUpdate.getTypedValue()); dto.value = variableValueDto.getValue(); dto.variableType = variableValueDto.getType(); dto.valueInfo = variableValueDto.getValueInfo(); } catch (RuntimeException e) { dto.errorMessage = e.getMessage(); dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); } } else { dto.errorMessage = historicVariableUpdate.getErrorMessage(); dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableUpdateDto.java
1
请在Spring Boot框架中完成以下Java代码
public ExpressionManager expressionManager(List<CustomFunctionProvider> customFunctionProviders) { ExpressionManager expressionManager = new ExpressionManager(); expressionManager.setCustomFunctionProviders(customFunctionProviders); return expressionManager; } @Bean @ConditionalOnMissingBean public ExpressionResolver expressionResolver(ExpressionManager expressionManager, ObjectMapper objectMapper) { return new ExpressionResolver(expressionManager, objectMapper, new DefaultDelegateInterceptor()); } @Bean @ConditionalOnMissingBean public IntegrationContextBuilder integrationContextBuilder( ExtensionsVariablesMappingProvider variablesMappingProvider, ExpressionManager expressionManager ) { return new IntegrationContextBuilder(variablesMappingProvider, expressionManager); } @Bean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) @ConditionalOnMissingBean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) public DefaultServiceTaskBehavior defaultServiceTaskBehavior( ApplicationContext applicationContext, IntegrationContextBuilder integrationContextBuilder, VariablesPropagator variablesPropagator ) { return new DefaultServiceTaskBehavior(applicationContext, integrationContextBuilder, variablesPropagator);
} @Bean @ConditionalOnMissingBean public ExtensionsVariablesMappingProvider variablesMappingProvider( ProcessExtensionService processExtensionService, ExpressionResolver expressionResolver, VariableParsingService variableParsingService ) { return new ExtensionsVariablesMappingProvider( processExtensionService, expressionResolver, variableParsingService ); } @Bean @ConditionalOnMissingBean public VariablesPropagator variablesPropagator(VariablesCalculator variablesCalculator) { return new VariablesPropagator(variablesCalculator); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ConnectorsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class PostgRESTConfigRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<OrgId, Optional<I_S_PostgREST_Config>> cache = CCache.<OrgId, Optional<I_S_PostgREST_Config>>builder() .tableName(I_S_PostgREST_Config.Table_Name) .build(); @NonNull public PostgRESTConfig getConfigFor(@NonNull final OrgId orgId) { final Optional<PostgRESTConfig> config = getOptionalConfigFor(orgId); return config.orElseThrow(() -> new AdempiereException("Missing PostgREST configs for the given orgID!") .appendParametersToMessage() .setParameter("OrgId", orgId)); } public Optional<PostgRESTConfig> getOptionalConfigFor(@NonNull final OrgId orgId) { return getOptionalConfigRecordFor(orgId) .map(record -> PostgRESTConfig.builder() .id(PostgRESTConfigId.ofRepoId(record.getS_PostgREST_Config_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .readTimeout(Duration.ofMillis(record.getRead_timeout())) .connectionTimeout(Duration.ofMillis(record.getConnection_timeout())) .baseURL(record.getBase_url()) .resultDirectory(record.getPostgREST_ResultDirectory()) .build()); } @NonNull private Optional<I_S_PostgREST_Config> getOptionalConfigRecordFor(@NonNull final OrgId orgId) { return cache.getOrLoad(orgId, this::retrieveConfigFor); } @NonNull private Optional<I_S_PostgREST_Config> retrieveConfigFor(@NonNull final OrgId orgId) { return queryBL .createQueryBuilder(I_S_PostgREST_Config.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_S_PostgREST_Config.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY) .orderBy(I_S_PostgREST_Config.COLUMNNAME_AD_Org_ID) .create()
.firstOptional(I_S_PostgREST_Config.class); } public void save(@NonNull final PostgRESTConfig postgRESTConfig) { final I_S_PostgREST_Config configRecord = InterfaceWrapperHelper.loadOrNew(postgRESTConfig.getId(), I_S_PostgREST_Config.class); configRecord.setAD_Org_ID(postgRESTConfig.getOrgId().getRepoId()); configRecord.setBase_url(postgRESTConfig.getBaseURL()); if (postgRESTConfig.getConnectionTimeout() == null) { configRecord.setConnection_timeout(0); } else { final long millis = postgRESTConfig.getConnectionTimeout().toMillis(); configRecord.setConnection_timeout((int)millis); } if (postgRESTConfig.getReadTimeout() == null) { configRecord.setRead_timeout(0); } else { final long millis = postgRESTConfig.getReadTimeout().toMillis(); configRecord.setRead_timeout((int)millis); } configRecord.setPostgREST_ResultDirectory(postgRESTConfig.getResultDirectory()); InterfaceWrapperHelper.saveRecord(configRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\config\PostgRESTConfigRepository.java
2
请完成以下Java代码
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // Background & Foreground Color bg = AdempierePLAF.getFieldBackground_Normal(); // Selected is white on blue in Windows if (isSelected && !hasFocus) bg = table.getSelectionBackground(); // row not selected or field has focus else { // Inactive Background if (!table.isCellEditable(row, col)) bg = AdempierePLAF.getFieldBackground_Inactive(); } // Set Color m_check.setBackground(bg); // Value setValue(value);
return m_check; } // getTableCellRendererComponent /** * Set Value * @param value */ @Override public void setValue(Object value) { if (value != null && ((Boolean)value).booleanValue()) m_check.setSelected(true); else m_check.setSelected(false); } // setValue } // CheckRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\CheckRenderer.java
1
请完成以下Java代码
public boolean isCompatible(final IHUAttributePropagator otherPropagator) { return true; } /** * Always returns {@link X_M_HU_PI_Attribute#PROPAGATIONTYPE_NoPropagation}. */ @Override public String getPropagationType() { return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation; } /** * Always returns {@link X_M_HU_PI_Attribute#PROPAGATIONTYPE_NoPropagation}.
*/ @Override public String getReversalPropagationType() { return getPropagationType(); // same } /** * Does nothing */ @Override public void propagateValue(final IHUAttributePropagationContext propagationContext, final IAttributeStorage attributeSet, final Object value) { // nothing // we are not throwing exception because it's perfectly OK to do nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\NullHUAttributePropagator.java
1
请完成以下Java代码
protected String doIt() throws Exception { I_AD_Migration migration = InterfaceWrapperHelper.create(getCtx(), I_AD_Migration.class, get_TrxName()); MTable table = MTable.get(getCtx(), tableId); String whereClause; List<PO> pos; if (recordId > 0) { pos = new ArrayList<>(1); pos.add(table.getPO(recordId, get_TrxName())); }
else { String where = "EntityType = ?"; pos = table.createQuery(where, get_TrxName()).list(PO.class); } final MFSession session = Services.get(ISessionBL.class).getCurrentSession(getCtx()); final POInfo info = POInfo.getPOInfo(getCtx(), tableId, get_TrxName()); for (PO po : pos) { Services.get(IMigrationLogger.class).logMigration(session, po, info, X_AD_MigrationStep.ACTION_Insert); } return "@OK@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationCreate.java
1
请完成以下Java代码
public class TablesAccessInfo { public static final transient TablesAccessInfo instance = new TablesAccessInfo(); private TablesAccessInfo() { } /** * @return table's access level or null if no table was found. */ @Nullable public final TableAccessLevel getTableAccessLevel(final int adTableId) { return POInfo.getPOInfoIfPresent(AdTableId.ofRepoId(adTableId)).map(POInfo::getAccessLevel).orElse(null); }
public boolean isView(final String tableName) { return POInfo.getPOInfoIfPresent(tableName).map(POInfo::isView).orElse(Boolean.FALSE); } @Nullable public String getSingleKeyColumnNameOrNull(final String tableName) { return POInfo.getPOInfoIfPresent(tableName).map(POInfo::getKeyColumnName).orElse(null); } public Optional<AdTableId> getAdTableId(final String tableName) { return POInfo.getPOInfoIfPresent(tableName).map(POInfo::getAdTableId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\TablesAccessInfo.java
1
请完成以下Java代码
public ModelDynAttributeAccessor<TargetModelType, Integer> getDynAttribute() { return dynAttribute; } @Override public IAggregator<Integer, SourceModelType> createAggregator(final TargetModelType targetModel) { Check.assumeNotNull(targetModel, "targetModel not null"); return new IAggregator<Integer, SourceModelType>() { private final ICompositeQueryFilter<SourceModelType> filters = CountIfQueryAggregateColumnBuilder.this.filters.copy(); private ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute = CountIfQueryAggregateColumnBuilder.this.dynAttribute; private int counter = 0; @Override public void add(final SourceModelType value)
{ if (filters.accept(value)) { counter++; } // Update target model's dynamic attribute dynAttribute.setValue(targetModel, counter); } @Override public Integer getValue() { return counter; } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CountIfQueryAggregateColumnBuilder.java
1
请完成以下Java代码
protected final ITranslatableString buildMessage() { final TranslatableStringBuilder message = TranslatableStrings.builder(); message.append(super.buildMessage()); final TableRecordReference record = getRecord(); if (record != null) { message.append("\n Record: ").append(record.toString()); } if (sql != null) { message.append("\n SQL: ").append(sql); } if (sqlParams != null) { message.append("\n SQL Params: ").append(Arrays.toString(sqlParams)); } if (existingLocks != null) { message.append("\n Existing Locks: ").append(existingLocks.toString()); } appendParameters(message); return message.build(); } @OverridingMethodsMustInvokeSuper public LockException setSql(final String sql, final Object[] sqlParams) { this.sql = sql;
this.sqlParams = sqlParams; resetMessageBuilt(); return this; } @Override @OverridingMethodsMustInvokeSuper public LockException setRecord(final @NonNull TableRecordReference record) { super.setRecord(record); resetMessageBuilt(); return this; } @Override @OverridingMethodsMustInvokeSuper public LockException setParameter(final @NonNull String name, final Object value) { super.setParameter(name, value); return this; } public LockException setExistingLocks(@NonNull final ImmutableList<ExistingLockInfo> existingLocks) { this.existingLocks = existingLocks; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\LockException.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "book_author", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "author_id")) private Set<Author> authors; 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 Set<Author> getAuthors() { return authors; } public void setAuthors(Set<Author> authors) { this.authors = authors; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\associations\unidirectional\Book.java
2
请在Spring Boot框架中完成以下Java代码
private List<SecurityReference> defaultAuth() { List<SecurityReference> securityReferences = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes)); return securityReferences; } /** * 解决Springfox与SpringBoot集成后,WebMvcRequestHandlerProvider和WebFluxRequestHandlerProvider冲突问题 * @return / */ @Bean @SuppressWarnings({"all"}) public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() { return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean)); } return bean; } private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> filteredMappings = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(filteredMappings); } private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); if (field != null) { field.setAccessible(true); try { return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to access handlerMappings field", e); } } return Collections.emptyList(); } }; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\webConfig\SwaggerConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class CockpitId implements RepoIdAware { @JsonCreator public static CockpitId ofRepoId(final int repoId) { return new CockpitId(repoId); } @Nullable public static CockpitId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new CockpitId(repoId) : null; } public static int toRepoId(@Nullable final CockpitId cockpitId) { return cockpitId != null ? cockpitId.getRepoId() : -1; }
int repoId; private CockpitId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "MD_Cockpit_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\CockpitId.java
2
请完成以下Java代码
public String toString() {return getCode();} @JsonValue @NonNull public String getCode() {return code;} public static boolean equals(@Nullable final EventType status1, @Nullable final EventType status2) {return Objects.equals(status1, status2);} } // // // // // @EqualsAndHashCode @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public static class EventStatus { //SCHEDULED, REFUNDED etc public static final EventStatus SCHEDULED = new EventStatus("SCHEDULED"); public static final EventStatus REFUNDED = new EventStatus("REFUNDED"); @NonNull private static final ConcurrentHashMap<String, EventStatus> intern = new ConcurrentHashMap<>(); static { Arrays.asList(SCHEDULED, REFUNDED).forEach(status -> intern.put(status.getCode(), status)); } @NonNull private final String code; private EventStatus(@NonNull final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); if (codeNorm == null) { throw new AdempiereException("Invalid status: " + code); } this.code = codeNorm; } @JsonCreator @NonNull public static EventStatus ofString(@NonNull final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); if (codeNorm == null) { throw new AdempiereException("Invalid status: " + code); } return intern.computeIfAbsent(codeNorm, EventStatus::new); } @Override @Deprecated public String toString() {return getCode();} @JsonValue
@NonNull public String getCode() {return code;} public static boolean equals(@Nullable final EventStatus status1, @Nullable final EventStatus status2) {return Objects.equals(status1, status2);} } // // // // // @Value @Builder @Jacksonized @JsonIgnoreProperties(ignoreUnknown = true) public static class Event { String id; EventType type; EventStatus status; /** * e.g. 2024-10-05T12:48:34.312Z */ String timestamp; BigDecimal amount; @JsonProperty("fee_amount") BigDecimal fee_amount; // other fields: // "deducted_amount": 0.0, // "deducted_fee_amount": 0.0, // "transaction_id": "1a434bf8-bd5c-44a6-8576-37bc9aedc912", // "installment_number": 1, // "payout_reference": "SUMUP PID", @JsonIgnore public boolean isRefunded() { return EventType.equals(type, EventType.REFUND) && EventStatus.equals(status, EventStatus.REFUNDED); } @JsonIgnore public BigDecimal getAmountPlusFee() { BigDecimal result = BigDecimal.ZERO; if (amount != null) { result = result.add(amount); } if (amount != null) { result = result.add(fee_amount); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\json\JsonGetTransactionResponse.java
1
请完成以下Java代码
public BERElement getElement(BERTagDecoder decoder, int tag, InputStream stream, int[] bytesRead, boolean[] implicit) throws IOException { tag &= 0x1F; implicit[0] = false; if (tag == 0) { // Either the choice or the time before expiry within it if (this.inChoice == null) { setInChoice(true); // Read the choice length from the stream (ignored) BERElement.readLengthOctets(stream, bytesRead); int[] componentLength = new int[1]; BERElement choice = new BERChoice(decoder, stream, componentLength); bytesRead[0] += componentLength[0]; // inChoice = null; return choice; } else { // Must be time before expiry return new BERInteger(stream, bytesRead); } } else if (tag == 1) { // Either the graceLogins or the error enumeration.
if (this.inChoice == null) { // The enumeration setInChoice(false); return new BEREnumerated(stream, bytesRead); } else { if (this.inChoice) { // graceLogins return new BERInteger(stream, bytesRead); } } } throw new DataRetrievalFailureException("Unexpected tag " + tag); } private void setInChoice(boolean inChoice) { this.inChoice = inChoice; } } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\ppolicy\PasswordPolicyResponseControl.java
1
请在Spring Boot框架中完成以下Java代码
public class SentinelConfiguration { @Bean public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); } @Bean public NacosDataSource nacosDataSource(ObjectMapper objectMapper) { // Nacos 配置。这里先写死,推荐后面写到 application.yaml 配置文件中。 String serverAddress = "127.0.0.1:8848"; // Nacos 服务器地址 String namespace = ""; // Nacos 命名空间 String dataId = "demo-application-flow-rule"; // Nacos 配置集编号 // String dataId = "example-sentinel"; // Nacos 配置集编号 String group = "DEFAULT_GROUP"; // Nacos 配置分组 // 创建 NacosDataSource 对象 Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddress); properties.setProperty(PropertyKeyConst.NAMESPACE, namespace); NacosDataSource<List<FlowRule>> nacosDataSource = new NacosDataSource<>(properties, group, dataId, new Converter<String, List<FlowRule>>() { // 转换器,将读取的 Nacos 配置,转换成 FlowRule 数组
@Override public List<FlowRule> convert(String value) { try { return Arrays.asList(objectMapper.readValue(value, FlowRule[].class)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); // 注册到 FlowRuleManager 中 FlowRuleManager.register2Property(nacosDataSource.getProperty()); return nacosDataSource; } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-nacos\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java
2
请完成以下Java代码
public void startConnection(String ip, int port) { try { clientSocket = new Socket(ip, port); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (IOException e) { LOG.debug(e.getMessage()); } } public String sendMessage(String msg) { try { out.println(msg); return in.readLine(); } catch (Exception e) {
return null; } } public void stopConnection() { try { in.close(); out.close(); clientSocket.close(); } catch (IOException e) { LOG.debug(e.getMessage()); } } }
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\socket\GreetClient.java
1
请完成以下Java代码
private static UserGroup toUserGroup(@NonNull final I_AD_UserGroup record) { return UserGroup.builder() .id(UserGroupId.ofRepoId(record.getAD_UserGroup_ID())) .name(record.getName()) .build(); } public Set<UserGroupId> getAssignedGroupIdsByUserId(@NonNull final UserId userId) { return getAssignedGroupIdsByUserId(userId, SystemTime.asInstant()); } public Set<UserGroupId> getAssignedGroupIdsByUserId(@NonNull final UserId userId, @NonNull final Instant date) { return assignmentsByUserId .getOrLoad(userId, this::retrieveUserAssignments) .getAssignedGroupIds(date); } @NonNull public UserGroupsCollection getByUserGroupId(@NonNull final UserGroupId userGroupId) { final ImmutableSet<UserGroupUserAssignment> assignments = queryBL .createQueryBuilderOutOfTrx(I_AD_UserGroup_User_Assign.class) .addEqualsFilter(I_AD_UserGroup_User_Assign.COLUMN_AD_UserGroup_ID, userGroupId) .addOnlyActiveRecordsFilter() .create() .stream() .map(UserGroupRepository::toUserGroupUserAssignment) .collect(ImmutableSet.toImmutableSet()); return UserGroupsCollection.of(assignments); } @NonNull private UserIdWithGroupsCollection retrieveUserAssignments(@NonNull final UserId userId) { final ImmutableSet<UserGroupUserAssignment> assignments = queryBL .createQueryBuilderOutOfTrx(I_AD_UserGroup_User_Assign.class) .addEqualsFilter(I_AD_UserGroup_User_Assign.COLUMN_AD_User_ID, userId) .addOnlyActiveRecordsFilter() .create() .stream() .map(UserGroupRepository::toUserGroupUserAssignment) .collect(ImmutableSet.toImmutableSet()); return UserIdWithGroupsCollection.of(assignments); } private static UserGroupUserAssignment toUserGroupUserAssignment(final I_AD_UserGroup_User_Assign record) { return UserGroupUserAssignment.builder() .userId(UserId.ofRepoId(record.getAD_User_ID())) .userGroupId(UserGroupId.ofRepoId(record.getAD_UserGroup_ID())) .validDates(extractValidDates(record)) .build(); }
private static Range<Instant> extractValidDates(final I_AD_UserGroup_User_Assign record) { final Instant validFrom = TimeUtil.asInstant(record.getValidFrom()); final Instant validTo = TimeUtil.asInstant(record.getValidTo()); if (validFrom == null) { if (validTo == null) { return Range.all(); } else { return Range.atMost(validTo); } } else { if (validTo == null) { return Range.atLeast(validFrom); } else { return Range.closed(validFrom, validTo); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserGroupRepository.java
1
请完成以下Java代码
public void onContextCheckOut(final Properties ctx) { final Thread thread = Thread.currentThread(); ctx.setProperty(CTXNAME_ThreadName, thread.getName()); ctx.setProperty(CTXNAME_ThreadId, String.valueOf(thread.getId())); } @Override public void onContextCheckIn(final Properties ctxNew, final Properties ctxOld) { activeContexts.remove(ctxOld); activeContexts.add(ctxNew); } public String[] getActiveContextsInfo() { final List<Properties> activeContextsCopy = new ArrayList<>(activeContexts); final int count = activeContextsCopy.size(); final List<String> activeContextsInfo = new ArrayList<>(count); int index = 1; for (final Properties ctx : activeContextsCopy) { if (ctx == null) { continue; } final String ctxInfo = index + "/" + count + ". " + toInfoString(ctx); activeContextsInfo.add(ctxInfo); index++; }
return activeContextsInfo.toArray(new String[activeContextsInfo.size()]); } private String toInfoString(final Properties ctx) { final String threadName = (String)ctx.get(CTXNAME_ThreadName); final String threadId = (String)ctx.get(CTXNAME_ThreadId); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); final int adUserId = Env.getAD_User_ID(ctx); final int adRoleId = Env.getAD_Role_ID(ctx); final int adSessionId = Env.getAD_Session_ID(ctx); return "Thread=" + threadName + "(" + threadId + ")" // + "\n" + ", Client/Org=" + adClientId + "/" + adOrgId + ", User/Role=" + adUserId + "/" + adRoleId + ", SessionId=" + adSessionId // + "\n" + ", id=" + System.identityHashCode(ctx) + ", " + ctx.getClass() // + "\n" + ", " + ctx.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\TraceContextProviderListener.java
1
请在Spring Boot框架中完成以下Java代码
public void setUrl(String url) { this.url = url; } @ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resources/oneApp.app") public String getUrl() { return url; } public void setContentUrl(String contentUrl) { this.contentUrl = contentUrl; } @ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resourcedata/oneApp.app") public String getContentUrl() { return contentUrl; } public void setMediaType(String mimeType) { this.mediaType = mimeType; }
@ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.") public String getMediaType() { return mediaType; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "appDefinition", value = "Type of resource", allowableValues = "resource,appDefinition") public String getType() { return type; } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResourceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public class ShipmentDeclarationLineId implements RepoIdAware { int repoId; @NonNull ShipmentDeclarationId shipmentDeclarationId; public static ShipmentDeclarationLineId ofRepoId(@NonNull final ShipmentDeclarationId shipmentDeclarationId, final int shipmentDeclarationLineId) { return new ShipmentDeclarationLineId(shipmentDeclarationId, shipmentDeclarationLineId); } public static ShipmentDeclarationLineId ofRepoId(final int shipmentDeclarationId, final int shipmentDeclarationLineId) { return new ShipmentDeclarationLineId(ShipmentDeclarationId.ofRepoId(shipmentDeclarationId), shipmentDeclarationLineId); }
public static ShipmentDeclarationLineId ofRepoIdOrNull( @Nullable final ShipmentDeclarationId shipmentDeclarationId, final int shipmentDeclarationLineId) { return shipmentDeclarationId != null && shipmentDeclarationLineId > 0 ? ofRepoId(shipmentDeclarationId, shipmentDeclarationLineId) : null; } private ShipmentDeclarationLineId(@NonNull final ShipmentDeclarationId shipmentDeclarationId, final int shipmentDeclarationLineId) { this.repoId = Check.assumeGreaterThanZero(shipmentDeclarationLineId, "shipmentDeclarationLineId"); this.shipmentDeclarationId = shipmentDeclarationId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\ShipmentDeclarationLineId.java
2
请在Spring Boot框架中完成以下Java代码
public class WebuiLetterRepository { private final AtomicInteger nextLetterId = new AtomicInteger(1); private final Cache<String, WebuiLetterEntry> lettersById = CacheBuilder.newBuilder() .expireAfterAccess(2, TimeUnit.HOURS) .build(); public WebuiLetter createNewLetter(final WebuiLetterBuilder createRequest) { final WebuiLetter letter = createRequest .letterId(String.valueOf(nextLetterId.getAndIncrement())) .build(); Check.assumeNotNull(letter.getOwnerUserId(), "ownerUserId is not null"); lettersById.put(letter.getLetterId(), new WebuiLetterEntry(letter)); return letter; } private WebuiLetterEntry getLetterEntry(final String letterId) { final WebuiLetterEntry letterEntry = lettersById.getIfPresent(letterId); if (letterEntry == null) { throw new EntityNotFoundException("Letter not found").setParameter("letterId", letterId); } return letterEntry; } public WebuiLetter getLetter(final String letterId) { return getLetterEntry(letterId).getLetter(); } public WebuiLetterChangeResult changeLetter(final String letterId, @NonNull final UnaryOperator<WebuiLetter> letterModifier) { return getLetterEntry(letterId).compute(letterModifier); } public void removeLetterById(final String letterId) { lettersById.invalidate(letterId); } public void createC_Letter(@NonNull final WebuiLetter letter) { final I_C_Letter persistentLetter = InterfaceWrapperHelper.newInstance(I_C_Letter.class); persistentLetter.setLetterSubject(letter.getSubject()); persistentLetter.setLetterBody(Strings.nullToEmpty(letter.getContent())); persistentLetter.setLetterBodyParsed(letter.getContent());
persistentLetter.setAD_BoilerPlate_ID(letter.getTextTemplateId()); persistentLetter.setC_BPartner_ID(letter.getBpartnerId()); persistentLetter.setC_BPartner_Location_ID(letter.getBpartnerLocationId()); persistentLetter.setC_BP_Contact_ID(letter.getBpartnerContactId()); persistentLetter.setBPartnerAddress(Strings.nullToEmpty(letter.getBpartnerAddress())); InterfaceWrapperHelper.save(persistentLetter); } @ToString private static final class WebuiLetterEntry { private WebuiLetter letter; public WebuiLetterEntry(@NonNull final WebuiLetter letter) { this.letter = letter; } public synchronized WebuiLetter getLetter() { return letter; } public synchronized WebuiLetterChangeResult compute(final UnaryOperator<WebuiLetter> modifier) { final WebuiLetter letterOld = letter; final WebuiLetter letterNew = modifier.apply(letterOld); if (letterNew == null) { throw new NullPointerException("letter"); } letter = letterNew; return WebuiLetterChangeResult.builder().letter(letterNew).originalLetter(letterOld).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\letter\WebuiLetterRepository.java
2
请在Spring Boot框架中完成以下Java代码
public final class DefaultInMemoryStorage implements InMemoryStorage { private final ConcurrentHashMap<String, BlockingQueue<TbQueueMsg>> storage = new ConcurrentHashMap<>(); @Override public void printStats() { if (log.isDebugEnabled()) { storage.forEach((topic, queue) -> { if (queue.size() > 0) { log.debug("[{}] Queue Size [{}]", topic, queue.size()); } }); } } @Override public int getLagTotal() { return storage.values().stream().map(BlockingQueue::size).reduce(0, Integer::sum); } @Override public int getLag(String topic) { return Optional.ofNullable(storage.get(topic)).map(Collection::size).orElse(0); } @Override public boolean put(String topic, TbQueueMsg msg) { return storage.computeIfAbsent(topic, (t) -> new LinkedBlockingQueue<>()).add(msg); } @SuppressWarnings("unchecked") @Override public <T extends TbQueueMsg> List<T> get(String topic) throws InterruptedException { final BlockingQueue<TbQueueMsg> queue = storage.get(topic); if (queue != null) { final TbQueueMsg firstMsg = queue.poll();
if (firstMsg != null) { final int queueSize = queue.size(); if (queueSize > 0) { final List<TbQueueMsg> entities = new ArrayList<>(Math.min(queueSize, 999) + 1); entities.add(firstMsg); queue.drainTo(entities, 999); return (List<T>) entities; } return Collections.singletonList((T) firstMsg); } } return Collections.emptyList(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\DefaultInMemoryStorage.java
2
请完成以下Java代码
public boolean shouldContinueEvaluating(boolean ruleResult) { return true; } /** * Default behavior for ComposeRuleOutput behavior */ @Override public void composeRuleResult(int ruleNumber, String outputName, Object outputValue, ELExecutionContext executionContext) { executionContext.addRuleResult(ruleNumber, outputName, outputValue); } /** * Default behavior for ComposeRuleOutput behavior */
@Override public void composeDecisionResults(ELExecutionContext executionContext) { List<Map<String, Object>> decisionResults = new ArrayList<>(executionContext.getRuleResults().values()); updateStackWithDecisionResults(decisionResults, executionContext); DecisionExecutionAuditContainer auditContainer = executionContext.getAuditContainer(); auditContainer.setDecisionResult(decisionResults); auditContainer.setMultipleResults(multipleResults); } @Override public void updateStackWithDecisionResults(List<Map<String, Object>> decisionResults, ELExecutionContext executionContext) { decisionResults.forEach(result -> result.forEach((k, v) -> executionContext.getStackVariables().put(k, v))); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\AbstractHitPolicy.java
1
请完成以下Java代码
private Stream<JsonExternalReferenceLookupItem> getAdditionalExternalReferenceItems( @NonNull final BPartnerId bPartnerId, @NonNull final ExternalSystem externalSystem) { final ExternalReferenceResolver externalReferenceResolver = ExternalReferenceResolver.of(externalSystem, externalReferenceRepository); final BPartnerComposite bPartnerComposite = bpartnerCompositeRepository.getById(bPartnerId); final Stream<Integer> bPartnerLocationIds = bPartnerComposite.streamBPartnerLocationIds() .filter(Objects::nonNull) .map(BPartnerLocationId::getRepoId); final Stream.Builder<JsonExternalReferenceLookupItem> lookupItemCollector = Stream.builder(); externalReferenceResolver.getLookupItems(bPartnerLocationIds, BPLocationExternalReferenceType.BPARTNER_LOCATION) .forEach(lookupItemCollector::add); final Stream<Integer> bPartnerContactIds = bPartnerComposite.streamContactIds() .filter(Objects::nonNull) .map(BPartnerContactId::getRepoId); externalReferenceResolver.getLookupItems(bPartnerContactIds, ExternalUserReferenceType.USER_ID) .forEach(lookupItemCollector::add); return lookupItemCollector.build(); } @NonNull private static JsonExternalReferenceLookupItem toJsonExternalReferenceLookupItem(@NonNull final ExternalReference externalReference) { return JsonExternalReferenceLookupItem.builder() .id(externalReference.getExternalReference()) .type(externalReference.getExternalReferenceType().getCode()) .build(); } @Value(staticConstructor = "of") private static class ExternalReferenceResolver { ExternalSystem externalSystemType;
ExternalReferenceRepository externalReferenceRepository; public Stream<JsonExternalReferenceLookupItem> getLookupItems( @NonNull final Stream<Integer> metasfreshRecordIdStream, @NonNull final IExternalReferenceType externalReferenceType) { return metasfreshRecordIdStream .map(id -> GetExternalReferenceByRecordIdReq.builder() .recordId(id) .externalSystem(externalSystemType) .externalReferenceType(externalReferenceType) .build()) .map(externalReferenceRepository::getExternalReferenceByMFReference) .filter(Optional::isPresent) .map(Optional::get) .map(ExportExternalReferenceToRabbitMQService::toJsonExternalReferenceLookupItem); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\ExportExternalReferenceToRabbitMQService.java
1
请完成以下Java代码
public void setC_TaxCategory_ID (int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_Value (COLUMNNAME_C_TaxCategory_ID, null); else set_Value (COLUMNNAME_C_TaxCategory_ID, Integer.valueOf(C_TaxCategory_ID)); } /** Get Tax Category. @return Tax Category */ public int getC_TaxCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxCategory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Same Currency. @param IsSameCurrency Same Currency */ public void setIsSameCurrency (boolean IsSameCurrency) { set_Value (COLUMNNAME_IsSameCurrency, Boolean.valueOf(IsSameCurrency)); } /** Get Same Currency. @return Same Currency */ public boolean isSameCurrency () { Object oo = get_Value(COLUMNNAME_IsSameCurrency); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Same Tax. @param IsSameTax Use the same tax as the main transaction */ public void setIsSameTax (boolean IsSameTax) { set_Value (COLUMNNAME_IsSameTax, Boolean.valueOf(IsSameTax)); } /** Get Same Tax. @return Use the same tax as the main transaction */ public boolean isSameTax () { Object oo = get_Value(COLUMNNAME_IsSameTax); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Price includes Tax. @param IsTaxIncluded Tax is included in the price */ public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); }
/** Get Price includes Tax. @return Tax is included in the price */ public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded); 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_C_Charge.java
1
请完成以下Java代码
public boolean isAll() { return all; } private void assertNotAll() { if (all) { throw new AdempiereException("method not supported for ALL"); } } public boolean isNone() { return !all && huIds.isEmpty(); } public Integer estimateSize()
{ return all ? null : huIds.size(); } public Stream<HuId> stream() { assertNotAll(); return huIds.stream(); } public ImmutableSet<HuId> toSet() { assertNotAll(); return huIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HuIdsFilterList.java
1
请完成以下Java代码
public void setC_RevenueRecognition_Plan_ID (int C_RevenueRecognition_Plan_ID) { if (C_RevenueRecognition_Plan_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Plan_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Plan_ID, Integer.valueOf(C_RevenueRecognition_Plan_ID)); } /** Get Revenue Recognition Plan. @return Plan for recognizing or recording revenue */ public int getC_RevenueRecognition_Plan_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Plan_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_RevenueRecognition_Plan_ID())); } /** Set Revenue Recognition Run. @param C_RevenueRecognition_Run_ID Revenue Recognition Run or Process */ public void setC_RevenueRecognition_Run_ID (int C_RevenueRecognition_Run_ID) { if (C_RevenueRecognition_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, Integer.valueOf(C_RevenueRecognition_Run_ID)); } /** Get Revenue Recognition Run. @return Revenue Recognition Run or Process */ public int getC_RevenueRecognition_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Run_ID); if (ii == null) return 0; return ii.intValue(); }
public I_GL_Journal getGL_Journal() throws RuntimeException { return (I_GL_Journal)MTable.get(getCtx(), I_GL_Journal.Table_Name) .getPO(getGL_Journal_ID(), get_TrxName()); } /** Set Journal. @param GL_Journal_ID General Ledger Journal */ public void setGL_Journal_ID (int GL_Journal_ID) { if (GL_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, Integer.valueOf(GL_Journal_ID)); } /** Get Journal. @return General Ledger Journal */ public int getGL_Journal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Journal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Recognized Amount. @param RecognizedAmt Recognized Amount */ public void setRecognizedAmt (BigDecimal RecognizedAmt) { set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt); } /** Get Recognized Amount. @return Recognized Amount */ public BigDecimal getRecognizedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Run.java
1
请完成以下Java代码
public ResponseEntity<Object> updateQuartzJob(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){ // 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义 checkBean(resources.getBeanName()); quartzJobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("更改定时任务状态") @ApiOperation("更改定时任务状态") @PutMapping(value = "/{id}") @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){ quartzJobService.updateIsPause(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("执行定时任务") @ApiOperation("执行定时任务") @PutMapping(value = "/exec/{id}") @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){ quartzJobService.execution(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} @Log("删除定时任务") @ApiOperation("删除定时任务") @DeleteMapping @PreAuthorize("@el.check('timing:del')") public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){ quartzJobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } private void checkBean(String beanName){ // 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类 // 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。 if(!SpringBeanHolder.getAllServiceBeanName().contains(beanName)){ throw new BadRequestException("非法的 Bean,请重新输入!"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\rest\QuartzJobController.java
1
请完成以下Java代码
public void setHUIterator(final IHUIterator iterator) { // do nothing; this is an immutable class } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return defaultResult; } @Override public Result afterHU(final I_M_HU hu) { return defaultResult; } @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return defaultResult; }
@Override public Result afterHUItem(final I_M_HU_Item item) { return defaultResult; } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return defaultResult; } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return defaultResult; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\NullHUIteratorListener.java
1
请完成以下Java代码
public class DeleteHistoricDecisionInstanceByInstanceIdCmd implements Command<Object> { protected final String historicDecisionInstanceId; public DeleteHistoricDecisionInstanceByInstanceIdCmd(String historicDecisionInstanceId) { this.historicDecisionInstanceId = historicDecisionInstanceId; } @Override public Object execute(CommandContext commandContext) { ensureNotNull("historicDecisionInstanceId", historicDecisionInstanceId); HistoricDecisionInstance historicDecisionInstance = commandContext .getHistoricDecisionInstanceManager() .findHistoricDecisionInstance(historicDecisionInstanceId); ensureNotNull("No historic decision instance found with id: " + historicDecisionInstanceId, "historicDecisionInstance", historicDecisionInstance); writeUserOperationLog(commandContext, historicDecisionInstance); for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricDecisionInstance(historicDecisionInstance); } commandContext .getHistoricDecisionInstanceManager() .deleteHistoricDecisionInstanceByIds(Arrays.asList(historicDecisionInstanceId)); return null; } protected void writeUserOperationLog(CommandContext commandContext, HistoricDecisionInstance historicDecisionInstance) { List<PropertyChange> propertyChanges = new ArrayList<PropertyChange>(); propertyChanges.add(new PropertyChange("nrOfInstances", null, 1)); propertyChanges.add(new PropertyChange("async", null, false)); commandContext.getOperationLogManager().logDecisionInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, historicDecisionInstance.getTenantId(), propertyChanges); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\DeleteHistoricDecisionInstanceByInstanceIdCmd.java
1
请完成以下Java代码
public final class AuthorityUtils { public static final List<GrantedAuthority> NO_AUTHORITIES = Collections.emptyList(); private AuthorityUtils() { } /** * Creates a array of GrantedAuthority objects from a comma-separated string * representation (e.g. "ROLE_A, ROLE_B, ROLE_C"). * @param authorityString the comma-separated string * @return the authorities created by tokenizing the string */ public static List<GrantedAuthority> commaSeparatedStringToAuthorityList(String authorityString) { return createAuthorityList(StringUtils.tokenizeToStringArray(authorityString, ",")); } /** * Converts an array of GrantedAuthority objects to a Set. * @return a Set of the Strings obtained from each call to * GrantedAuthority.getAuthority() */ public static Set<String> authorityListToSet(Collection<? extends GrantedAuthority> userAuthorities) { Assert.notNull(userAuthorities, "userAuthorities cannot be null"); Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; } /** * Converts authorities into a List of GrantedAuthority objects. * @param authorities the authorities to convert
* @return a List of GrantedAuthority objects */ public static List<GrantedAuthority> createAuthorityList(String... authorities) { Assert.notNull(authorities, "authorities cannot be null"); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities.length); for (String authority : authorities) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } /** * Converts authorities into a List of GrantedAuthority objects. * @param authorities the authorities to convert * @return a List of GrantedAuthority objects * @since 6.1 */ public static List<GrantedAuthority> createAuthorityList(Collection<String> authorities) { List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities.size()); for (String authority : authorities) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\AuthorityUtils.java
1
请完成以下Java代码
public void detachState() { externalTask.getExecution().removeExternalTask(externalTask); externalTask.setExecution(null); } @Override public void attachState(MigratingScopeInstance owningInstance) { ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution(); representativeExecution.addExternalTask(externalTask); externalTask.setExecution(representativeExecution); } @Override public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } @Override public void migrateState() { ScopeImpl targetActivity = migratingActivityInstance.getTargetScope(); ProcessDefinition targetProcessDefinition = (ProcessDefinition) targetActivity.getProcessDefinition(); externalTask.setActivityId(targetActivity.getId()); externalTask.setProcessDefinitionId(targetProcessDefinition.getId());
externalTask.setProcessDefinitionKey(targetProcessDefinition.getKey()); } public String getId() { return externalTask.getId(); } public ScopeImpl getTargetScope() { return migratingActivityInstance.getTargetScope(); } public void addMigratingDependentInstance(MigratingInstance migratingInstance) { dependentInstances.add(migratingInstance); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingExternalTaskInstance.java
1
请完成以下Java代码
public BigDecimal retrieveQtyAvailable(final int wareHouseId, final int locatorId, final int productId, final int attributeSetInstanceId, final String trxName) { return MStorage.getQtyAvailable(wareHouseId, locatorId, productId, attributeSetInstanceId, trxName); } @Override public BigDecimal retrieveQtyOrdered(final int productId, final int warehouseId) { ResultSet rs = null; final PreparedStatement pstmt = DB.prepareStatement( SQL_SELECT_QTY_ORDERED, null); try { pstmt.setInt(1, productId); pstmt.setInt(2, warehouseId); rs = pstmt.executeQuery(); if (rs.next()) { final BigDecimal qtyOrdered = rs.getBigDecimal(1);
if (qtyOrdered == null) { return BigDecimal.ZERO; } return qtyOrdered; } throw new RuntimeException( "Unable to retrive qtyOrdererd for M_Product_ID '" + productId + "'"); } catch (SQLException e) { throw new RuntimeException(e); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StoragePA.java
1
请完成以下Java代码
private void setupEventBus() { final List<Topic> userNotificationsTopics = getAvailableUserNotificationsTopics(); if (userNotificationsTopics != null && !userNotificationsTopics.isEmpty()) { final IEventBusFactory eventBusFactory = Services.get(IEventBusFactory.class); for (final Topic topic : userNotificationsTopics) { eventBusFactory.addAvailableUserNotificationsTopic(topic); } } } /** * @return available user notifications topics to listen */ protected List<Topic> getAvailableUserNotificationsTopics() { return ImmutableList.of(); } private void setupMigrationScriptsLogger() { final Set<String> tableNames = getTableNamesToSkipOnMigrationScriptsLogging(); if (tableNames != null && !tableNames.isEmpty()) { final IMigrationLogger migrationLogger = Services.get(IMigrationLogger.class); migrationLogger.addTablesToIgnoreList(tableNames); } }
protected Set<String> getTableNamesToSkipOnMigrationScriptsLogging() {return ImmutableSet.of();} @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing } /** * Does nothing. Module interceptors are not allowed to intercept models or documents */ @Override public final void onModelChange(final Object model, final ModelChangeType changeType) { // nothing } /** * Does nothing. Module interceptors are not allowed to intercept models or documents */ @Override public final void onDocValidate(final Object model, final DocTimingType timing) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModuleInterceptor.java
1
请完成以下Java代码
public TransportProtos.PostTelemetryMsg convertToPostTelemetry(JsonElement jsonElement) throws AdaptorException { try { return JsonConverter.convertToTelemetryProto(jsonElement); } catch (IllegalStateException | JsonSyntaxException ex) { throw new AdaptorException(ex); } } @Override public TransportProtos.PostAttributeMsg convertToPostAttributes(JsonElement jsonElement) throws AdaptorException { try { return JsonConverter.convertToAttributesProto(jsonElement); } catch (IllegalStateException | JsonSyntaxException ex) { throw new AdaptorException(ex); } } @Override public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(Collection<String> clientKeys, Collection<String> sharedKeys) throws AdaptorException {
try { TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder(); Random random = new Random(); result.setRequestId(random.nextInt()); if (clientKeys != null) { result.addAllClientAttributeNames(clientKeys); } if (sharedKeys != null) { result.addAllSharedAttributeNames(sharedKeys); } return result.build(); } catch (RuntimeException e) { throw new AdaptorException(e); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\adaptors\LwM2MJsonAdaptor.java
1
请完成以下Java代码
public DocumentPrintOptionsIncludingDescriptors getDocumentPrintOptionsIncludingDescriptors( @NonNull final AdProcessId reportProcessId, @NonNull final TableRecordReference recordRef, @NonNull final DocumentReportFlavor flavor) { final StandardDocumentReportType type = StandardDocumentReportType.ofProcessIdOrNull(reportProcessId); if (type != null) { final DocumentReportAdvisor advisor = getAdvisorByType(type); final DocumentReportInfo reportInfo = getDocumentReportInfo(advisor, recordRef, null, null, flavor); final DocumentPrintOptionDescriptorsList printOptionDescriptors = documentPrintOptionDescriptorsRepository.getPrintingOptionDescriptors(reportInfo.getReportProcessId()); final DocumentPrintOptions printOptions = reportInfo.getPrintOptions() .mergeWithFallback(printOptionDescriptors.getDefaults()); return DocumentPrintOptionsIncludingDescriptors.builder() .descriptors(printOptionDescriptors) .values(printOptions) .build(); } else { final DocumentPrintOptionDescriptorsList printOptionDescriptors = documentPrintOptionDescriptorsRepository.getPrintingOptionDescriptors(reportProcessId); return DocumentPrintOptionsIncludingDescriptors.builder() .descriptors(printOptionDescriptors) .values(printOptionDescriptors.getDefaults()) .build(); } } private DocumentReportInfo getDocumentReportInfo( @NonNull final DocumentReportAdvisor advisor, @NonNull final TableRecordReference recordRef, @Nullable final PrintFormatId printFormatIdToUse, @Nullable final AdProcessId reportProcessId, @NonNull final DocumentReportFlavor flavor) { final DocumentReportInfo reportInfo = advisor.getDocumentReportInfo(recordRef, printFormatIdToUse, reportProcessId); return reportInfo.withPrintOptionsFallback(getDocTypePrintOptions(reportInfo.getDocTypeId(), flavor)); }
private DocumentPrintOptions getDocTypePrintOptions( @Nullable final DocTypeId docTypeId, @Nullable final DocumentReportFlavor flavor) { return docTypeId != null && flavor != null ? docTypePrintOptionsRepository.getByDocTypeAndFlavor(docTypeId, flavor) : DocumentPrintOptions.NONE; } public static String getBarcodeServlet( @NonNull final ClientId clientId, @NonNull final OrgId orgId) { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); return sysConfigBL.getValue( ReportConstants.SYSCONFIG_BarcodeServlet, null, // defaultValue, clientId.getRepoId(), orgId.getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportService.java
1
请完成以下Java代码
public int getAsyncExecutorMaxAsyncJobsDuePerAcquisition() { return asyncExecutorMaxAsyncJobsDuePerAcquisition; } public ProcessEngineConfigurationImpl setAsyncExecutorMaxAsyncJobsDuePerAcquisition(int asyncExecutorMaxAsyncJobsDuePerAcquisition) { this.asyncExecutorMaxAsyncJobsDuePerAcquisition = asyncExecutorMaxAsyncJobsDuePerAcquisition; return this; } public int getAsyncExecutorDefaultTimerJobAcquireWaitTime() { return asyncExecutorDefaultTimerJobAcquireWaitTime; } public ProcessEngineConfigurationImpl setAsyncExecutorDefaultTimerJobAcquireWaitTime(int asyncExecutorTimerJobAcquireWaitTime) { this.asyncExecutorDefaultTimerJobAcquireWaitTime = asyncExecutorTimerJobAcquireWaitTime; return this; } public int getAsyncExecutorDefaultAsyncJobAcquireWaitTime() { return asyncExecutorDefaultAsyncJobAcquireWaitTime; } public ProcessEngineConfigurationImpl setAsyncExecutorDefaultAsyncJobAcquireWaitTime(int asyncExecutorDefaultAsyncJobAcquireWaitTime) { this.asyncExecutorDefaultAsyncJobAcquireWaitTime = asyncExecutorDefaultAsyncJobAcquireWaitTime; return this; } public int getAsyncExecutorDefaultQueueSizeFullWaitTime() { return asyncExecutorDefaultQueueSizeFullWaitTime; } public ProcessEngineConfigurationImpl setAsyncExecutorDefaultQueueSizeFullWaitTime(int asyncExecutorDefaultQueueSizeFullWaitTime) { this.asyncExecutorDefaultQueueSizeFullWaitTime = asyncExecutorDefaultQueueSizeFullWaitTime; return this; } public String getAsyncExecutorLockOwner() { return asyncExecutorLockOwner; } public ProcessEngineConfigurationImpl setAsyncExecutorLockOwner(String asyncExecutorLockOwner) { this.asyncExecutorLockOwner = asyncExecutorLockOwner; return this; } public int getAsyncExecutorTimerLockTimeInMillis() { return asyncExecutorTimerLockTimeInMillis; }
public ProcessEngineConfigurationImpl setAsyncExecutorTimerLockTimeInMillis(int asyncExecutorTimerLockTimeInMillis) { this.asyncExecutorTimerLockTimeInMillis = asyncExecutorTimerLockTimeInMillis; return this; } public int getAsyncExecutorAsyncJobLockTimeInMillis() { return asyncExecutorAsyncJobLockTimeInMillis; } public ProcessEngineConfigurationImpl setAsyncExecutorAsyncJobLockTimeInMillis(int asyncExecutorAsyncJobLockTimeInMillis) { this.asyncExecutorAsyncJobLockTimeInMillis = asyncExecutorAsyncJobLockTimeInMillis; return this; } public int getAsyncExecutorLockRetryWaitTimeInMillis() { return asyncExecutorLockRetryWaitTimeInMillis; } public ProcessEngineConfigurationImpl setAsyncExecutorLockRetryWaitTimeInMillis(int asyncExecutorLockRetryWaitTimeInMillis) { this.asyncExecutorLockRetryWaitTimeInMillis = asyncExecutorLockRetryWaitTimeInMillis; return this; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public static JSONObject mergeJSON(JSONObject target, JSONObject source) { for (String key : source.keySet()) { Object sourceItem = source.get(key); // 是否是 JSONObject if (sourceItem instanceof Map) { // target中存在此key if (target.containsKey(key)) { // 两个都是 JSONObject,继续合并 if (target.get(key) instanceof Map) { CommonUtils.mergeJSON(target.getJSONObject(key), source.getJSONObject(key)); continue; } } } // target不存在此key,或不是 JSONObject,则覆盖 target.put(key, sourceItem); } return target; } /** * 将list集合以分割符的方式进行分割 * @param list String类型的集合文本 * @param separator 分隔符 * @return */ public static String getSplitText(List<String> list, String separator) { if (null != list && list.size() > 0) { return StringUtils.join(list, separator); } return ""; } /** * 通过table的条件SQL * * @param tableSql sys_user where name = '1212' * @return name = '1212' */ public static String getFilterSqlByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); if (arr != null && oConvertUtils.isNotEmpty(arr[1])) { return arr[1]; } } return ""; } /** * 通过table获取表名 *
* @param tableSql sys_user where name = '1212' * @return sys_user */ public static String getTableNameByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); return arr[0].trim(); } else { return tableSql; } } /** * 判断两个数组是否存在交集 * @param set1 * @param arr2 * @return */ public static boolean hasIntersection(Set<String> set1, String[] arr2) { if (set1 == null) { return false; } if(set1.size()>0){ for (String str : arr2) { if (set1.contains(str)) { return true; } } } return false; } /** * 输出info日志,会捕获异常,防止因为日志问题导致程序异常 * * @param msg * @param objects */ public static void logInfo(String msg, Object... objects) { try { log.info(msg, objects); } catch (Exception e) { log.warn("{} —— {}", msg, e.getMessage()); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\CommonUtils.java
1
请完成以下Java代码
public class DonAsynchron { public static <T> void withCallback(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure) { withCallback(future, onSuccess, onFailure, null); } public static <T> void withCallback(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor) { FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(T result) { if (onSuccess == null) { return; } try { onSuccess.accept(result); } catch (Throwable th) { onFailure(th); } } @Override public void onFailure(Throwable t) { if (onFailure == null) { return; } onFailure.accept(t); } };
if (executor != null) { Futures.addCallback(future, callback, executor); } else { Futures.addCallback(future, callback, MoreExecutors.directExecutor()); } } public static <T> ListenableFuture<T> submit(Callable<T> task, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor) { return submit(task, onSuccess, onFailure, executor, null); } public static <T> ListenableFuture<T> submit(Callable<T> task, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor, Executor callbackExecutor) { ListenableFuture<T> future = Futures.submit(task, executor); withCallback(future, onSuccess, onFailure, callbackExecutor); return future; } public static <T> FluentFuture<T> toFluentFuture(CompletableFuture<T> completable) { SettableFuture<T> future = SettableFuture.create(); completable.whenComplete((result, exception) -> { if (exception != null) { future.setException(exception); } else { future.set(result); } }); return FluentFuture.from(future); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\DonAsynchron.java
1
请完成以下Java代码
public class CatchEventXMLConverter extends BaseBpmnXMLConverter { protected Map<String, BaseChildElementParser> childParserMap = new HashMap<>(); public CatchEventXMLConverter() { InParameterParser inParameterParser = new InParameterParser(); childParserMap.put(inParameterParser.getElementName(), inParameterParser); VariableListenerEventDefinitionParser variableListenerEventDefinitionParser = new VariableListenerEventDefinitionParser(); childParserMap.put(variableListenerEventDefinitionParser.getElementName(), variableListenerEventDefinitionParser); } @Override public Class<? extends BaseElement> getBpmnElementType() { return IntermediateCatchEvent.class; } @Override protected String getXMLElementName() { return ELEMENT_EVENT_CATCH; } @Override @SuppressWarnings("unchecked") protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { IntermediateCatchEvent catchEvent = new IntermediateCatchEvent(); BpmnXMLUtil.addXMLLocation(catchEvent, xtr); String elementId = xtr.getAttributeValue(null, ATTRIBUTE_ID); catchEvent.setId(elementId); BpmnXMLUtil.addCustomAttributes(xtr, catchEvent, defaultElementAttributes, defaultActivityAttributes); parseChildElements(getXMLElementName(), catchEvent, childParserMap, model, xtr);
return catchEvent; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { } @Override protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception { IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) element; didWriteExtensionStartElement = writeVariableListenerDefinition(catchEvent, didWriteExtensionStartElement, xtw); return didWriteExtensionStartElement; } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) element; writeEventDefinitions(catchEvent, catchEvent.getEventDefinitions(), model, xtw); } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\CatchEventXMLConverter.java
1
请完成以下Java代码
public List<WorkQueue> getQueueRecordsToStore() { return queueItemsToProcess; } @Override public List<WorkQueue> getQueueRecordsToDelete() { return queueItemsToDelete; } /** * @return the {@link Partition} from the last invokation of {@link #clearAfterPartitionStored(Partition)}, or an empty partition. */ @Override public Partition getPartition() { return partition; } @Override public void registerHandler(IIterateResultHandler handler) { handlerSupport.registerListener(handler); } @Override public List<IIterateResultHandler> getRegisteredHandlers() { return handlerSupport.getRegisteredHandlers(); } @Override public boolean isHandlerSignaledToStop() {
return handlerSupport.isHandlerSignaledToStop(); } @Override public String toString() { return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size() + ", queueItemsToDelete.size()=" + queueItemsToDelete.size() + ", size=" + size + ", tableName2Record.size()=" + tableName2Record.size() + ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size() + ", iterator=" + iterator + ", ctxAware=" + ctxAware + ", partition=" + partition + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java
1
请完成以下Java代码
public void setIsPurchaseQty (boolean IsPurchaseQty) { set_Value (COLUMNNAME_IsPurchaseQty, Boolean.valueOf(IsPurchaseQty)); } /** Get Purchase Quantity. @return This quantity is used in the Purchase Order to the Supplier */ @Override public boolean isPurchaseQty () { Object oo = get_Value(COLUMNNAME_IsPurchaseQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set RfQ Quantity. @param IsRfQQty The quantity is used when generating RfQ Responses */ @Override public void setIsRfQQty (boolean IsRfQQty) { set_Value (COLUMNNAME_IsRfQQty, Boolean.valueOf(IsRfQQty)); } /** Get RfQ Quantity. @return The quantity is used when generating RfQ Responses */ @Override public boolean isRfQQty () { Object oo = get_Value(COLUMNNAME_IsRfQQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Margin %. @param Margin Margin for a product as a percentage */ @Override public void setMargin (java.math.BigDecimal Margin) { set_Value (COLUMNNAME_Margin, Margin); } /** Get Margin %. @return Margin for a product as a percentage */ @Override public java.math.BigDecimal getMargin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Offer Amount. @param OfferAmt Amount of the Offer
*/ @Override public void setOfferAmt (java.math.BigDecimal OfferAmt) { set_Value (COLUMNNAME_OfferAmt, OfferAmt); } /** Get Offer Amount. @return Amount of the Offer */ @Override public java.math.BigDecimal getOfferAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java
1
请完成以下Java代码
public static List<Term> segment(String text) { return SEGMENT.seg(text); } /** * 分词 * @param text 文本 * @return 分词结果 */ public static List<Term> segment(char[] text) { return SEGMENT.seg(text); } /** * 切分为句子形式 * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text)
{ return SEGMENT.seg2sentence(text); } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\IndexTokenizer.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_OrgType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Organization Type. @param AD_OrgType_ID Organization Type */ public void setAD_OrgType_ID (int AD_OrgType_ID) { if (AD_OrgType_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_OrgType_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_OrgType_ID, Integer.valueOf(AD_OrgType_ID)); } /** Get Organization Type. @return Organization Type */ public int getAD_OrgType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgType_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_PrintColor getAD_PrintColor() throws RuntimeException { return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name) .getPO(getAD_PrintColor_ID(), get_TrxName()); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_Value (COLUMNNAME_AD_PrintColor_ID, null); else set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgType.java
1
请完成以下Java代码
public boolean isFiFo() { return MMPOLICY_FiFo.equals(getMMPolicy()); } // isFiFo static void assertNoLoopInTree(final I_M_Product_Category productCategory) { if (hasLoopInTree(productCategory)) { throw new AdempiereException("@ProductCategoryLoopDetected@"); } } /** * Loop detection of product category tree. */ private static boolean hasLoopInTree (final I_M_Product_Category productCategory) { final int productCategoryId = productCategory.getM_Product_Category_ID(); final int newParentCategoryId = productCategory.getM_Product_Category_Parent_ID(); // get values ResultSet rs = null; PreparedStatement pstmt = null; final String sql = " SELECT M_Product_Category_ID, M_Product_Category_Parent_ID FROM M_Product_Category"; final Vector<SimpleTreeNode> categories = new Vector<>(100); try { pstmt = DB.prepareStatement(sql, null); rs = pstmt.executeQuery(); while (rs.next()) { if (rs.getInt(1) == productCategoryId) categories.add(new SimpleTreeNode(rs.getInt(1), newParentCategoryId)); categories.add(new SimpleTreeNode(rs.getInt(1), rs.getInt(2))); } if (hasLoop(newParentCategoryId, categories, productCategoryId)) return true; } catch (final SQLException e) { log.error(sql, e); return true; } finally { DB.close(rs, pstmt); } return false; } // hasLoopInTree /** * Recursive search for parent nodes - climbs the to the root. * If there is a circle there is no root but it comes back to the start node.
*/ private static boolean hasLoop(final int parentCategoryId, final Vector<SimpleTreeNode> categories, final int loopIndicatorId) { final Iterator<SimpleTreeNode> iter = categories.iterator(); boolean ret = false; while (iter.hasNext()) { final SimpleTreeNode node = iter.next(); if(node.getNodeId()==parentCategoryId){ if (node.getParentId()==0) { //root node, all fine return false; } if(node.getNodeId()==loopIndicatorId){ //loop found return true; } ret = hasLoop(node.getParentId(), categories, loopIndicatorId); } } return ret; } //hasLoop /** * Simple class for tree nodes. * @author Karsten Thiemann, kthiemann@adempiere.org * */ private static class SimpleTreeNode { /** id of the node */ private final int nodeId; /** id of the nodes parent */ private final int parentId; public SimpleTreeNode(final int nodeId, final int parentId) { this.nodeId = nodeId; this.parentId = parentId; } public int getNodeId() { return nodeId; } public int getParentId() { return parentId; } } } // MProductCategory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MProductCategory.java
1
请完成以下Java代码
public Set<String> getPatterns() { return this.patterns; } public List<MediaTypeExpressionDescription> getProduces() { return this.produces; } /** * A description of a {@link MediaTypeExpression} in a request mapping condition. */ public static class MediaTypeExpressionDescription { private final String mediaType; private final boolean negated; MediaTypeExpressionDescription(MediaTypeExpression expression) { this.mediaType = expression.getMediaType().toString(); this.negated = expression.isNegated(); } public String getMediaType() { return this.mediaType; } public boolean isNegated() { return this.negated; } } /** * A description of a {@link NameValueExpression} in a request mapping condition. */ public static class NameValueExpressionDescription { private final String name;
private final @Nullable Object value; private final boolean negated; NameValueExpressionDescription(NameValueExpression<?> expression) { this.name = expression.getName(); this.value = expression.getValue(); this.negated = expression.isNegated(); } public String getName() { return this.name; } public @Nullable Object getValue() { return this.value; } public boolean isNegated() { return this.negated; } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\RequestMappingConditionsDescription.java
1
请完成以下Java代码
public Optional<I_M_HU_PI_Attribute> getByAttributeIdIfExists(final AttributeId attributeId) { final I_M_HU_PI_Attribute piAttribute = getByAttributeIdOrNull(attributeId); return Optional.ofNullable(piAttribute); } private I_M_HU_PI_Attribute getByAttributeIdOrNull(final AttributeId attributeId) { return attributesByAttributeId.get(attributeId); } public PIAttributes addIfAbsent(@NonNull final PIAttributes from) { if (from.isEmpty()) { return this; } if (this.isEmpty()) { return from; } final LinkedHashMap<AttributeId, I_M_HU_PI_Attribute> piAttributesNew = new LinkedHashMap<>(attributesByAttributeId); from.attributesByAttributeId.forEach(piAttributesNew::putIfAbsent); return of(piAttributesNew.values());
} public int getSeqNoByAttributeId(final AttributeId attributeId, final int seqNoIfNotFound) { final I_M_HU_PI_Attribute piAttribute = getByAttributeIdOrNull(attributeId); if (piAttribute == null) { return seqNoIfNotFound; } return piAttribute.getSeqNo(); } public ImmutableSet<AttributeId> getAttributeIds() { return attributesByAttributeId.keySet(); } public boolean isEmpty() { return attributesByAttributeId.isEmpty(); } public boolean isUseInASI(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId).isUseInASI(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\PIAttributes.java
1
请完成以下Java代码
public final Throwable[] determineCauseChain(Throwable throwable) { Assert.notNull(throwable, "Invalid throwable: null"); List<Throwable> chain = new ArrayList<>(); Throwable currentThrowable = throwable; while (currentThrowable != null) { chain.add(currentThrowable); currentThrowable = extractCause(currentThrowable); } return chain.toArray(new Throwable[0]); } /** * Extracts the cause of the given throwable using an appropriate extractor. * @param throwable the <code>Throwable</code> (not <code>null</code> * @return the cause, may be <code>null</code> if none could be resolved */ private @Nullable Throwable extractCause(Throwable throwable) { for (Map.Entry<Class<? extends Throwable>, ThrowableCauseExtractor> entry : this.extractorMap.entrySet()) { Class<? extends Throwable> throwableType = entry.getKey(); if (throwableType.isInstance(throwable)) { ThrowableCauseExtractor extractor = entry.getValue(); return extractor.extractCause(throwable); } } return null; } /** * Returns the first throwable from the passed in array that is assignable to the * provided type. A returned instance is safe to be cast to the specified type. * <p> * If the passed in array is null or empty this method returns <code>null</code>. * @param throwableType the type to look for * @param chain the array (will be processed in element order) * @return the found <code>Throwable</code>, <code>null</code> if not found * @throws IllegalArgumentException if the provided type is <code>null</code> or no * subclass of <code>Throwable</code> */ public final @Nullable Throwable getFirstThrowableOfType(Class<? extends Throwable> throwableType, Throwable[] chain) { if (chain != null) { for (Throwable t : chain) { if ((t != null) && throwableType.isInstance(t)) { return t; } } }
return null; } /** * Verifies that the provided throwable is a valid subclass of the provided type (or * of the type itself). If <code>expectedBaseType</code> is <code>null</code>, no * check will be performed. * <p> * Can be used for verification purposes in implementations of * {@link ThrowableCauseExtractor extractors}. * @param throwable the <code>Throwable</code> to check * @param expectedBaseType the type to check against * @throws IllegalArgumentException if <code>throwable</code> is either * <code>null</code> or its type is not assignable to <code>expectedBaseType</code> */ public static void verifyThrowableHierarchy(Throwable throwable, Class<? extends Throwable> expectedBaseType) { if (expectedBaseType == null) { return; } Assert.notNull(throwable, "Invalid throwable: null"); Class<? extends Throwable> throwableType = throwable.getClass(); Assert.isTrue(expectedBaseType.isAssignableFrom(throwableType), () -> "Invalid type: '" + throwableType.getName() + "'. Has to be a subclass of '" + expectedBaseType.getName() + "'"); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\ThrowableAnalyzer.java
1
请完成以下Java代码
public void doLock() { } /** * 环绕操作 * * @param point 切入点 * @return 原方法返回值 * @throws Throwable 异常信息 */ @Around("doLock()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Object[] args = point.getArgs(); ZooLock zooLock = method.getAnnotation(ZooLock.class); if (StrUtil.isBlank(zooLock.key())) { throw new RuntimeException("分布式锁键不能为空"); } String lockKey = buildLockKey(zooLock, method, args); InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey); try { // 假设上锁成功,以后拿到的都是 false if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) { return point.proceed(); } else { throw new RuntimeException("请勿重复提交"); } } finally { lock.release(); } } /** * 构造分布式锁的键 * * @param lock 注解 * @param method 注解标记的方法 * @param args 方法上的参数 * @return * @throws NoSuchFieldException * @throws IllegalAccessException */ private String buildLockKey(ZooLock lock, Method method, Object[] args) throws NoSuchFieldException, IllegalAccessException { StringBuilder key = new StringBuilder(KEY_SEPARATOR + KEY_PREFIX + lock.key()); // 迭代全部参数的注解,根据使用LockKeyParam的注解的参数所在的下标,来获取args中对应下标的参数值拼接到前半部分key上 Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) {
// 循环该参数全部注解 for (Annotation annotation : parameterAnnotations[i]) { // 注解不是 @LockKeyParam if (!annotation.annotationType().isInstance(LockKeyParam.class)) { continue; } // 获取所有fields String[] fields = ((LockKeyParam) annotation).fields(); if (ArrayUtil.isEmpty(fields)) { // 普通数据类型直接拼接 if (ObjectUtil.isNull(args[i])) { throw new RuntimeException("动态参数不能为null"); } key.append(KEY_SEPARATOR).append(args[i]); } else { // @LockKeyParam的fields值不为null,所以当前参数应该是对象类型 for (String field : fields) { Class<?> clazz = args[i].getClass(); Field declaredField = clazz.getDeclaredField(field); declaredField.setAccessible(true); Object value = declaredField.get(clazz); key.append(KEY_SEPARATOR).append(value); } } } } return key.toString(); } }
repos\spring-boot-demo-master\demo-zookeeper\src\main\java\com\xkcoding\zookeeper\aspectj\ZooLockAspect.java
1
请完成以下Java代码
public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseCatalog() { return databaseCatalog; } public void setDatabaseCatalog(String databaseCatalog) { this.databaseCatalog = databaseCatalog; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema; } public boolean isTablePrefixIsSchema() { return tablePrefixIsSchema; } public int getMaxNrOfStatementsInBulkInsert() { return maxNrOfStatementsInBulkInsert; } public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) { this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java
1
请完成以下Java代码
private void copyHUStorage(final I_M_HU_Storage oldHUStorage) { final HuId oldHUId = HuId.ofRepoId(oldHUStorage.getM_HU_ID()); final HuId newHUId = old2new_M_HU_ID.get(oldHUId); if (newHUId == null) { throw new AdempiereException("HU was not already cloned for " + oldHUId); } final I_M_HU_Storage newHUStorage = InterfaceWrapperHelper.newInstance(I_M_HU_Storage.class); InterfaceWrapperHelper.copyValues(oldHUStorage, newHUStorage); newHUStorage.setM_HU_ID(newHUId.getRepoId()); InterfaceWrapperHelper.save(newHUStorage); } private void copyHUItemStorage(final I_M_HU_Item_Storage oldHUItemStorage)
{ final HuItemId oldHUItemId = HuItemId.ofRepoId(oldHUItemStorage.getM_HU_Item_ID()); final HuItemId newHUItemId = old2new_M_HU_Item_ID.get(oldHUItemId); if (newHUItemId == null) { throw new AdempiereException("HU Item was not already cloned for " + oldHUItemId); } final I_M_HU_Item_Storage newHUItemStorage = InterfaceWrapperHelper.newInstance(I_M_HU_Item_Storage.class); InterfaceWrapperHelper.copyValues(oldHUItemStorage, newHUItemStorage); newHUItemStorage.setM_HU_Item_ID(newHUItemId.getRepoId()); InterfaceWrapperHelper.save(newHUItemStorage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CopyHUsCommand.java
1
请完成以下Java代码
public Class<? extends DbEntity> getEntityType() { return AcquirableJobEntity.class; } @Override public OptimisticLockingResult failedOperation(DbOperation operation) { if (operation instanceof DbEntityOperation) { DbEntityOperation entityOperation = (DbEntityOperation) operation; // could not lock the job -> remove it from list of acquired jobs acquiredJobs.removeJobId(entityOperation.getEntity().getId()); // When the job that failed the lock with an OLE is removed, // we suppress the OLE. return OptimisticLockingResult.IGNORE; } // If none of the conditions are satisfied, this might indicate a bug, // so we throw the OLE.
return OptimisticLockingResult.THROW; } protected boolean isAcquireExclusiveOverProcessHierarchies(CommandContext context) { var engineConfig = context.getProcessEngineConfiguration(); return engineConfig != null && engineConfig.isJobExecutorAcquireExclusiveOverProcessHierarchies(); } protected String selectProcessInstanceId(AcquirableJobEntity job, boolean isAcquireExclusiveOverProcessHierarchies) { if (isAcquireExclusiveOverProcessHierarchies && job.getRootProcessInstanceId() != null) { return job.getRootProcessInstanceId(); } return job.getProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AcquireJobsCmd.java
1
请在Spring Boot框架中完成以下Java代码
public at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType getTaxExtension() { return taxExtension; } /** * Sets the value of the taxExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType } * */ public void setTaxExtension(at.erpel.schemas._1p0.documents.extensions.edifact.TaxExtensionType value) { this.taxExtension = value; } /** * Gets the value of the erpelTaxExtension property. * * @return * possible object is * {@link CustomType } * */
public CustomType getErpelTaxExtension() { return erpelTaxExtension; } /** * Sets the value of the erpelTaxExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelTaxExtension(CustomType value) { this.erpelTaxExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\TaxExtensionType.java
2
请完成以下Java代码
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return getScannedQRCode(wfProcess, wfActivity) != null ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final ManufacturingJobActivityId jobActivityId = request.getWfActivity().getId().getAsId(ManufacturingJobActivityId.class); final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(request.getWfProcess()); final ManufacturingJobActivity activity = job.getActivityById(jobActivityId); final GlobalQRCode scannedQRCode = GlobalQRCode.ofString(request.getScannedBarcode()); validateScannedQRCode(activity, scannedQRCode); final ManufacturingJob changedJob = manufacturingJobService.withScannedQRCode(job, jobActivityId, scannedQRCode); return ManufacturingRestService.toWFProcess(changedJob); } @Nullable private ImmutableList<JsonQRCode> getSourceLocatorQRCodes(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); final ManufacturingJobActivity activity = job.getActivityById(wfActivity.getId()); if (activity.getSourceLocatorValidate() == null) { return null; } return activity.getSourceLocatorValidate() .getSourceLocatorList() .stream() .map(locatorInfo -> JsonQRCode.builder() .caption(locatorInfo.getCaption()) .qrCode(LocatorQRCode.builder() .locatorId(locatorInfo.getId()) .caption(locatorInfo.getCaption()) .build().toGlobalQRCodeJsonString())
.build()) .collect(ImmutableList.toImmutableList()); } @Nullable private static GlobalQRCode getScannedQRCode(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); final ManufacturingJobActivityId jobActivityId = wfActivity.getId().getAsId(ManufacturingJobActivityId.class); final ManufacturingJobActivity jobActivity = job.getActivityById(jobActivityId); return jobActivity.getScannedQRCode(); } private static void validateScannedQRCode( @NonNull final ManufacturingJobActivity activity, @NonNull final GlobalQRCode qrCode) { final ValidateLocatorInfo validateLocatorInfo = activity.getSourceLocatorValidate(); if (validateLocatorInfo == null) { throw new AdempiereException(NO_SOURCE_LOCATOR_ERR_MSG); } if (!LocatorQRCode.isTypeMatching(qrCode)) { throw new AdempiereException(QR_CODE_INVALID_TYPE_ERR_MSG); } final LocatorId scannedLocatorId = LocatorQRCode.ofGlobalQRCode(qrCode).getLocatorId(); if (!validateLocatorInfo.isLocatorIdValid(scannedLocatorId)) { throw new AdempiereException(QR_CODE_DOES_NOT_MATCH_ERR_MSG); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\validateLocator\ValidateLocatorActivityHandler.java
1
请完成以下Java代码
public void setDt(XMLGregorianCalendar value) { this.dt = value; } /** * Gets the value of the ctry property. * * @return * possible object is * {@link String } * */ public String getCtry() { return ctry; } /** * Sets the value of the ctry property. * * @param value * allowed object is * {@link String } * */ public void setCtry(String value) { this.ctry = value; } /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAmt() {
return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the inf 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 inf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getInf() { if (inf == null) { inf = new ArrayList<String>(); } return this.inf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\StructuredRegulatoryReporting3.java
1
请在Spring Boot框架中完成以下Java代码
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { if (isOidcProvider(userRequest.getClientRegistration())) { // 尝试获取 OIDC ID Token OidcIdToken idToken = extractOidcIdToken(userRequest); OidcUserRequest oidcUserRequest = new OidcUserRequest( userRequest.getClientRegistration(), userRequest.getAccessToken(), idToken); return oidcUserService.loadUser(oidcUserRequest); } else { return defaultOAuth2UserService.loadUser(userRequest); } } private boolean isOidcProvider(ClientRegistration clientRegistration) { return clientRegistration.getProviderDetails() .getConfigurationMetadata() .containsKey("userinfo_endpoint"); }
private OidcIdToken extractOidcIdToken(OAuth2UserRequest userRequest) { // 从 userRequest 中获取 OIDC ID Token,这里假设它已经包含在 access token response 的附加参数中 // 如果不存在,则需要处理这个情况,可能是返回 null 或抛出异常 Map<String, Object> additionalParameters = userRequest.getAdditionalParameters(); Object idTokenObj = additionalParameters.get("id_token"); if (idTokenObj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> idTokenClaims = (Map<String, Object>) idTokenObj; return new OidcIdToken(userRequest.getAccessToken().getTokenValue(), userRequest.getAccessToken().getIssuedAt(), userRequest.getAccessToken().getExpiresAt(), idTokenClaims); } throw new OAuth2AuthenticationException(new OAuth2Error("invalid_id_token"), "Invalid or missing ID token"); } }
repos\springboot-demo-master\keycloak\src\main\java\com\et\service\CustomOAuth2UserService.java
2
请完成以下Java代码
public final class ExpressionBasedFilterInvocationSecurityMetadataSource extends DefaultFilterInvocationSecurityMetadataSource { private static final Log logger = LogFactory.getLog(ExpressionBasedFilterInvocationSecurityMetadataSource.class); public ExpressionBasedFilterInvocationSecurityMetadataSource( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap, SecurityExpressionHandler<FilterInvocation> expressionHandler) { super(processMap(requestMap, expressionHandler.getExpressionParser())); Assert.notNull(expressionHandler, "A non-null SecurityExpressionHandler is required"); } private static LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processMap( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap, ExpressionParser parser) { Assert.notNull(parser, "SecurityExpressionHandler returned a null parser object"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processed = new LinkedHashMap<>(requestMap); requestMap.forEach((request, value) -> process(parser, request, value, processed::put)); return processed; } private static void process(ExpressionParser parser, RequestMatcher request, Collection<ConfigAttribute> value, BiConsumer<RequestMatcher, Collection<ConfigAttribute>> consumer) { String expression = getExpression(request, value); if (logger.isDebugEnabled()) { logger.debug(LogMessage.format("Adding web access control expression [%s] for %s", expression, request)); } AbstractVariableEvaluationContextPostProcessor postProcessor = createPostProcessor(request); ArrayList<ConfigAttribute> processed = new ArrayList<>(1); try { processed.add(new WebExpressionConfigAttribute(parser.parseExpression(expression), postProcessor)); } catch (ParseException ex) { throw new IllegalArgumentException("Failed to parse expression '" + expression + "'");
} consumer.accept(request, processed); } private static String getExpression(RequestMatcher request, Collection<ConfigAttribute> value) { Assert.isTrue(value.size() == 1, () -> "Expected a single expression attribute for " + request); return value.toArray(new ConfigAttribute[1])[0].getAttribute(); } private static AbstractVariableEvaluationContextPostProcessor createPostProcessor(RequestMatcher request) { return new RequestVariablesExtractorEvaluationContextPostProcessor(request); } static class RequestVariablesExtractorEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor { private final RequestMatcher matcher; RequestVariablesExtractorEvaluationContextPostProcessor(RequestMatcher matcher) { this.matcher = matcher; } @Override Map<String, String> extractVariables(HttpServletRequest request) { return this.matcher.matcher(request).getVariables(); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\ExpressionBasedFilterInvocationSecurityMetadataSource.java
1
请完成以下Java代码
public @Nullable KeyResolver getKeyResolver() { return keyResolver; } public Config setKeyResolver(KeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } public @Nullable RateLimiter getRateLimiter() { return rateLimiter; } public Config setRateLimiter(RateLimiter rateLimiter) { this.rateLimiter = rateLimiter; return this; } public HttpStatus getStatusCode() { return statusCode; } public Config setStatusCode(HttpStatus statusCode) { this.statusCode = statusCode; return this; } public @Nullable Boolean getDenyEmptyKey() { return denyEmptyKey; } public Config setDenyEmptyKey(Boolean denyEmptyKey) { this.denyEmptyKey = denyEmptyKey; return this; } public @Nullable String getEmptyKeyStatus() { return emptyKeyStatus; }
public Config setEmptyKeyStatus(String emptyKeyStatus) { this.emptyKeyStatus = emptyKeyStatus; return this; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override public @Nullable String getRouteId() { return this.routeId; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestRateLimiterGatewayFilterFactory.java
1
请完成以下Java代码
private String createExternalId( @NonNull final JsonOLCandCreateRequest request, final int recordId) { final String externalHeaderId = assumeNotEmpty(request.getExternalHeaderId(), "request.externalHeaderId may not be empty; request={}", request); return "" + externalHeaderId + "_" + recordId; } private JsonProductInfo createProduct( @NonNull final String productCode, @NonNull final String productName, @NonNull final XmlToOLCandsService.HighLevelContext context) { return JsonProductInfo.builder() .syncAdvise(context.getProductsSyncAdvise()) .code(productCode) .name(productName) .type(JsonProductInfo.Type.SERVICE) .uomCode(UOM_CODE) .build(); } private BigDecimal createPrice(@NonNull final RecordOtherType recordOtherType)
{ return createPrice( recordOtherType.getUnit(), recordOtherType.getUnitFactor(), recordOtherType.getExternalFactor()); } private BigDecimal createPrice( @Nullable final BigDecimal unit, @Nullable final BigDecimal unitFactor, @Nullable final BigDecimal externalFactor) { final BigDecimal unitToUse = coalesce(unit, ONE); // tax point (TP) of the applied service final BigDecimal unitFactorToUse = coalesce(unitFactor, ONE); // tax point value (TPV) of the applied service final BigDecimal externalFactorToUse = coalesce(externalFactor, ONE); return unitToUse.multiply(unitFactorToUse).multiply(externalFactorToUse); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_rest-api\src\main\java\de\metas\vertical\healthcare\forum_datenaustausch_ch\rest\xml_to_olcands\XmlServiceRecordUtil.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Benchmark. @param PA_Benchmark_ID Performance Benchmark */ public void setPA_Benchmark_ID (int PA_Benchmark_ID) { if (PA_Benchmark_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID)); } /** Get Benchmark. @return Performance Benchmark */ public int getPA_Benchmark_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Benchmark.java
1
请完成以下Java代码
public int getAD_Table_AttachmentListener_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_AttachmentListener_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DB-Tabelle. @param AD_Table_ID Database Table information */ @Override public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Send Notification. @param IsSendNotification Send Notification */ @Override public void setIsSendNotification (boolean IsSendNotification) { set_Value (COLUMNNAME_IsSendNotification, Boolean.valueOf(IsSendNotification)); } /** Get Send Notification. @return Send Notification */ @Override public boolean isSendNotification () { Object oo = get_Value(COLUMNNAME_IsSendNotification); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_AttachmentListener.java
1
请完成以下Java代码
protected Object doSuspend(Object transaction) { RabbitTransactionObject txObject = (RabbitTransactionObject) transaction; txObject.setResourceHolder(null); return TransactionSynchronizationManager.unbindResource(getResourceFactory()); } @Override protected void doResume(@Nullable Object transaction, Object suspendedResources) { RabbitResourceHolder conHolder = (RabbitResourceHolder) suspendedResources; TransactionSynchronizationManager.bindResource(getResourceFactory(), conHolder); } @Override protected void doCommit(DefaultTransactionStatus status) { RabbitTransactionObject txObject = (RabbitTransactionObject) status.getTransaction(); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.commitAll(); } } @Override protected void doRollback(DefaultTransactionStatus status) { RabbitTransactionObject txObject = (RabbitTransactionObject) status.getTransaction(); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.rollbackAll(); } } @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { RabbitTransactionObject txObject = (RabbitTransactionObject) status.getTransaction(); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.setRollbackOnly(); } } @Override protected void doCleanupAfterCompletion(Object transaction) {
RabbitTransactionObject txObject = (RabbitTransactionObject) transaction; TransactionSynchronizationManager.unbindResource(getResourceFactory()); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.closeAll(); resourceHolder.clear(); } } /** * Rabbit transaction object, representing a RabbitResourceHolder. Used as transaction object by * RabbitTransactionManager. * @see RabbitResourceHolder */ private static class RabbitTransactionObject implements SmartTransactionObject { private @Nullable RabbitResourceHolder resourceHolder; RabbitTransactionObject() { } public void setResourceHolder(@Nullable RabbitResourceHolder resourceHolder) { this.resourceHolder = resourceHolder; } public @Nullable RabbitResourceHolder getResourceHolder() { return this.resourceHolder; } @Override public boolean isRollbackOnly() { return this.resourceHolder != null && this.resourceHolder.isRollbackOnly(); } @Override public void flush() { // no-op } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\transaction\RabbitTransactionManager.java
1
请完成以下Java代码
public String teams() { return readJson("classpath:org/jeecg/modules/demo/mock/json/workplace_teams.json"); } @GetMapping(value = "/workplace/radar") public String radar() { return readJson("classpath:org/jeecg/modules/demo/mock/json/workplace_radar.json"); } @GetMapping(value = "/task/process") public String taskProcess() { return readJson("classpath:org/jeecg/modules/demo/mock/json/task_process.json"); } //------------------------------------------------------------------------------------------- //author:lvdandan-----date:20190315---for:添加数据日志json---- /** * 数据日志 */ public String sysDataLogJson() { return readJson("classpath:org/jeecg/modules/demo/mock/json/sysdatalog.json"); } //author:lvdandan-----date:20190315---for:添加数据日志json---- //--update-begin--author:wangshuai-----date:20201023---for:返回用户信息json数据---- /** * 用户信息 */ @GetMapping(value = "/getUserInfo") public String getUserInfo(){ return readJson("classpath:org/jeecg/modules/demo/mock/json/userinfo.json"); } //--update-end--author:wangshuai-----date:20201023---for:返回用户信息json数据---- /** * 读取json格式文件
* @param jsonSrc * @return */ private String readJson(String jsonSrc) { String json = ""; try { //File jsonFile = ResourceUtils.getFile(jsonSrc); //json = FileUtils.re.readFileToString(jsonFile); //换个写法,解决springboot读取jar包中文件的问题 InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonSrc.replace("classpath:", "")); json = IOUtils.toString(stream,"UTF-8"); } catch (IOException e) { log.error(e.getMessage(),e); } return json; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\MockController.java
1
请完成以下Java代码
protected void createShellActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createShellActivityBehavior(serviceTask)); } protected void createActivityBehaviorForCustomServiceTaskType(BpmnParse bpmnParse, ServiceTask serviceTask) { logger.warn( "Invalid service task type: '" + serviceTask.getType() + "' " + " for service task " + serviceTask.getId() ); } protected void createClassDelegateServiceTask(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createClassDelegateServiceTask(serviceTask)); } protected void createServiceTaskDelegateExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskDelegateExpressionActivityBehavior(serviceTask)
); } protected void createServiceTaskExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskExpressionActivityBehavior(serviceTask) ); } protected void createWebServiceActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createWebServiceActivityBehavior(serviceTask)); } protected void createDefaultServiceTaskActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createDefaultServiceTaskBehavior(serviceTask)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ServiceTaskParseHandler.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public Integer getThreadNum() { return threadNum; } public void setThreadNum(Integer threadNum) { this.threadNum = threadNum; } public Long getPassQps() { return passQps; } public void setPassQps(Long passQps) { this.passQps = passQps; } public Long getBlockQps() { return blockQps; } public void setBlockQps(Long blockQps) { this.blockQps = blockQps; } public Long getTotalQps() { return totalQps; } public void setTotalQps(Long totalQps) { this.totalQps = totalQps; } public Long getAverageRt() { return averageRt; } public void setAverageRt(Long averageRt) { this.averageRt = averageRt; } public Long getSuccessQps() { return successQps; }
public void setSuccessQps(Long successQps) { this.successQps = successQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public Long getOneMinutePass() { return oneMinutePass; } public void setOneMinutePass(Long oneMinutePass) { this.oneMinutePass = oneMinutePass; } public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; } public Long getOneMinuteException() { return oneMinuteException; } public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException; } public Long getOneMinuteTotal() { return oneMinuteTotal; } public void setOneMinuteTotal(Long oneMinuteTotal) { this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public List<ResourceTreeNode> getChildren() { return children; } public void setChildren(List<ResourceTreeNode> children) { this.children = children; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
1
请在Spring Boot框架中完成以下Java代码
private boolean validateThereWillBeEnoughStockAtGivenDate( @NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor, @NonNull final BigDecimal requiredQtyInStock, @NonNull final Instant givenTime) { final Optional<Candidate> latestStockAtGivenTime = getLatestStockAtGivenTime(supplyRequiredDescriptor, givenTime, DateAndSeqNo.Operator.INCLUSIVE); return latestStockAtGivenTime .map(Candidate::getQuantity) .map(availableStock -> availableStock.compareTo(requiredQtyInStock) >= 0) .orElse(false); } private boolean isStockForSupplyCandidate(@NonNull final Candidate stock, @NonNull final Candidate supplyCandidate) { Check.assume(CandidateId.isRegularNonNull(supplyCandidate.getParentId()), "Supply Candidates have the stock candidate as parent!"); return stock.getId().equals(supplyCandidate.getParentId()); } @NonNull private Candidate getUnspecifiedSupplyCandidate(@NonNull final CandidateId supplyCandidateId) { return candidateRepositoryRetrieval.retrieveLatestMatch(CandidatesQuery.fromId(supplyCandidateId)) .orElseThrow(() -> new AdempiereException("Missing Candidate for Id:" + supplyCandidateId)); }
@NonNull private static PPOrderCandidateAdvisedEvent buildWithPPOrderData(@NonNull final PPOrderCandidateAdvisedEvent event, @NonNull final PPOrderData ppOrderData) { return event.toBuilder() .ppOrderCandidate(event.getPpOrderCandidate().withPpOrderData(ppOrderData)) .build(); } @Value @Builder private static class ProductionTimingResult { @NonNull Instant datePromised; @NonNull BigDecimal qtyRequired; @NonNull Instant missingQtySolvedTime; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ppordercandidate\PPOrderCandidateAdvisedHandler.java
2
请完成以下Java代码
public int getCM_BroadcastServer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_BroadcastServer_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_WebProject getCM_WebProject() throws RuntimeException { return (I_CM_WebProject)MTable.get(getCtx(), I_CM_WebProject.Table_Name) .getPO(getCM_WebProject_ID(), get_TrxName()); } /** Set Web Project. @param CM_WebProject_ID A web project is the main data container for Containers, URLs, Ads, Media etc. */ public void setCM_WebProject_ID (int CM_WebProject_ID) { if (CM_WebProject_ID < 1) set_Value (COLUMNNAME_CM_WebProject_ID, null); else set_Value (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID)); } /** Get Web Project. @return A web project is the main data container for Containers, URLs, Ads, Media etc. */ public int getCM_WebProject_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set IP Address. @param IP_Address Defines the IP address to transfer data to */ public void setIP_Address (String IP_Address) { set_Value (COLUMNNAME_IP_Address, IP_Address); } /** Get IP Address. @return Defines the IP address to transfer data to */
public String getIP_Address () { return (String)get_Value(COLUMNNAME_IP_Address); } /** Set Last Synchronized. @param LastSynchronized Date when last synchronized */ public void setLastSynchronized (Timestamp LastSynchronized) { set_Value (COLUMNNAME_LastSynchronized, LastSynchronized); } /** Get Last Synchronized. @return Date when last synchronized */ public Timestamp getLastSynchronized () { return (Timestamp)get_Value(COLUMNNAME_LastSynchronized); } /** 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_CM_BroadcastServer.java
1
请完成以下Java代码
protected void logActivityTrace(StringWriter writer, List<Map<String, String>> activities) { for (int i = 0; i < activities.size(); i++) { if(i != 0) { writer.write("\t ^\n"); writer.write("\t |\n"); } writer.write("\t"); Map<String, String> activity = activities.get(i); String activityId = activity.get("activityId"); writer.write(activityId); String activityName = activity.get("activityName"); if (activityName != null) { writer.write(", name="); writer.write(activityName); } writer.write("\n"); } } protected List<Map<String, String>> collectActivityTrace() { List<Map<String, String>> activityTrace = new ArrayList<Map<String, String>>(); for (AtomicOperationInvocation atomicOperationInvocation : perfromedInvocations) { String activityId = atomicOperationInvocation.getActivityId(); if(activityId == null) { continue; } Map<String, String> activity = new HashMap<String, String>(); activity.put("activityId", activityId); String activityName = atomicOperationInvocation.getActivityName(); if (activityName != null) { activity.put("activityName", activityName); } if(activityTrace.isEmpty() || !activity.get("activityId").equals(activityTrace.get(0).get("activityId"))) { activityTrace.add(0, activity); } } return activityTrace; } public void add(AtomicOperationInvocation atomicOperationInvocation) { perfromedInvocations.add(atomicOperationInvocation);
} protected void writeInvocation(AtomicOperationInvocation invocation, StringWriter writer) { writer.write("\t"); writer.write(invocation.getActivityId()); writer.write(" ("); writer.write(invocation.getOperation().getCanonicalName()); writer.write(", "); writer.write(invocation.getExecution().toString()); if(invocation.isPerformAsync()) { writer.write(", ASYNC"); } if(invocation.getApplicationContextName() != null) { writer.write(", pa="); writer.write(invocation.getApplicationContextName()); } writer.write(")\n"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\BpmnStackTrace.java
1
请完成以下Java代码
public int[][] getBoardValues() { return boardValues; } public void setBoardValues(int[][] boardValues) { this.boardValues = boardValues; } public int checkStatus() { int boardSize = boardValues.length; int maxIndex = boardSize - 1; int[] diag1 = new int[boardSize]; int[] diag2 = new int[boardSize]; for (int i = 0; i < boardSize; i++) { int[] row = boardValues[i]; int[] col = new int[boardSize]; for (int j = 0; j < boardSize; j++) { col[j] = boardValues[j][i]; } int checkRowForWin = checkForWin(row); if(checkRowForWin!=0) return checkRowForWin; int checkColForWin = checkForWin(col); if(checkColForWin!=0) return checkColForWin; diag1[i] = boardValues[i][i]; diag2[i] = boardValues[maxIndex - i][i]; } int checkDia1gForWin = checkForWin(diag1); if(checkDia1gForWin!=0) return checkDia1gForWin; int checkDiag2ForWin = checkForWin(diag2); if(checkDiag2ForWin!=0) return checkDiag2ForWin; if (getEmptyPositions().size() > 0) return IN_PROGRESS; else return DRAW; } private int checkForWin(int[] row) { boolean isEqual = true; int size = row.length; int previous = row[0]; for (int i = 0; i < size; i++) { if (previous != row[i]) { isEqual = false; break; } previous = row[i];
} if(isEqual) return previous; else return 0; } public void printBoard() { int size = this.boardValues.length; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(boardValues[i][j] + " "); } System.out.println(); } } public List<Position> getEmptyPositions() { int size = this.boardValues.length; List<Position> emptyPositions = new ArrayList<>(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (boardValues[i][j] == 0) emptyPositions.add(new Position(i, j)); } } return emptyPositions; } public void printStatus() { switch (this.checkStatus()) { case P1: System.out.println("Player 1 wins"); break; case P2: System.out.println("Player 2 wins"); break; case DRAW: System.out.println("Game Draw"); break; case IN_PROGRESS: System.out.println("Game In Progress"); break; } } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\tictactoe\Board.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** IsDirectPrint AD_Reference_ID=319 */ public static final int ISDIRECTPRINT_AD_Reference_ID=319; /** Yes = Y */ public static final String ISDIRECTPRINT_Yes = "Y"; /** No = N */ public static final String ISDIRECTPRINT_No = "N"; /** Set Direct print. @param IsDirectPrint Print without dialog */ public void setIsDirectPrint (String IsDirectPrint) { set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint); } /** Get Direct print. @return Print without dialog */ public String getIsDirectPrint () { return (String)get_Value(COLUMNNAME_IsDirectPrint); } /** Set Drucker. @param PrinterName Name of the Printer */ public void setPrinterName (String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Drucker. @return Name of the Printer */ public String getPrinterName () { return (String)get_Value(COLUMNNAME_PrinterName); } /** Get Record ID/ColumnName @return ID/ColumnName pair
*/ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getPrinterName()); } /** PrinterType AD_Reference_ID=540227 */ public static final int PRINTERTYPE_AD_Reference_ID=540227; /** General = G */ public static final String PRINTERTYPE_General = "G"; /** Fax = F */ public static final String PRINTERTYPE_Fax = "F"; /** Label = L */ public static final String PRINTERTYPE_Label = "L"; /** Set Printer Type. @param PrinterType Printer Type */ public void setPrinterType (String PrinterType) { set_Value (COLUMNNAME_PrinterType, PrinterType); } /** Get Printer Type. @return Printer Type */ public String getPrinterType () { return (String)get_Value(COLUMNNAME_PrinterType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Printer.java
1
请在Spring Boot框架中完成以下Java代码
public GetUser createGetUser() { return new GetUser(); } /** * Create an instance of {@link SayHelloResponse } * */ public SayHelloResponse createSayHelloResponse() { return new SayHelloResponse(); } /** * Create an instance of {@link User } * */ public User createUser() { return new User(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetUser }{@code >}} * */ @XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "getUser") public JAXBElement<GetUser> createGetUser(GetUser value) { return new JAXBElement<GetUser>(_GetUser_QNAME, GetUser.class, null, value); } /**
* Create an instance of {@link JAXBElement }{@code <}{@link GetUserResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "getUserResponse") public JAXBElement<GetUserResponse> createGetUserResponse(GetUserResponse value) { return new JAXBElement<GetUserResponse>(_GetUserResponse_QNAME, GetUserResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SayHello }{@code >}} * */ @XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "sayHello") public JAXBElement<SayHello> createSayHello(SayHello value) { return new JAXBElement<SayHello>(_SayHello_QNAME, SayHello.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SayHelloResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "sayHelloResponse") public JAXBElement<SayHelloResponse> createSayHelloResponse(SayHelloResponse value) { return new JAXBElement<SayHelloResponse>(_SayHelloResponse_QNAME, SayHelloResponse.class, null, value); } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\ObjectFactory.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isFullyAllocated() { return creditMemoPayableDoc.getAmountsToAllocate().getPayAmt().isZero(); } /** * Computes projected over under amt taking into account discount. * * @implNote for credit memo as payment, the negated discount needs to be added to the open amount. Negated value is used * as it actually needs to increase the open amount. * * e.g. Having a credit memo with totalGrandAmount = 10 and paymentTerm.Discount=10% translates to 11 total payment amount available. */ @Override public Money calculateProjectedOverUnderAmt(@NonNull final Money payAmountToAllocate) { final Money discountAmt = creditMemoPayableDoc.getAmountsToAllocateInitial().getDiscountAmt().negate(); final Money openAmtWithDiscount = creditMemoPayableDoc.getOpenAmtInitial().add(discountAmt); final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(creditMemoPayableDoc.getTotalAllocatedAmount()); final Money adjustedPayAmountToAllocate = payAmountToAllocate.negate(); return remainingOpenAmtWithDiscount.subtract(adjustedPayAmountToAllocate); } @Override public boolean canPay(@NonNull final PayableDocument payable) { if (payable.getType() != PayableDocumentType.Invoice) { return false; } if (payable.getSoTrx() != creditMemoPayableDoc.getSoTrx()) { return false; } // A credit memo cannot pay another credit memo if (payable.isCreditMemo()) { return false; } return true; } @Override public PaymentDirection getPaymentDirection() { return PaymentDirection.ofSOTrx(creditMemoPayableDoc.getSoTrx());
} @Override public CurrencyId getCurrencyId() { return creditMemoPayableDoc.getCurrencyId(); } @Override public LocalDate getDate() { return creditMemoPayableDoc.getDate(); } @Override public PaymentCurrencyContext getPaymentCurrencyContext() { return PaymentCurrencyContext.builder() .paymentCurrencyId(creditMemoPayableDoc.getCurrencyId()) .currencyConversionTypeId(creditMemoPayableDoc.getCurrencyConversionTypeId()) .build(); } @Override public Money getPaymentDiscountAmt() { return creditMemoPayableDoc.getAmountsToAllocate().getDiscountAmt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\CreditMemoInvoiceAsPaymentDocumentWrapper.java
2
请完成以下Java代码
public static DemandDetail forShipmentLineId( final int inOutLineId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .inOutLineId(inOutLineId) .qty(qty) .build(); } public static DemandDetail forForecastLineId( final int forecastLineId, final int forecastId, @NonNull final BigDecimal qty) { return DemandDetail.builder() .forecastLineId(forecastLineId) .forecastId(forecastId) .qty(qty).build(); } int forecastId; int forecastLineId; int shipmentScheduleId; int orderId; int orderLineId; int subscriptionProgressId; int inOutLineId; BigDecimal qty; /** * Used when a new supply candidate is created, to link it to it's respective demand candidate; * When a demand detail is loaded from DB, this field is always <= 0. */ int demandCandidateId; /** * dev-note: it's about an {@link de.metas.material.event.MaterialEvent} traceId, currently used when posting SupplyRequiredEvents */
@With @Nullable String traceId; @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.SHIPMENT; } public static DemandDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail) { return businessCaseDetail instanceof DemandDetail ? cast(businessCaseDetail) : null; } public static DemandDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (DemandDetail)businessCaseDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DemandDetail.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\nFetch author"); System.out.println("------------"); Author author = bookstoreService.fetchAuthor(4L); System.out.println("\nFetch books of author"); System.out.println("---------------------"); System.out.println("\nBad approach:"); List<Book> booksBad = bookstoreService.fetchBooksOfAuthorBad(author); System.out.println("Books: " + booksBad);
System.out.println("\nGood approach:"); List<Book> booksGood = bookstoreService.fetchBooksOfAuthorGood(author); System.out.println("Books: " + booksGood); System.out.println("\n=============================="); System.out.println("=============================="); System.out.println("\nFetch book"); System.out.println("----------"); Book book = bookstoreService.fetchBook(4L); System.out.println("\nFetch author of book"); System.out.println("---------------------"); System.out.println("\nBad approach:"); Author authorBad = bookstoreService.fetchAuthorOfBookBad(book); System.out.println("Author: " + authorBad); System.out.println("\nGood approach:"); Author authorGood = bookstoreService.fetchAuthorOfBookGood(book); System.out.println("Author: " + authorGood); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootParentChildSeparateQueries\src\main\java\com\bookstore\MainApplication.java
2
请在Spring Boot框架中完成以下Java代码
public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); private final Environment env; public DatabaseConfiguration(Environment env) { this.env = env; } /** * Open the TCP port for the H2 database, so it is available remotely. * * @return the H2 database TCP server * @throws SQLException if the server failed to start */ @Bean(initMethod = "start", destroyMethod = "stop") @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public Object h2TCPServer() throws SQLException { String port = getValidPortForH2(); log.debug("H2 database is available on port {}", port);
return H2ConfigurationHelper.createServer(port); } private String getValidPortForH2() { int port = Integer.parseInt(env.getProperty("server.port")); if (port < 10000) { port = 10000 + port; } else { if (port < 63536) { port = port + 2000; } else { port = port - 2000; } } return String.valueOf(port); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\DatabaseConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public HADDI1 getHADDI1() { return haddi1; } /** * Sets the value of the haddi1 property. * * @param value * allowed object is * {@link HADDI1 } * */ public void setHADDI1(HADDI1 value) { this.haddi1 = value; } /** * Gets the value of the hrefe1 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 hrefe1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHREFE1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link HREFE1 } * * */ public List<HREFE1> getHREFE1() { if (hrefe1 == null) { hrefe1 = new ArrayList<HREFE1>(); } return this.hrefe1; } /** * Gets the value of the hadre1 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 hadre1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHADRE1().add(newItem); * </pre> * *
* <p> * Objects of the following type(s) are allowed in the list * {@link HADRE1 } * * */ public List<HADRE1> getHADRE1() { if (hadre1 == null) { hadre1 = new ArrayList<HADRE1>(); } return this.hadre1; } /** * Gets the value of the htrsd1 property. * * @return * possible object is * {@link HTRSD1 } * */ public HTRSD1 getHTRSD1() { return htrsd1; } /** * Sets the value of the htrsd1 property. * * @param value * allowed object is * {@link HTRSD1 } * */ public void setHTRSD1(HTRSD1 value) { this.htrsd1 = value; } /** * Gets the value of the packin property. * * @return * possible object is * {@link PACKINXlief } * */ public PACKINXlief getPACKIN() { return packin; } /** * Sets the value of the packin property. * * @param value * allowed object is * {@link PACKINXlief } * */ public void setPACKIN(PACKINXlief value) { this.packin = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HEADERXlief.java
2
请完成以下Java代码
private static class DefaultRetrieveSpec extends RetrieveSpecSupport implements RetrieveSpec { private final Mono<ClientGraphQlResponse> responseMono; DefaultRetrieveSpec(Mono<ClientGraphQlResponse> responseMono, String path) { super(path); this.responseMono = responseMono; } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Mono<D> toEntity(Class<D> entityType) { return this.responseMono.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Mono<D> toEntity(ParameterizedTypeReference<D> entityType) { return this.responseMono.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @Override public <D> Mono<List<D>> toEntityList(Class<D> elementType) { return this.responseMono.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } @Override public <D> Mono<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseMono.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } private static class DefaultRetrieveSubscriptionSpec extends RetrieveSpecSupport implements RetrieveSubscriptionSpec { private final Flux<ClientGraphQlResponse> responseFlux; DefaultRetrieveSubscriptionSpec(Flux<ClientGraphQlResponse> responseFlux, String path) { super(path); this.responseFlux = responseFlux;
} @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Flux<D> toEntity(Class<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Flux<D> toEntity(ParameterizedTypeReference<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @Override public <D> Flux<List<D>> toEntityList(Class<D> elementType) { return this.responseFlux.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } @Override public <D> Flux<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseFlux.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultGraphQlClient.java
1
请完成以下Java代码
final class SupplierDeferredSecurityContext implements DeferredSecurityContext { private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class); private final Supplier<SecurityContext> supplier; private final SecurityContextHolderStrategy strategy; private @Nullable SecurityContext securityContext; private boolean missingContext; SupplierDeferredSecurityContext(Supplier<SecurityContext> supplier, SecurityContextHolderStrategy strategy) { this.supplier = supplier; this.strategy = strategy; } @Override public @Nullable SecurityContext get() { init(); return this.securityContext; } @Override public boolean isGenerated() { init(); return this.missingContext; } private void init() {
if (this.securityContext != null) { return; } this.securityContext = this.supplier.get(); this.missingContext = (this.securityContext == null); if (this.missingContext) { this.securityContext = this.strategy.createEmptyContext(); if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Created %s", this.securityContext)); } } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\SupplierDeferredSecurityContext.java
1
请完成以下Java代码
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email;
} public void setEmail(String email) { this.email = email; } @Override public String toString() { return "RegisterParam{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 5-7 课: 综合实战客户管理系统(一)\user-manage\src\main\java\com\neo\param\RegisterParam.java
1
请在Spring Boot框架中完成以下Java代码
public class AccessDatabaseController { // Upload Access database file and query data @PostMapping("/upload") public List<Map<String, Object>> uploadAndQuery(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName) { List<Map<String, Object>> results = new ArrayList<>(); Connection connection = null; try { // Save the uploaded file to the server's temporary directory File tempFile = File.createTempFile("upload-", ".accdb"); file.transferTo(tempFile); // Connect to the Access database String dbUrl = "jdbc:ucanaccess://" + tempFile.getAbsolutePath(); connection = DriverManager.getConnection(dbUrl); // Query the specified table in the database Statement statement = connection.createStatement(); String query = "SELECT * FROM " + tableName; ResultSet resultSet = statement.executeQuery(query); // Store query results in a List<Map<String, Object>> while (resultSet.next()) { Map<String, Object> row = new HashMap<>(); int columnCount = resultSet.getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = resultSet.getMetaData().getColumnName(i); row.put(columnName, resultSet.getObject(i)); } results.add(row); }
// Close the ResultSet and Statement resultSet.close(); statement.close(); // Mark temporary file for deletion upon JVM exit tempFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } finally { // Close the database connection if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } return results; } }
repos\springboot-demo-master\accessDB\src\main\java\com\demo\controller\AccessDatabaseController.java
2
请完成以下Java代码
public Map<ProductId, I_M_Product_AlbertaArticle> getAlbertaArticles(@NonNull final AlbertaDataQuery albertaDataQuery) { final IQueryBuilder<I_M_Product_AlbertaArticle> queryBuilder = queryBL.createQueryBuilder(I_M_Product_AlbertaArticle.class) .addOnlyActiveRecordsFilter(); final Timestamp updatedAfter = TimeUtil.asTimestamp(albertaDataQuery.getUpdatedAfter()); final ICompositeQueryFilter<I_M_Product_AlbertaArticle> productOrTimestampFilter = queryBL.createCompositeQueryFilter(I_M_Product_AlbertaArticle.class) .setJoinOr() .addInArrayFilter(I_M_Product_AlbertaArticle.COLUMNNAME_M_Product_ID, albertaDataQuery.getProductIds()) .addCompareFilter(I_M_Product_AlbertaArticle.COLUMNNAME_Updated, CompareQueryFilter.Operator.GREATER_OR_EQUAL, updatedAfter); queryBuilder.filter(productOrTimestampFilter); return queryBuilder .create() .list() .stream() .collect(ImmutableMap.toImmutableMap( record -> ProductId.ofRepoId(record.getM_Product_ID()), Function.identity())); }
@NonNull public Map<ProductId, List<I_M_Product_AlbertaPackagingUnit>> getPackagingUnits(@NonNull final AlbertaDataQuery albertaDataQuery) { final IQueryBuilder<I_M_Product_AlbertaPackagingUnit> queryBuilder = queryBL.createQueryBuilder(I_M_Product_AlbertaPackagingUnit.class) .addOnlyActiveRecordsFilter(); final Timestamp updatedAfter = TimeUtil.asTimestamp(albertaDataQuery.getUpdatedAfter()); final ICompositeQueryFilter<I_M_Product_AlbertaPackagingUnit> productOrTimestampFilter = queryBL.createCompositeQueryFilter(I_M_Product_AlbertaPackagingUnit.class) .setJoinOr() .addInArrayFilter(I_M_Product_AlbertaPackagingUnit.COLUMNNAME_M_Product_ID, albertaDataQuery.getProductIds()) .addCompareFilter(I_M_Product_AlbertaPackagingUnit.COLUMNNAME_Updated, CompareQueryFilter.Operator.GREATER_OR_EQUAL, updatedAfter); queryBuilder.filter(productOrTimestampFilter); return queryBuilder .create() .list() .stream() .collect(Collectors.groupingBy(record -> ProductId.ofRepoId(record.getM_Product_ID()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\dao\AlbertaProductDAO.java
1
请完成以下Java代码
public void setA_License_No (String A_License_No) { set_Value (COLUMNNAME_A_License_No, A_License_No); } /** Get License No. @return License No */ public String getA_License_No () { return (String)get_Value(COLUMNNAME_A_License_No); } /** Set Policy Renewal Date. @param A_Renewal_Date Policy Renewal Date */ public void setA_Renewal_Date (Timestamp A_Renewal_Date) { set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date); } /** Get Policy Renewal Date. @return Policy Renewal Date */ public Timestamp getA_Renewal_Date () { return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date); } /** Set Account State. @param A_State State of the Credit Card or Account holder
*/ public void setA_State (String A_State) { set_Value (COLUMNNAME_A_State, A_State); } /** Get Account State. @return State of the Credit Card or Account holder */ public String getA_State () { return (String)get_Value(COLUMNNAME_A_State); } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Lic.java
1
请完成以下Java代码
public void updateRecord(final I_C_PurchaseCandidate record, final Dimension from) { record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId())); record.setC_Campaign_ID(from.getCampaignId()); record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId())); record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId())); record.setUserElementString1(from.getUserElementString1()); record.setUserElementString2(from.getUserElementString2()); record.setUserElementString3(from.getUserElementString3()); record.setUserElementString4(from.getUserElementString4()); record.setUserElementString5(from.getUserElementString5()); record.setUserElementString6(from.getUserElementString6()); record.setUserElementString7(from.getUserElementString7()); } @NonNull @Override public Dimension getFromRecord(@NonNull final I_C_PurchaseCandidate record) { return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID())) .campaignId(record.getC_Campaign_ID()) .activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID())) .salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID())) .userElementString1(record.getUserElementString1()) .userElementString2(record.getUserElementString2()) .userElementString3(record.getUserElementString3()) .userElementString4(record.getUserElementString4()) .userElementString5(record.getUserElementString5()) .userElementString6(record.getUserElementString6()) .userElementString7(record.getUserElementString7()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\document\dimension\PurchaseCandidateDimensionFactory.java
1