instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder setLayoutType(final LayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setLayoutType(final String layoutTypeStr) { layoutType = LayoutType.fromNullable(layoutTypeStr); return this; } public Builder setColumnCount(final int columnCount) { this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1); return this; } public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder) { elementLinesBuilders.add(elementLineBuilder); return this;
} public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders) { elementLinesBuilders.addAll(elementLineBuilders); return this; } public boolean hasElementLines() { return !elementLinesBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java
1
请完成以下Java代码
public PageData<EdgeInfo> findEdgeInfosByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData( edgeRepository.findEdgeInfosByTenantId( tenantId, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink, EdgeInfoEntity.edgeInfoColumnMap))); } @Override public Optional<Edge> findByRoutingKey(UUID tenantId, String routingKey) { Edge edge = DaoUtil.getData(edgeRepository.findByRoutingKey(routingKey)); return Optional.ofNullable(edge); } @Override public PageData<Edge> findEdgesByTenantIdAndEntityId(UUID tenantId, UUID entityId, EntityType entityType, PageLink pageLink) { log.debug("Try to find edges by tenantId [{}], entityId [{}], entityType [{}], pageLink [{}]", tenantId, entityId, entityType, pageLink); return DaoUtil.toPageData( edgeRepository.findByTenantIdAndEntityId( tenantId, entityId, entityType.name(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<EdgeId> findEdgeIdsByTenantIdAndEntityId(UUID tenantId, UUID entityId, EntityType entityType, PageLink pageLink) { log.debug("Try to find edge ids by tenantId [{}], entityId [{}], entityType [{}], pageLink [{}]", tenantId, entityId, entityType, pageLink); return DaoUtil.pageToPageData( edgeRepository.findIdsByTenantIdAndEntityId( tenantId, entityId, entityType.name(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))).mapData(EdgeId::fromUUID); } @Override public PageData<Edge> findEdgesByTenantProfileId(UUID tenantProfileId, PageLink pageLink) { log.debug("Try to find edges by tenantProfileId [{}], pageLink [{}]", tenantProfileId, pageLink); return DaoUtil.toPageData( edgeRepository.findByTenantProfileId( tenantProfileId,
DaoUtil.toPageable(pageLink))); } @Override public Long countByTenantId(TenantId tenantId) { return edgeRepository.countByTenantId(tenantId.getId()); } @Override public PageData<Edge> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findEdgesByTenantId(tenantId.getId(), pageLink); } @Override public List<EdgeFields> findNextBatch(UUID id, int batchSize) { return edgeRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.EDGE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaEdgeDao.java
1
请在Spring Boot框架中完成以下Java代码
public static class TimerJobConfiguration implements JobHandlerConfiguration { protected String timerElementKey; protected String timerElementSecondaryKey; protected boolean followUpJobCreated; public String getTimerElementKey() { return timerElementKey; } public void setTimerElementKey(String timerElementKey) { this.timerElementKey = timerElementKey; } public boolean isFollowUpJobCreated() { return followUpJobCreated; } public void setFollowUpJobCreated(boolean followUpJobCreated) { this.followUpJobCreated = followUpJobCreated; } public String getTimerElementSecondaryKey() { return timerElementSecondaryKey; } public void setTimerElementSecondaryKey(String timerElementSecondaryKey) { this.timerElementSecondaryKey = timerElementSecondaryKey;
} @Override public String toCanonicalString() { String canonicalString = timerElementKey; if (timerElementSecondaryKey != null) { canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_TASK_LISTENER_PREFIX + timerElementSecondaryKey; } if (followUpJobCreated) { canonicalString += JOB_HANDLER_CONFIG_PROPERTY_DELIMITER + JOB_HANDLER_CONFIG_PROPERTY_FOLLOW_UP_JOB_CREATED; } return canonicalString; } } public void onDelete(TimerJobConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerEventJobHandler.java
2
请完成以下Java代码
public void setRecipientBankCountryId (final int RecipientBankCountryId) { set_Value (COLUMNNAME_RecipientBankCountryId, RecipientBankCountryId); } @Override public int getRecipientBankCountryId() { return get_ValueAsInt(COLUMNNAME_RecipientBankCountryId); } @Override public void setRecipientCountryId (final int RecipientCountryId) { set_Value (COLUMNNAME_RecipientCountryId, RecipientCountryId); } @Override public int getRecipientCountryId() { return get_ValueAsInt(COLUMNNAME_RecipientCountryId); } /** * RecipientType AD_Reference_ID=541372 * Reference name: RecipientTypeList */ public static final int RECIPIENTTYPE_AD_Reference_ID=541372; /** COMPANY = COMPANY */ public static final String RECIPIENTTYPE_COMPANY = "COMPANY"; /** INDIVIDUAL = INDIVIDUAL */ public static final String RECIPIENTTYPE_INDIVIDUAL = "INDIVIDUAL"; @Override public void setRecipientType (final java.lang.String RecipientType) { set_Value (COLUMNNAME_RecipientType, RecipientType); } @Override public java.lang.String getRecipientType() { return get_ValueAsString(COLUMNNAME_RecipientType); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID()
{ return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setRevolut_Payment_Export_ID (final int Revolut_Payment_Export_ID) { if (Revolut_Payment_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, Revolut_Payment_Export_ID); } @Override public int getRevolut_Payment_Export_ID() { return get_ValueAsInt(COLUMNNAME_Revolut_Payment_Export_ID); } @Override public void setRoutingNo (final @Nullable java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java-gen\de\metas\payment\revolut\model\X_Revolut_Payment_Export.java
1
请在Spring Boot框架中完成以下Java代码
public class SseEmitterController { @Autowired private SseEmitterService sseEmitterService; /** * 创建SSE长链接 * * @param clientId 客户端唯一ID(如果为空,则由后端生成并返回给前端) * @return org.springframework.web.servlet.mvc.method.annotation.SseEmitter * @author re * @date 2021/12/12 **/ @CrossOrigin //如果nginx做了跨域处理,此处可去掉 @GetMapping("/CreateSseConnect") public SseEmitter createSseConnect(@RequestParam(name = "clientId", required = false) String clientId) throws BusinessException { return sseEmitterService.createSseConnect(clientId); }
/** * 关闭SSE连接 * * @param clientId 客户端ID * @author re * @date 2021/12/13 **/ @GetMapping("/CloseSseConnect") public String closeSseConnect(String clientId) { sseEmitterService.closeSseConnect(clientId); return "success"; } @PostMapping( "/chat/stream") public SseEmitter chatStream(@RequestBody ChatRequest request) throws Exception { return sseEmitterService.streamChat(request); } }
repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\controller\SseEmitterController.java
2
请完成以下Java代码
public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Gueltig. @return Element ist gueltig */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Refresh Date. @param LastRefreshDate Last Refresh Date */ public void setLastRefreshDate (Timestamp LastRefreshDate) { set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate); } /** Get Last Refresh Date.
@return Last Refresh Date */ public Timestamp getLastRefreshDate () { return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate); } /** Set Staled Since. @param StaledSinceDate Staled Since */ public void setStaledSinceDate (Timestamp StaledSinceDate) { set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate); } /** Get Staled Since. @return Staled Since */ public Timestamp getStaledSinceDate () { return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java
1
请完成以下Java代码
public class DBRes_sl extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][]{ { "CConnectionDialog", "Server povezava" }, { "Name", "Ime" }, { "AppsHost", "Programski stre\u017enik" }, { "AppsPort", "Vrata programskega stre\u017enika" }, { "TestApps", "Test programskega stre\u017enika" }, { "DBHost", "Stre\u017enik baze podatkov" }, { "DBPort", "Vrata baze podatkov" }, { "DBName", "Ime baze podatkov" }, { "DBUidPwd", "Uporabnik / geslo" }, { "ViaFirewall", "Skozi po\u017earni zid" }, { "FWHost", "Po\u017earni zid" }, { "FWPort", "Vrata po\u017earnega zidu" }, { "TestConnection", "Testiranje baze podatkov" }, { "Type", "Tip baze podatkov" }, { "BequeathConnection", "Bequeath Connection" }, { "Overwrite", "Prepi\u0161i" },
{ "ConnectionProfile", "Povezava" }, { "LAN", "LAN" }, { "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Napaka na povezavi" }, { "ServerNotActive", "Stre\u017enik ni aktiven" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_sl.java
1
请完成以下Java代码
private Map<String, DockerCliInspectResponse> inspect(List<DockerCliComposePsResponse> runningPsResponses) { List<String> ids = runningPsResponses.stream().map(DockerCliComposePsResponse::id).toList(); List<DockerCliInspectResponse> inspectResponses = this.cli.run(new DockerCliCommand.Inspect(ids)); return inspectResponses.stream().collect(Collectors.toMap(DockerCliInspectResponse::id, Function.identity())); } private @Nullable DockerCliInspectResponse inspectContainer(String id, Map<String, DockerCliInspectResponse> inspected) { DockerCliInspectResponse inspect = inspected.get(id); if (inspect != null) { return inspect; } // Docker Compose v2.23.0 returns truncated ids, so we have to do a prefix match for (Entry<String, DockerCliInspectResponse> entry : inspected.entrySet()) { if (entry.getKey().startsWith(id)) {
return entry.getValue(); } } return null; } private List<DockerCliComposePsResponse> runComposePs() { return this.cli.run(new DockerCliCommand.ComposePs()); } private boolean isRunning(DockerCliComposePsResponse psResponse) { return !"exited".equals(psResponse.state()); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DefaultDockerCompose.java
1
请完成以下Java代码
public class SparkRestExample { public static void main(String[] args) { final UserService userService = new UserServiceMapImpl(); post("/users", (request, response) -> { response.type("application/json"); User user = new Gson().fromJson(request.body(), User.class); userService.addUser(user); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS)); }); get("/users", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUsers()))); }); get("/users/:id", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUser(request.params(":id"))))); }); put("/users/:id", (request, response) -> { response.type("application/json"); User toEdit = new Gson().fromJson(request.body(), User.class); User editedUser = userService.editUser(toEdit); if (editedUser != null) {
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(editedUser))); } else { return new Gson().toJson(new StandardResponse(StatusResponse.ERROR, new Gson().toJson("User not found or error in edit"))); } }); delete("/users/:id", (request, response) -> { response.type("application/json"); userService.deleteUser(request.params(":id")); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, "user deleted")); }); options("/users/:id", (request, response) -> { response.type("application/json"); return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, (userService.userExist(request.params(":id"))) ? "User exists" : "User does not exists")); }); } }
repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\SparkRestExample.java
1
请在Spring Boot框架中完成以下Java代码
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher { @Autowired private PmsOperatorService pmsOperatorService; private Cache<String, AtomicInteger> passwordRetryCache; public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) { passwordRetryCache = cacheManager.getCache("passwordRetryCache"); } @Override /** * 做认证匹配 */ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { String username = (String) token.getPrincipal(); // retry count + 1 AtomicInteger retryCount = passwordRetryCache.get(username); if (retryCount == null) { retryCount = new AtomicInteger(0); passwordRetryCache.put(username, retryCount);
} if (retryCount.incrementAndGet() > 5) { // if retry count > 5 throw throw new ExcessiveAttemptsException(); } boolean matches = super.doCredentialsMatch(token, info); if (matches) { // clear retry count passwordRetryCache.remove(username); // 根据登录名查询操作员 PmsOperator operator = pmsOperatorService.findOperatorByLoginName(username); Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.setAttribute("PmsOperator", operator); } return matches; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\credentials\RetryLimitHashedCredentialsMatcher.java
2
请完成以下Java代码
public Collection<AttributeKvEntry> getServerSideAttributes() { return serverPrivateAttributesMap.values(); } public Collection<AttributeKvEntry> getServerSidePublicAttributes() { return serverPublicAttributesMap.values(); } public Optional<AttributeKvEntry> getClientSideAttribute(String attribute) { return Optional.ofNullable(clientSideAttributesMap.get(attribute)); } public Optional<AttributeKvEntry> getServerPrivateAttribute(String attribute) { return Optional.ofNullable(serverPrivateAttributesMap.get(attribute)); } public Optional<AttributeKvEntry> getServerPublicAttribute(String attribute) { return Optional.ofNullable(serverPublicAttributesMap.get(attribute)); } public void remove(AttributeKey key) { Map<String, AttributeKvEntry> map = getMapByScope(key.getScope()); if (map != null) { map.remove(key.getAttributeKey()); } } public void update(String scope, List<AttributeKvEntry> values) { Map<String, AttributeKvEntry> map = getMapByScope(scope); values.forEach(v -> map.put(v.getKey(), v)); } private Map<String, AttributeKvEntry> getMapByScope(String scope) { Map<String, AttributeKvEntry> map = null; if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) { map = clientSideAttributesMap; } else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) {
map = serverPublicAttributesMap; } else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) { map = serverPrivateAttributesMap; } return map; } @Override public String toString() { return "DeviceAttributes{" + "clientSideAttributesMap=" + clientSideAttributesMap + ", serverPrivateAttributesMap=" + serverPrivateAttributesMap + ", serverPublicAttributesMap=" + serverPublicAttributesMap + '}'; } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java
1
请完成以下Java代码
class M_HU_Storage_SnapshotHandler extends AbstractSnapshotHandler<I_M_HU_Storage, I_M_HU_Storage_Snapshot, I_M_HU> { M_HU_Storage_SnapshotHandler(final AbstractSnapshotHandler<I_M_HU, ?, ?> parentHandler) { super(parentHandler); } @Override protected void createSnapshotsByParentIds(final Set<Integer> huIds) { Check.assumeNotEmpty(huIds, "huIds not empty"); query(I_M_HU_Storage.class) .addInArrayOrAllFilter(I_M_HU_Storage.COLUMN_M_HU_ID, huIds) .create() .insertDirectlyInto(I_M_HU_Storage_Snapshot.class) .mapCommonColumns() .mapColumnToConstant(I_M_HU_Storage_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId()) .execute(); } @Override protected Map<Integer, I_M_HU_Storage_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU model) { return query(I_M_HU_Storage_Snapshot.class) .addEqualsFilter(I_M_HU_Storage_Snapshot.COLUMN_M_HU_ID, model.getM_HU_ID()) .addEqualsFilter(I_M_HU_Storage_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId()) .create() .map(I_M_HU_Storage_Snapshot.class, snapshot2ModelIdFunction); } @Override protected final Map<Integer, I_M_HU_Storage> retrieveModelsByParent(final I_M_HU hu) { return query(I_M_HU_Storage.class) .addEqualsFilter(I_M_HU_Storage.COLUMN_M_HU_ID, hu.getM_HU_ID()) .create()
.mapById(I_M_HU_Storage.class); } @Override protected I_M_HU_Storage_Snapshot retrieveModelSnapshot(final I_M_HU_Storage model) { throw new UnsupportedOperationException(); } @Override protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Storage model) { model.setQty(BigDecimal.ZERO); } @Override protected int getModelId(final I_M_HU_Storage_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Storage_ID(); } @Override protected I_M_HU_Storage getModel(final I_M_HU_Storage_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_Storage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Storage_SnapshotHandler.java
1
请在Spring Boot框架中完成以下Java代码
private OAuth2AuthorizationCodeGrantFilter createAuthorizationCodeGrantFilter(B builder) { AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = new OAuth2AuthorizationCodeGrantFilter( getClientRegistrationRepository(builder), getAuthorizedClientRepository(builder), authenticationManager); if (this.authorizationRequestRepository != null) { authorizationCodeGrantFilter.setAuthorizationRequestRepository(this.authorizationRequestRepository); } authorizationCodeGrantFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); RequestCache requestCache = builder.getSharedObject(RequestCache.class); if (requestCache != null) { authorizationCodeGrantFilter.setRequestCache(requestCache); } return authorizationCodeGrantFilter; } private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> getAccessTokenResponseClient() { if (this.accessTokenResponseClient != null) { return this.accessTokenResponseClient; } ResolvableType resolvableType = ResolvableType.forClassWithGenerics(OAuth2AccessTokenResponseClient.class, OAuth2AuthorizationCodeGrantRequest.class); OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> bean = getBeanOrNull(resolvableType); return (bean != null) ? bean : new RestClientAuthorizationCodeTokenResponseClient(); }
private ClientRegistrationRepository getClientRegistrationRepository(B builder) { return (OAuth2ClientConfigurer.this.clientRegistrationRepository != null) ? OAuth2ClientConfigurer.this.clientRegistrationRepository : OAuth2ClientConfigurerUtils.getClientRegistrationRepository(builder); } private OAuth2AuthorizedClientRepository getAuthorizedClientRepository(B builder) { return (OAuth2ClientConfigurer.this.authorizedClientRepository != null) ? OAuth2ClientConfigurer.this.authorizedClientRepository : OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(builder); } @SuppressWarnings("unchecked") private <T> T getBeanOrNull(ResolvableType type) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return (T) context.getBeanProvider(type).getIfUnique(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OAuth2ClientConfigurer.java
2
请完成以下Java代码
public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } /** * Sets the {@link AuthenticationSuccessHandler} used for handling an * {@link OidcLogoutAuthenticationToken} and performing the logout. * @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used * for handling an {@link OidcLogoutAuthenticationToken} */ public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null"); this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets the {@link AuthenticationFailureHandler} used for handling an * {@link OAuth2AuthenticationException} and returning the {@link OAuth2Error Error
* Response}. * @param authenticationFailureHandler the {@link AuthenticationFailureHandler} used * for handling an {@link OAuth2AuthenticationException} */ public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler; } private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException { OAuth2Error error = ((OAuth2AuthenticationException) exception).getError(); response.sendError(HttpStatus.BAD_REQUEST.value(), error.toString()); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcLogoutEndpointFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } @ApiModelProperty(example = "fozzie") public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime;
} @ApiModelProperty(example = "86400056") public Long getDurationInMillis() { return durationInMillis; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public class DataCouchbaseProperties { /** * Automatically create views and indexes. Use the meta-data provided by * "@ViewIndexed", "@N1qlPrimaryIndexed" and "@N1qlSecondaryIndexed". */ private boolean autoIndex; /** * Name of the bucket to connect to. */ private @Nullable String bucketName; /** * Name of the scope used for all collection access. */ private @Nullable String scopeName; /** * Fully qualified name of the FieldNamingStrategy to use. */ private @Nullable Class<?> fieldNamingStrategy; /** * Name of the field that stores the type information for complex types when using * "MappingCouchbaseConverter". */ private String typeKey = "_class"; public boolean isAutoIndex() { return this.autoIndex; } public void setAutoIndex(boolean autoIndex) { this.autoIndex = autoIndex; }
public @Nullable String getBucketName() { return this.bucketName; } public void setBucketName(@Nullable String bucketName) { this.bucketName = bucketName; } public @Nullable String getScopeName() { return this.scopeName; } public void setScopeName(@Nullable String scopeName) { this.scopeName = scopeName; } public @Nullable Class<?> getFieldNamingStrategy() { return this.fieldNamingStrategy; } public void setFieldNamingStrategy(@Nullable Class<?> fieldNamingStrategy) { this.fieldNamingStrategy = fieldNamingStrategy; } public String getTypeKey() { return this.typeKey; } public void setTypeKey(String typeKey) { this.typeKey = typeKey; } }
repos\spring-boot-4.0.1\module\spring-boot-data-couchbase\src\main\java\org\springframework\boot\data\couchbase\autoconfigure\DataCouchbaseProperties.java
2
请完成以下Java代码
protected boolean afterSave(boolean newRecord, boolean success) { if (!success) return success; BundleUtil.updateCCM_Bundle_Status(getR_Group_ID(), get_TrxName()); return true; } @Override protected boolean beforeDelete() { if (getR_Request_ID() > 0) { throw new AdempiereException("@R_Request_ID@"); } expireLock(); if (isLocked()) { throw new AdempiereException("de.metas.callcenter.CannotDeleteLocked"); } return true; } @Override protected boolean afterDelete(boolean success) { if (!success) return success; BundleUtil.updateCCM_Bundle_Status(getR_Group_ID(), get_TrxName()); return true; } public void lockContact() { int AD_User_ID = Env.getAD_User_ID(getCtx()); Timestamp ts = new Timestamp(System.currentTimeMillis()); setLocked(true); setLockedBy(AD_User_ID); setLockedDate(ts); } public void unlockContact() { setLocked(false); set_Value(COLUMNNAME_LockedBy, null); setLockedDate(null); } public boolean isExpired()
{ if (!isLocked()) return true; Timestamp dateExpire = TimeUtil.addMinutes(getLockedDate(), LOCK_EXPIRE_MIN); Timestamp now = new Timestamp(System.currentTimeMillis()); return dateExpire.before(now); } public void expireLock() { if (isLocked() && isExpired()) unlockContact(); } @Override public String toString() { String bundleName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_R_Group.COLUMNNAME_Name+" FROM "+I_R_Group.Table_Name +" WHERE "+I_R_Group.COLUMNNAME_R_Group_ID+"=?", getR_Group_ID()); String bpName = DB.getSQLValueString(get_TrxName(), "SELECT "+I_C_BPartner.COLUMNNAME_Value+"||'_'||"+I_C_BPartner.COLUMNNAME_Name +" FROM "+I_C_BPartner.Table_Name +" WHERE "+I_C_BPartner.COLUMNNAME_C_BPartner_ID+"=?", getC_BPartner_ID()); return bundleName+"/"+bpName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\model\MRGroupProspect.java
1
请完成以下Java代码
public BigDecimal getPriceEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param QtyEntered The Quantity Entered is based on the selected UoM */ public void setQtyEntered (BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Quantity. @return The Quantity Entered is based on the selected UoM */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_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_C_InvoiceBatchLine.java
1
请完成以下Java代码
public boolean isDecimalPoint () { Object oo = get_Value(COLUMNNAME_IsDecimalPoint); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set System Language. @param IsSystemLanguage The screens, etc. are maintained in this Language */ public void setIsSystemLanguage (boolean IsSystemLanguage) { set_Value (COLUMNNAME_IsSystemLanguage, Boolean.valueOf(IsSystemLanguage)); } /** Get System Language. @return The screens, etc. are maintained in this Language */ public boolean isSystemLanguage () { Object oo = get_Value(COLUMNNAME_IsSystemLanguage); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Language Code. @param LanguageISO Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public void setLanguageISO (String LanguageISO) { set_Value (COLUMNNAME_LanguageISO, LanguageISO); } /** Get ISO Language Code. @return Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public String getLanguageISO () { return (String)get_Value(COLUMNNAME_LanguageISO); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Time Pattern. @param TimePattern Java Time Pattern */ public void setTimePattern (String TimePattern) { set_Value (COLUMNNAME_TimePattern, TimePattern); } /** Get Time Pattern. @return Java Time Pattern */ public String getTimePattern () { return (String)get_Value(COLUMNNAME_TimePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
1
请在Spring Boot框架中完成以下Java代码
public void configure() { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(StaticEndpointBuilders.direct(MF_ERROR_ROUTE_ID)); from(FROM_MF_ROUTE) .routeId(FROM_MF_ROUTE_ID) .to("direct:dispatch"); from("direct:dispatch") .routeId(DISPATCH_ROUTE_ID) .streamCache("true") .unmarshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonExternalSystemRequest.class)) .process(this::processExternalSystemRequest) .log("routing request to route ${header." + HEADER_TARGET_ROUTE + "}") .process(this::logRequestRouted) .toD("direct:${header." + HEADER_TARGET_ROUTE + "}", false) .process(this::logInvocationDone); } private void logRequestRouted(@NonNull final Exchange exchange) { final String targetRoute = exchange.getIn().getHeader(HEADER_TARGET_ROUTE, String.class); processLogger.logMessage("Routing request to: " + targetRoute, exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class)); } private void logInvocationDone(@NonNull final Exchange exchange) { final String targetRoute = exchange.getIn().getHeader(HEADER_TARGET_ROUTE, String.class); processLogger.logMessage("Invocation done: " + targetRoute, exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class)); }
private void processExternalSystemRequest(@NonNull final Exchange exchange) { final var request = exchange.getIn().getBody(JsonExternalSystemRequest.class); exchange.getIn().setHeader(HEADER_TARGET_ROUTE, request.getExternalSystemName().getName() + "-" + request.getCommand()); exchange.getIn().setHeader(HEADER_TRACE_ID, request.getTraceId()); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); } if (EmptyUtil.isNotBlank(request.getWriteAuditEndpoint())) { exchange.getIn().setHeader(HEADER_AUDIT_TRAIL, request.getWriteAuditEndpoint()); } if (request.getParameters() != null && Check.isNotBlank(request.getParameters().get(PARAM_CHILD_CONFIG_VALUE))) { exchange.getIn().setHeader(HEADER_EXTERNAL_SYSTEM_VALUE, request.getParameters().get(PARAM_CHILD_CONFIG_VALUE)); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\from_mf\CallDispatcherRouteBuilder.java
2
请完成以下Java代码
public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public Integer getLowStock() { return lowStock; } public void setLowStock(Integer lowStock) { this.lowStock = lowStock; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getSale() { return sale; } public void setSale(Integer sale) { this.sale = sale; } public BigDecimal getPromotionPrice() { return promotionPrice; } public void setPromotionPrice(BigDecimal promotionPrice) { this.promotionPrice = promotionPrice; } public Integer getLockStock() { return lockStock; } public void setLockStock(Integer lockStock) {
this.lockStock = lockStock; } public String getSpData() { return spData; } public void setSpData(String spData) { this.spData = spData; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", skuCode=").append(skuCode); sb.append(", price=").append(price); sb.append(", stock=").append(stock); sb.append(", lowStock=").append(lowStock); sb.append(", pic=").append(pic); sb.append(", sale=").append(sale); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", lockStock=").append(lockStock); sb.append(", spData=").append(spData); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsSkuStock.java
1
请完成以下Java代码
public static FacetsCollection ofCollection(final Collection<Facet> collection) { return !collection.isEmpty() ? new FacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY; } @Override @NonNull public Iterator<Facet> iterator() {return set.iterator();} public boolean isEmpty() {return set.isEmpty();} public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds) { if (isEmpty()) { return WorkflowLaunchersFacetGroupList.EMPTY; }
final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>(); for (final ManufacturingJobFacets.Facet manufacturingFacet : set) { final WorkflowLaunchersFacet facet = manufacturingFacet.toWorkflowLaunchersFacet(activeFacetIds); groupBuilders.computeIfAbsent(facet.getGroupId(), k -> manufacturingFacet.newWorkflowLaunchersFacetGroupBuilder()) .facet(facet); } final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values() .stream() .map(WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder::build) .collect(ImmutableList.toImmutableList()); return WorkflowLaunchersFacetGroupList.ofList(groups); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobFacets.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public void setType(String type) { this.type = type; } public void setRequired(boolean required) { this.required = required; } public void setDisplay(Boolean display) { this.display = display; } public void setDisplayName(String displayName) { this.displayName = displayName; }
public boolean isAnalytics() { return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } public void setEphemeral(boolean ephemeral) { this.ephemeral = ephemeral; } public boolean isEphemeral() { return ephemeral; } }
repos\Activiti-develop\activiti-core-common\activiti-connector-model\src\main\java\org\activiti\core\common\model\connector\VariableDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public class Person { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; private String name; private String email; public Person() { } public Person(String name, String email) { this.name = name; this.email = email; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\sfvsemf\entity\Person.java
2
请完成以下Java代码
public GatewayFilter apply(Config config) { KeyResolver resolver = getOrDefault(config.keyResolver, defaultKeyResolver); RateLimiter<Object> limiter = getOrDefault(config.rateLimiter, defaultRateLimiter); boolean denyEmpty = getOrDefault(config.denyEmptyKey, this.denyEmptyKey); HttpStatusHolder emptyKeyStatus = HttpStatusHolder .parse(getOrDefault(config.emptyKeyStatus, this.emptyKeyStatusCode)); return (exchange, chain) -> resolver.resolve(exchange).defaultIfEmpty(EMPTY_KEY).flatMap(key -> { if (EMPTY_KEY.equals(key)) { if (denyEmpty) { setResponseStatus(exchange, emptyKeyStatus); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } String routeId = config.getRouteId(); if (routeId == null) { Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); routeId = Objects.requireNonNull(route, "Route not found").getId(); } return limiter.isAllowed(routeId, key).flatMap(response -> { for (Map.Entry<String, String> header : response.getHeaders().entrySet()) { exchange.getResponse().getHeaders().add(header.getKey(), header.getValue()); } if (response.isAllowed()) { return chain.filter(exchange); } setResponseStatus(exchange, config.getStatusCode()); return exchange.getResponse().setComplete(); }); }); } private <T> T getOrDefault(@Nullable T configValue, T defaultValue) { return (configValue != null) ? configValue : defaultValue; } public static class Config implements HasRouteId { private @Nullable KeyResolver keyResolver; private @Nullable RateLimiter rateLimiter; private HttpStatus statusCode = HttpStatus.TOO_MANY_REQUESTS; private @Nullable Boolean denyEmptyKey; private @Nullable String emptyKeyStatus; private @Nullable String routeId; 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代码
public void setModelFromRecordId(int modelFromRecordId) { this.modelFromRecordId = modelFromRecordId; } @Override public int getModelToRecordId() { return modelToRecordId; } @Override public void setModelToRecordId(int modelToRecordId) { this.modelToRecordId = modelToRecordId; } @Override public ISqlQueryFilter getFilter() { return filter; } @Override public void setFilter(ISqlQueryFilter filter) { this.filter = filter; } @Override public ISqlQueryFilter getModelFilter() { return modelFilter; } @Override public void setModelFilter(ISqlQueryFilter modelFilter) { this.modelFilter = modelFilter; } @Override public Access getRequiredAccess() { return requiredAccess; } @Override public void setRequiredAccess(final Access requiredAccess)
{ this.requiredAccess = requiredAccess; } @Override public Integer getCopies() { return copies; } @Override public void setCopies(int copies) { this.copies = copies; } @Override public String getAggregationKey() { return aggregationKey; } @Override public void setAggregationKey(final String aggregationKey) { this.aggregationKey=aggregationKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_MediaTray.java
1
请完成以下Java代码
public void notifyPostingError( @NonNull final UserId recipientUserId, @NonNull final TableRecordReference documentRef, @NonNull final String message) { userNotifications.sendAfterCommit(toUserNotificationRequest(recipientUserId, documentRef, message)); } private static UserNotificationRequest toUserNotificationRequestOrNull( @NonNull final DocumentPostRequest postRequest, @NonNull final String message) { final UserId recipientUserId = postRequest.getOnErrorNotifyUserId(); if (recipientUserId == null) {return null;} return UserNotificationRequest.builder() .topic(NOTIFICATIONS_TOPIC) .recipientUserId(recipientUserId) .contentPlain(message) .targetAction(UserNotificationRequest.TargetRecordAction.of(postRequest.getRecord()))
.build(); } private static UserNotificationRequest toUserNotificationRequest( @NonNull final UserId recipientUserId, @NonNull final TableRecordReference documentRef, @NonNull final String message) { return UserNotificationRequest.builder() .topic(NOTIFICATIONS_TOPIC) .recipientUserId(recipientUserId) .contentPlain(message) .targetAction(UserNotificationRequest.TargetRecordAction.of(documentRef)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingUserNotificationService.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(frequency, amount, timePeriod, annotation); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractVisitInterval {\n"); sb.append(" frequency: ").append(toIndentedString(frequency)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n"); sb.append("}");
return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractVisitInterval.java
2
请完成以下Java代码
class PulsarDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<PulsarConnectionDetails> { private static final int BROKER_PORT = 6650; private static final int ADMIN_PORT = 8080; PulsarDockerComposeConnectionDetailsFactory() { super("apachepulsar/pulsar"); } @Override protected PulsarConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new PulsarDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link PulsarConnectionDetails} backed by a {@code pulsar} {@link RunningService}. */ static class PulsarDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements PulsarConnectionDetails { private final String brokerUrl;
private final String adminUrl; PulsarDockerComposeConnectionDetails(RunningService service) { super(service); ConnectionPorts ports = service.ports(); this.brokerUrl = "pulsar://%s:%s".formatted(service.host(), ports.get(BROKER_PORT)); this.adminUrl = "http://%s:%s".formatted(service.host(), ports.get(ADMIN_PORT)); } @Override public String getBrokerUrl() { return this.brokerUrl; } @Override public String getAdminUrl() { return this.adminUrl; } } }
repos\spring-boot-4.0.1\module\spring-boot-pulsar\src\main\java\org\springframework\boot\pulsar\docker\compose\PulsarDockerComposeConnectionDetailsFactory.java
1
请在Spring Boot框架中完成以下Java代码
protected CaseDefinitionQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createCaseDefinitionQuery(); } @Override protected void applyFilters(CaseDefinitionQuery query) { if (caseDefinitionId != null) { query.caseDefinitionId(caseDefinitionId); } if (caseDefinitionIdIn != null && !caseDefinitionIdIn.isEmpty()) { query.caseDefinitionIdIn(caseDefinitionIdIn.toArray(new String[caseDefinitionIdIn.size()])); } if (category != null) { query.caseDefinitionCategory(category); } if (categoryLike != null) { query.caseDefinitionCategoryLike(categoryLike); } if (name != null) { query.caseDefinitionName(name); } if (nameLike != null) { query.caseDefinitionNameLike(nameLike); } if (deploymentId != null) { query.deploymentId(deploymentId); } if (key != null) { query.caseDefinitionKey(key); } if (keyLike != null) { query.caseDefinitionKeyLike(keyLike); } if (resourceName != null) { query.caseDefinitionResourceName(resourceName); } if (resourceNameLike != null) { query.caseDefinitionResourceNameLike(resourceNameLike); } if (version != null) { query.caseDefinitionVersion(version); } if (TRUE.equals(latestVersion)) { query.latestVersion(); }
if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDefinitionsWithoutTenantId)) { query.includeCaseDefinitionsWithoutTenantId(); } } @Override protected void applySortBy(CaseDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { query.orderByCaseDefinitionCategory(); } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { query.orderByCaseDefinitionKey(); } else if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByCaseDefinitionId(); } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { query.orderByCaseDefinitionVersion(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByCaseDefinitionName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\CaseDefinitionQueryDto.java
2
请完成以下Java代码
public HistoricJobLogResource getHistoricJobLog(String historicJobLogId) { return new HistoricJobLogResourceImpl(historicJobLogId, processEngine); } @Override public List<HistoricJobLogDto> getHistoricJobLogs(UriInfo uriInfo, Integer firstResult, Integer maxResults) { HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricJobLogs(queryDto, firstResult, maxResults); } @Override public List<HistoricJobLogDto> queryHistoricJobLogs(HistoricJobLogQueryDto queryDto, Integer firstResult, Integer maxResults) { queryDto.setObjectMapper(objectMapper); HistoricJobLogQuery query = queryDto.toQuery(processEngine); List<HistoricJobLog> matchingHistoricJobLogs = QueryUtil.list(query, firstResult, maxResults); List<HistoricJobLogDto> results = new ArrayList<HistoricJobLogDto>(); for (HistoricJobLog historicJobLog : matchingHistoricJobLogs) { HistoricJobLogDto result = HistoricJobLogDto.fromHistoricJobLog(historicJobLog); results.add(result); } return results; } @Override public CountResultDto getHistoricJobLogsCount(UriInfo uriInfo) { HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricJobLogsCount(queryDto); } @Override public CountResultDto queryHistoricJobLogsCount(HistoricJobLogQueryDto queryDto) { queryDto.setObjectMapper(objectMapper); HistoricJobLogQuery query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricJobLogRestServiceImpl.java
1
请完成以下Java代码
public class XxlJobLog { private long id; // job info private int jobGroup; private int jobId; // execute info private String executorAddress; private String executorHandler; private String executorParam; private String executorShardingParam; private int executorFailRetryCount; // trigger info private Date triggerTime; private int triggerCode; private String triggerMsg; // handle info private Date handleTime; private int handleCode; private String handleMsg; // alarm info private int alarmStatus; public long getId() { return id; } public void setId(long id) { this.id = id; } public int getJobGroup() { return jobGroup; } public void setJobGroup(int jobGroup) { this.jobGroup = jobGroup; } public int getJobId() { return jobId; } public void setJobId(int jobId) { this.jobId = jobId; } public String getExecutorAddress() { return executorAddress; } public void setExecutorAddress(String executorAddress) { this.executorAddress = executorAddress; } public String getExecutorHandler() { return executorHandler; } public void setExecutorHandler(String executorHandler) { this.executorHandler = executorHandler; } public String getExecutorParam() { return executorParam; } public void setExecutorParam(String executorParam) { this.executorParam = executorParam; } public String getExecutorShardingParam() { return executorShardingParam; } public void setExecutorShardingParam(String executorShardingParam) { this.executorShardingParam = executorShardingParam;
} public int getExecutorFailRetryCount() { return executorFailRetryCount; } public void setExecutorFailRetryCount(int executorFailRetryCount) { this.executorFailRetryCount = executorFailRetryCount; } public Date getTriggerTime() { return triggerTime; } public void setTriggerTime(Date triggerTime) { this.triggerTime = triggerTime; } public int getTriggerCode() { return triggerCode; } public void setTriggerCode(int triggerCode) { this.triggerCode = triggerCode; } public String getTriggerMsg() { return triggerMsg; } public void setTriggerMsg(String triggerMsg) { this.triggerMsg = triggerMsg; } public Date getHandleTime() { return handleTime; } public void setHandleTime(Date handleTime) { this.handleTime = handleTime; } public int getHandleCode() { return handleCode; } public void setHandleCode(int handleCode) { this.handleCode = handleCode; } public String getHandleMsg() { return handleMsg; } public void setHandleMsg(String handleMsg) { this.handleMsg = handleMsg; } public int getAlarmStatus() { return alarmStatus; } public void setAlarmStatus(int alarmStatus) { this.alarmStatus = alarmStatus; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java
1
请完成以下Java代码
public boolean containsAnyOfRowIds(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds) { return viewSelectionFactory.containsAnyOfRowIds(selection, rowIds); } @Override public void deleteSelection(final ViewRowIdsOrderedSelection selection) { viewSelectionFactory.deleteSelection(selection.getSelectionId()); } @Override public SqlViewRowsWhereClause buildSqlWhereClause(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds) { return SqlViewSelectionQueryBuilder.prepareSqlWhereClause() .sqlTableAlias(I_M_HU.Table_Name) .keyColumnNamesMap(SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_HU.COLUMNNAME_M_HU_ID)) .selectionId(selection.getSelectionId()) .rowIds(rowIds) .rowIdsConverter(getRowIdsConverter()) .build(); } @Override public void warmUp(@NonNull final Set<HuId> huIds) { InterfaceWrapperHelper.loadByRepoIdAwares(huIds, I_M_HU.class); // caches the given HUs with one SQL query huReservationService.warmup(huIds);
} @Nullable private JSONLookupValue getHUClearanceStatusLookupValue(@NonNull final I_M_HU hu) { final ClearanceStatus huClearanceStatus = ClearanceStatus.ofNullableCode(hu.getClearanceStatus()); if (huClearanceStatus == null) { return null; } final ITranslatableString huClearanceStatusCaption = handlingUnitsBL.getClearanceStatusCaption(huClearanceStatus); return JSONLookupValue.of(huClearanceStatus.getCode(), huClearanceStatusCaption.translate(Env.getAD_Language())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\SqlHUEditorViewRepository.java
1
请在Spring Boot框架中完成以下Java代码
public BatchDto restartProcessInstanceAsync(RestartProcessInstanceDto restartProcessInstanceDto) { Batch batch = null; try { batch = createRestartProcessInstanceBuilder(restartProcessInstanceDto).executeAsync(); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } return BatchDto.fromBatch(batch); } private RestartProcessInstanceBuilder createRestartProcessInstanceBuilder(RestartProcessInstanceDto restartProcessInstanceDto) { RuntimeService runtimeService = engine.getRuntimeService(); RestartProcessInstanceBuilder builder = runtimeService .restartProcessInstances(processDefinitionId); if (restartProcessInstanceDto.getProcessInstanceIds() != null) { builder.processInstanceIds(restartProcessInstanceDto.getProcessInstanceIds()); } if (restartProcessInstanceDto.getHistoricProcessInstanceQuery() != null) { builder.historicProcessInstanceQuery(restartProcessInstanceDto.getHistoricProcessInstanceQuery().toQuery(engine)); } if (restartProcessInstanceDto.isInitialVariables()) { builder.initialSetOfVariables(); } if (restartProcessInstanceDto.isWithoutBusinessKey()) { builder.withoutBusinessKey(); } if (restartProcessInstanceDto.isSkipCustomListeners()) { builder.skipCustomListeners(); } if (restartProcessInstanceDto.isSkipIoMappings()) { builder.skipIoMappings(); } restartProcessInstanceDto.applyTo(builder, engine, objectMapper);
return builder; } public Response getDeployedStartForm() { try { InputStream deployedStartForm = engine.getFormService().getDeployedStartForm(processDefinitionId); return Response.ok(deployedStartForm, getStartFormMediaType(processDefinitionId)).build(); } catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } catch (AuthorizationException e) { throw new InvalidRequestException(Status.FORBIDDEN, e.getMessage()); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } protected String getStartFormMediaType(String processDefinitionId) { String formKey = engine.getFormService().getStartFormKey(processDefinitionId); CamundaFormRef camundaFormRef = engine.getFormService().getStartFormData(processDefinitionId).getCamundaFormRef(); if(formKey != null) { return ContentTypeUtil.getFormContentType(formKey); } else if(camundaFormRef != null) { return ContentTypeUtil.getFormContentType(camundaFormRef); } return MediaType.APPLICATION_XHTML_XML; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\ProcessDefinitionResourceImpl.java
2
请完成以下Java代码
public static String replaceRepeatCycleAndDate(String repeatExpression) { if (repeatExpression.split("/").length == 2) { return repeatExpression.replace("/", "/" + SIMPLE_DATE_FORMAT.format(ClockUtil.getCurrentTime()) + "/"); } return repeatExpression; // expression include start date } protected RepeatingFailedJobListener createRepeatingFailedJobListener(CommandExecutor commandExecutor) { return new RepeatingFailedJobListener(commandExecutor, getId()); } public void createNewTimerJob(Date dueDate) { // create new timer job TimerEntity newTimer = new TimerEntity(this); newTimer.setDuedate(dueDate); Context .getCommandContext() .getJobManager() .schedule(newTimer); } public Date calculateNewDueDate() { BusinessCalendar businessCalendar = Context .getProcessEngineConfiguration() .getBusinessCalendarManager() .getBusinessCalendar(CycleBusinessCalendar.NAME); return ((CycleBusinessCalendar) businessCalendar).resolveDuedate(repeat, null, repeatOffset); } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public long getRepeatOffset() { return repeatOffset; } public void setRepeatOffset(long repeatOffset) {
this.repeatOffset = repeatOffset; } @Override public String getType() { return TYPE; } @Override public Object getPersistentState() { Map<String, Object> persistentState = (HashMap) super.getPersistentState(); persistentState.put("repeat", repeat); return persistentState; } @Override public String toString() { return this.getClass().getSimpleName() + "[repeat=" + repeat + ", id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", repeatOffset=" + repeatOffset + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TimerEntity.java
1
请完成以下Java代码
private Instant calculateTo() { Instant to = SystemTime.asInstant(); if (defaultTimeRangeEndOffset != null) { to = to.plus(defaultTimeRangeEndOffset); } return to; } private Instant calculateFrom(@NonNull final Instant to) { if (defaultTimeRange == null || defaultTimeRange.isZero()) { return Instant.ofEpochMilli(0);
} else { return to.minus(defaultTimeRange.abs()); } } public KPITimeRangeDefaults compose(final KPITimeRangeDefaults fallback) { return builder() .defaultTimeRange(CoalesceUtil.coalesce(getDefaultTimeRange(), fallback.getDefaultTimeRange())) .defaultTimeRangeEndOffset(CoalesceUtil.coalesce(getDefaultTimeRangeEndOffset(), fallback.getDefaultTimeRangeEndOffset())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\KPITimeRangeDefaults.java
1
请完成以下Java代码
public String format(final IHUPackingInfo huPackingInfo) { final StringBuilder packingInfo = new StringBuilder(); // // LU if (isShowLU()) { final I_M_HU_PI luPI = huPackingInfo.getM_LU_HU_PI(); if (luPI != null) { packingInfo.append(luPI.getName()); } } // // TU final I_M_HU_PI tuPI = huPackingInfo.getM_TU_HU_PI(); if (tuPI != null && !Services.get(IHandlingUnitsBL.class).isVirtual(tuPI)) { if (packingInfo.length() > 0) { packingInfo.append(" x "); } final BigDecimal qtyTU = huPackingInfo.getQtyTUsPerLU(); if (!huPackingInfo.isInfiniteQtyTUsPerLU() && qtyTU != null && qtyTU.signum() > 0) { packingInfo.append(qtyTU.intValue()).append(" "); } packingInfo.append(tuPI.getName()); } // // CU final BigDecimal qtyCU = huPackingInfo.getQtyCUsPerTU();
if (!huPackingInfo.isInfiniteQtyCUsPerTU() && qtyCU != null && qtyCU.signum() > 0) { if (packingInfo.length() > 0) { packingInfo.append(" x "); } final DecimalFormat qtyFormat = DisplayType.getNumberFormat(DisplayType.Quantity); packingInfo.append(qtyFormat.format(qtyCU)); final I_C_UOM uom = huPackingInfo.getQtyCUsPerTU_UOM(); final String uomSymbol = uom == null ? null : uom.getUOMSymbol(); if (uomSymbol != null) { packingInfo.append(" ").append(uomSymbol); } } if (packingInfo.length() == 0) { return null; // no override } return packingInfo.toString(); } public HUPackingInfoFormatter setShowLU(final boolean showLU) { _showLU = showLU; return this; } private boolean isShowLU() { return _showLU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\HUPackingInfoFormatter.java
1
请完成以下Java代码
public void init(TbActorCtx ctx) throws TbActorException { super.init(ctx); log.debug("[{}][{}] Starting CF entity actor.", processor.tenantId, processor.entityId); try { processor.init(ctx); log.debug("[{}][{}] CF entity actor started.", processor.tenantId, processor.entityId); } catch (Exception e) { log.warn("[{}][{}] Unknown failure", processor.tenantId, processor.entityId, e); throw new TbActorException("Failed to initialize CF entity actor", e); } } @Override public void destroy(TbActorStopReason stopReason, Throwable cause) throws TbActorException { log.debug("[{}] Stopping CF entity actor.", processor.tenantId); processor.stop(false); } @Override protected boolean doProcessCfMsg(ToCalculatedFieldSystemMsg msg) throws CalculatedFieldException { switch (msg.getMsgType()) { case CF_PARTITIONS_CHANGE_MSG: processor.process((CalculatedFieldPartitionChangeMsg) msg); break; case CF_STATE_RESTORE_MSG: processor.process((CalculatedFieldStateRestoreMsg) msg); break; case CF_STATE_PARTITION_RESTORE_MSG: processor.process((CalculatedFieldStatePartitionRestoreMsg) msg); break; case CF_ENTITY_INIT_CF_MSG: processor.process((EntityInitCalculatedFieldMsg) msg); break; case CF_ENTITY_DELETE_MSG: processor.process((CalculatedFieldEntityDeleteMsg) msg); break; case CF_RELATION_ACTION_MSG: processor.process((CalculatedFieldRelationActionMsg) msg); break; case CF_ENTITY_TELEMETRY_MSG: processor.process((EntityCalculatedFieldTelemetryMsg) msg); break; case CF_LINKED_TELEMETRY_MSG:
processor.process((EntityCalculatedFieldLinkedTelemetryMsg) msg); break; case CF_REEVALUATE_MSG: processor.process((CalculatedFieldReevaluateMsg) msg); break; case CF_ALARM_ACTION_MSG: processor.process((CalculatedFieldAlarmActionMsg) msg); break; case CF_ARGUMENT_RESET_MSG: processor.process((CalculatedFieldArgumentResetMsg) msg); break; default: return false; } return true; } @Override void logProcessingException(Exception e) { log.warn("[{}][{}] Processing failure", tenantId, processor.entityId, e); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\calculatedField\CalculatedFieldEntityActor.java
1
请完成以下Java代码
public class MyCustomRealm extends JdbcRealm { private Map<String, String> credentials = new HashMap<>(); private Map<String, Set<String>> roles = new HashMap<>(); private Map<String, Set<String>> perm = new HashMap<>(); { credentials.put("user", "password"); credentials.put("user2", "password2"); credentials.put("user3", "password3"); roles.put("user", new HashSet<>(Arrays.asList("admin"))); roles.put("user2", new HashSet<>(Arrays.asList("editor"))); roles.put("user3", new HashSet<>(Arrays.asList("author"))); perm.put("admin", new HashSet<>(Arrays.asList("*"))); perm.put("editor", new HashSet<>(Arrays.asList("articles:*"))); perm.put("author", new HashSet<>(Arrays.asList("articles:compose", "articles:save"))); } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken uToken = (UsernamePasswordToken) token; if(uToken.getUsername() == null || uToken.getUsername().isEmpty() || !credentials.containsKey(uToken.getUsername()) ) { throw new UnknownAccountException("username not found!"); } return new SimpleAuthenticationInfo( uToken.getUsername(), credentials.get(uToken.getUsername()), getName()); } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Set<String> roleNames = new HashSet<>(); Set<String> permissions = new HashSet<>(); principals.forEach(p -> { try { Set<String> roles = getRoleNamesForUser(null, (String) p); roleNames.addAll(roles); permissions.addAll(getPermissions(null, null,roles)); } catch (SQLException e) {
e.printStackTrace(); } }); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(permissions); return info; } @Override protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException { if(!roles.containsKey(username)) { throw new SQLException("username not found!"); } return roles.get(username); } @Override protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException { for (String role : roleNames) { if (!perm.containsKey(role)) { throw new SQLException("role not found!"); } } Set<String> finalSet = new HashSet<>(); for (String role : roleNames) { finalSet.addAll(perm.get(role)); } return finalSet; } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\MyCustomRealm.java
1
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public Map getParameters() { return parameters; } public void addParameter(String key, String value){ this.parameters.put(key, value); } public void addParameters(String key, Collection<String> values){ this.parameters.put(key, values); } public void setParameters(Map _parameters) { this.parameters.putAll(_parameters); } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public boolean isSslVerify() { return sslVerify; } public void setSslVerify(boolean sslVerify) { this.sslVerify = sslVerify; } public int getMaxResultSize() { return maxResultSize; } public void setMaxResultSize(int maxResultSize) { this.maxResultSize = maxResultSize; } public Map getHeaders() { return headers; } public void addHeader(String key, String value){ this.headers.put(key, value); } public void addHeaders(String key, Collection<String> values){ this.headers.put(key, values); } public void setHeaders(Map _headers) { this.headers.putAll(_headers); } public int getReadTimeout() {
return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public boolean isIgnoreContentIfUnsuccess() { return ignoreContentIfUnsuccess; } public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) { this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess; } public String getPostData() { return postData; } public void setPostData(String postData) { this.postData = postData; } public ClientKeyStore getClientKeyStore() { return clientKeyStore; } public void setClientKeyStore(ClientKeyStore clientKeyStore) { this.clientKeyStore = clientKeyStore; } public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() { return TrustKeyStore; } public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) { TrustKeyStore = trustKeyStore; } public boolean isHostnameVerify() { return hostnameVerify; } public void setHostnameVerify(boolean hostnameVerify) { this.hostnameVerify = hostnameVerify; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
2
请在Spring Boot框架中完成以下Java代码
public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) { super.update(reprocessMap); packIdx.set(0); } @Override protected void doOnSuccess(UUID id) { boolean endOfPendingPack; synchronized (pendingPack) { TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg> msg = pendingPack.remove(id); endOfPendingPack = msg != null && pendingPack.isEmpty(); } if (endOfPendingPack) { packIdx.incrementAndGet(); submitNext(); } } private void submitNext() { int listSize = orderedMsgList.size(); int startIdx = Math.min(packIdx.get() * batchSize, listSize); int endIdx = Math.min(startIdx + batchSize, listSize); Map<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> tmpPack; synchronized (pendingPack) {
pendingPack.clear(); for (int i = startIdx; i < endIdx; i++) { IdMsgPair<TransportProtos.ToRuleEngineMsg> pair = orderedMsgList.get(i); pendingPack.put(pair.uuid, pair.msg); } tmpPack = new LinkedHashMap<>(pendingPack); } int submitSize = pendingPack.size(); if (log.isDebugEnabled() && submitSize > 0) { log.debug("[{}] submitting [{}] messages to rule engine", queueName, submitSize); } tmpPack.forEach(msgConsumer); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\BatchTbRuleEngineSubmitStrategy.java
2
请完成以下Java代码
public Collaboration newInstance(ModelTypeInstanceContext instanceContext) { return new CollaborationImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); isClosedAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_CLOSED) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); participantCollection = sequenceBuilder.elementCollection(Participant.class) .build(); messageFlowCollection = sequenceBuilder.elementCollection(MessageFlow.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); conversationNodeCollection = sequenceBuilder.elementCollection(ConversationNode.class) .build(); conversationAssociationCollection = sequenceBuilder.elementCollection(ConversationAssociation.class) .build(); participantAssociationCollection = sequenceBuilder.elementCollection(ParticipantAssociation.class) .build(); messageFlowAssociationCollection = sequenceBuilder.elementCollection(MessageFlowAssociation.class) .build(); correlationKeyCollection = sequenceBuilder.elementCollection(CorrelationKey.class) .build(); conversationLinkCollection = sequenceBuilder.elementCollection(ConversationLink.class) .build(); typeBuilder.build(); } public CollaborationImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this);
} public void setName(String name) { nameAttribute.setValue(this, name); } public boolean isClosed() { return isClosedAttribute.getValue(this); } public void setClosed(boolean isClosed) { isClosedAttribute.setValue(this, isClosed); } public Collection<Participant> getParticipants() { return participantCollection.get(this); } public Collection<MessageFlow> getMessageFlows() { return messageFlowCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } public Collection<ConversationNode> getConversationNodes() { return conversationNodeCollection.get(this); } public Collection<ConversationAssociation> getConversationAssociations() { return conversationAssociationCollection.get(this); } public Collection<ParticipantAssociation> getParticipantAssociations() { return participantAssociationCollection.get(this); } public Collection<MessageFlowAssociation> getMessageFlowAssociations() { return messageFlowAssociationCollection.get(this); } public Collection<CorrelationKey> getCorrelationKeys() { return correlationKeyCollection.get(this); } public Collection<ConversationLink> getConversationLinks() { return conversationLinkCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CollaborationImpl.java
1
请完成以下Java代码
public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Request Type. @param RequestType Request Type */ public void setRequestType (String RequestType) { set_Value (COLUMNNAME_RequestType, RequestType); } /** Get Request Type. @return Request Type */ public String getRequestType () { return (String)get_Value(COLUMNNAME_RequestType); } /** Set Status Code. @param StatusCode Status Code */ public void setStatusCode (int StatusCode) {
set_Value (COLUMNNAME_StatusCode, Integer.valueOf(StatusCode)); } /** Get Status Code. @return Status Code */ public int getStatusCode () { Integer ii = (Integer)get_Value(COLUMNNAME_StatusCode); if (ii == null) return 0; return ii.intValue(); } /** Set User Agent. @param UserAgent Browser Used */ public void setUserAgent (String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } /** Get User Agent. @return Browser Used */ public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } /** Set Web Session. @param WebSession Web Session ID */ public void setWebSession (String WebSession) { set_Value (COLUMNNAME_WebSession, WebSession); } /** Get Web Session. @return Web Session ID */ public String getWebSession () { return (String)get_Value(COLUMNNAME_WebSession); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebAccessLog.java
1
请完成以下Java代码
public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** * ReplenishType AD_Reference_ID=164 * Reference name: M_Replenish Type */ public static final int REPLENISHTYPE_AD_Reference_ID=164; /** Maximalbestand beibehalten = 2 */ public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2"; /** Manuell = 0 */ public static final String REPLENISHTYPE_Manuell = "0"; /** Bei Unterschreitung Minimalbestand = 1 */ public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1"; /** Custom = 9 */ public static final String REPLENISHTYPE_Custom = "9"; /** Zuk?nftigen Bestand sichern = 7 */ public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7"; @Override public void setReplenishType (java.lang.String ReplenishType) { set_Value (COLUMNNAME_ReplenishType, ReplenishType);
} @Override public java.lang.String getReplenishType() { return (java.lang.String)get_Value(COLUMNNAME_ReplenishType); } @Override public void setTimeToMarket (int TimeToMarket) { set_Value (COLUMNNAME_TimeToMarket, Integer.valueOf(TimeToMarket)); } @Override public int getTimeToMarket() { return get_ValueAsInt(COLUMNNAME_TimeToMarket); } @Override public void setWarehouseValue (java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return (java.lang.String)get_Value(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Replenish.java
1
请完成以下Java代码
public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { writeResponse(ctx); } responseData.setLength(0); responseData.append(RequestUtils.formatParams(request)); } responseData.append(RequestUtils.evaluateDecoderResult(request)); if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; responseData.append(RequestUtils.formatBody(httpContent)); responseData.append(RequestUtils.evaluateDecoderResult(request)); if (msg instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) msg; responseData.append(RequestUtils.prepareLastResponse(request, trailer)); writeResponse(ctx, trailer, responseData); } } } private void writeResponse(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER); ctx.write(response); } private void writeResponse(ChannelHandlerContext ctx, LastHttpContent trailer, StringBuilder responseData) { boolean keepAlive = HttpUtil.isKeepAlive(request); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, ((HttpObject) trailer).decoderResult() .isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(responseData.toString(), CharsetUtil.UTF_8));
httpResponse.headers() .set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { httpResponse.headers() .setInt(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content() .readableBytes()); httpResponse.headers() .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(httpResponse); if (!keepAlive) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\http\server\CustomHttpServerHandler.java
1
请完成以下Spring Boot application配置
spring: ai: vectorstore: oracle: initialize-schema: true openai: api-key: ${OPENAI_API_KEY} embedding: options: model:
text-embedding-3-large chat: options: model: gpt-4o
repos\tutorials-master\spring-ai-modules\spring-ai-vector-stores\spring-ai-oracle\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class SecurPharmaActionRepository { public Set<SecurPharmProductId> getProductIdsByInventoryId(@NonNull final InventoryId inventoryId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_M_Securpharm_Action_Result.class) .addEqualsFilter(I_M_Securpharm_Action_Result.COLUMN_M_Inventory_ID, inventoryId) .addNotNull(I_M_Securpharm_Action_Result.COLUMNNAME_M_Securpharm_Productdata_Result_ID) .create() .listDistinct(I_M_Securpharm_Action_Result.COLUMNNAME_M_Securpharm_Productdata_Result_ID, Integer.class) .stream() .map(SecurPharmProductId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } public void save(@NonNull final DecommissionResponse response) { if (response.getId() != null) { throw new AdempiereException("Response was already saved: " + response); } final I_M_Securpharm_Action_Result record = newInstance(I_M_Securpharm_Action_Result.class); record.setIsError(response.isError()); record.setAction(SecurPharmAction.DECOMMISSION.getCode()); record.setM_Inventory_ID(InventoryId.toRepoId(response.getInventoryId())); record.setM_Securpharm_Productdata_Result_ID(response.getProductId().getRepoId()); record.setTransactionIDServer(response.getServerTransactionId());
saveRecord(record); response.setId(SecurPharmActionResultId.ofRepoId(record.getM_Securpharm_Action_Result_ID())); } public void save(@NonNull final UndoDecommissionResponse response) { if (response.getId() != null) { throw new AdempiereException("Response was already saved: " + response); } final I_M_Securpharm_Action_Result record = newInstance(I_M_Securpharm_Action_Result.class); record.setIsError(response.isError()); record.setAction(SecurPharmAction.UNDO_DECOMMISSION.getCode()); record.setM_Inventory_ID(InventoryId.toRepoId(response.getInventoryId())); record.setM_Securpharm_Productdata_Result_ID(response.getProductId().getRepoId()); record.setTransactionIDServer(response.getServerTransactionId()); saveRecord(record); response.setId(SecurPharmActionResultId.ofRepoId(record.getM_Securpharm_Action_Result_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\actions\SecurPharmaActionRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class ZuulPropertiesRefresher { private static final Logger logger = LoggerFactory.getLogger(ZuulPropertiesRefresher.class); @Autowired private ApplicationContext applicationContext; @Autowired private RouteLocator routeLocator; @ApolloConfigChangeListener(interestedKeyPrefixes = "zuul.") public void onChange(ConfigChangeEvent changeEvent) { refreshZuulProperties(changeEvent); } private void refreshZuulProperties(ConfigChangeEvent changeEvent) { logger.info("Refreshing zuul properties!"); /*
* rebind configuration beans, e.g. ZuulProperties * @see org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder#onApplicationEvent */ this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys())); /* * refresh routes * @see org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration.ZuulRefreshListener#onApplicationEvent */ this.applicationContext.publishEvent(new RoutesRefreshedEvent(routeLocator)); logger.info("Zuul properties refreshed!"); } }
repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo03-config-apollo\src\main\java\cn\iocoder\springcloud\labx21\zuuldemo\ZuulPropertiesRefresher.java
2
请完成以下Java代码
public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @Override public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public Date getEndDate() {
return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCorrelationId() { // v5 Jobs have no correlationId return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java
1
请完成以下Java代码
private QueryBuilder createElasticsearchQuery(final LookupDataSourceContext evalCtx) { final String text = evalCtx.getFilter(); return QueryBuilders.multiMatchQuery(text, esSearchFieldNames); } @Override public boolean isCached() { return true; } @Override public String getCachePrefix() { return null; } @Override public Optional<String> getLookupTableName() { return Optional.of(modelTableName); } @Override public void cacheInvalidate() { // nothing } @Override public LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public boolean isHighVolume() { return true; } @Override
public LookupSource getLookupSourceType() { return LookupSource.lookup; } @Override public boolean hasParameters() { return true; } @Override public boolean isNumericKey() { return true; } @Override public Set<String> getDependsOnFieldNames() { return null; } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } @Override public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression() { return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java
1
请完成以下Java代码
public TaskQuery taskNameNotEqual(String name) { this.nameNotEqual = name; return this; } @Override public TaskQuery taskNameNotLike(String nameNotLike) { ensureNotNull("Task nameNotLike", nameNotLike); this.nameNotLike = nameNotLike; return this; } /** * @return true if the query is not supposed to find CMMN or standalone tasks */ public boolean isQueryForProcessTasksOnly() { ProcessEngineConfigurationImpl engineConfiguration = Context.getProcessEngineConfiguration(); return !engineConfiguration.isCmmnEnabled() && !engineConfiguration.isStandaloneTasksEnabled(); } @Override public TaskQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } TaskQueryImpl orQuery = new TaskQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public TaskQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } @Override public TaskQuery matchVariableNamesIgnoreCase() { this.variableNamesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableNameIgnoreCase(true); } return this; } @Override public TaskQuery matchVariableValuesIgnoreCase() { this.variableValuesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableValueIgnoreCase(true); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public class Ruecknahmeangebot { @XmlElement(name = "Artikel", required = true) protected List<ArtikelMenge> artikel; @XmlAttribute(name = "Id", required = true) protected String id; /** * Gets the value of the artikel 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 artikel property. * * <p> * For example, to add a new item, do as follows: * <pre> * getArtikel().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ArtikelMenge } * * */ public List<ArtikelMenge> getArtikel() { if (artikel == null) {
artikel = new ArrayList<ArtikelMenge>(); } return this.artikel; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\Ruecknahmeangebot.java
1
请完成以下Java代码
public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public CoreModelElement getEventSource() { return eventSource; } public void setEventSource(CoreModelElement eventSource) { this.eventSource = eventSource; } public int getListenerIndex() { return listenerIndex; } public void setListenerIndex(int listenerIndex) { this.listenerIndex = listenerIndex; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void invokeListener(DelegateListener listener) throws Exception { listener.notify(this); } public boolean hasFailedOnEndListeners() { return false; } // getters / setters ///////////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBusinessKeyWithoutCascade() { return businessKeyWithoutCascade; }
public void setBusinessKey(String businessKey) { this.businessKey = businessKey; this.businessKeyWithoutCascade = businessKey; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMapping; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMapping = skipIoMappings; } public boolean isSkipSubprocesses() { return skipSubprocesses; } public void setSkipSubprocesseses(boolean skipSubprocesses) { this.skipSubprocesses = skipSubprocesses; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("tableName", tableName) .add("recordId", recordId) .add("AD_Window_ID", adWindowId) .toString(); } @Override public Properties getCtx() { return ctx; } @Override public String getTrxName() { return ITrx.TRXNAME_ThreadInherited; } @Override public AdWindowId getAD_Window_ID() { return adWindowId; } @Override public int getAD_Table_ID() { return adTableId; } @Override public String getKeyColumnNameOrNull() { return keyColumnName; }
@Override public int getRecord_ID() { return recordId; } @Override public boolean isSingleKeyRecord() { return keyColumnName != null; } @Override public Evaluatee createEvaluationContext() { return evaluationContext; } @Override public boolean hasField(final String columnName) { return document.hasField(columnName); } @Override public Object getFieldValue(final String columnName) { return document.getFieldView(columnName).getValue(); } @Override public boolean getFieldValueAsBoolean(final String columnName) { return document.getFieldView(columnName).getValueAsBoolean(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\service\WebuiDocumentReferencesService.java
2
请完成以下Java代码
public class MultiAlarmCar implements Vehicle, Alarm { private final String brand; public MultiAlarmCar(String brand) { this.brand = brand; } @Override public String getBrand() { return brand; } @Override public String speedUp() { return "The motorbike is speeding up."; } @Override public String slowDown() { return "The mootorbike is slowing down."; }
@Override public String turnAlarmOn() { return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn(); } @Override public String turnAlarmOff() { return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff(); } @Override public double getSpeed() { return 0; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\defaultstaticinterfacemethods\model\MultiAlarmCar.java
1
请完成以下Java代码
public final class SliceConnectionAdapter extends ConnectionAdapterSupport<ScrollPosition> implements ConnectionAdapter { /** * Constructor with the {@link CursorStrategy} to use to encode the * {@code ScrollPosition} of page items. * @param strategy the cursor strategy to use */ public SliceConnectionAdapter(CursorStrategy<ScrollPosition> strategy) { super(strategy); } @Override public boolean supports(Class<?> containerType) { return Slice.class.isAssignableFrom(containerType); } @Override public <T> Collection<T> getContent(Object container) { Slice<T> slice = slice(container); return slice.getContent(); } @Override public boolean hasPrevious(Object container) { return slice(container).hasPrevious();
} @Override public boolean hasNext(Object container) { return slice(container).hasNext(); } @Override public String cursorAt(Object container, int index) { Slice<?> slice = slice(container); ScrollPosition position = ScrollPosition.offset((long) slice.getNumber() * slice.getSize() + index); return getCursorStrategy().toCursor(position); } @SuppressWarnings("unchecked") private <T> Slice<T> slice(Object container) { return (Slice<T>) container; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\query\SliceConnectionAdapter.java
1
请完成以下Java代码
public final class ReactiveJwtAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> { private Converter<Jwt, Flux<GrantedAuthority>> jwtGrantedAuthoritiesConverter = new ReactiveJwtGrantedAuthoritiesConverterAdapter( new JwtGrantedAuthoritiesConverter()); private String principalClaimName = JwtClaimNames.SUB; @Override public Mono<AbstractAuthenticationToken> convert(Jwt jwt) { // @formatter:off return this.jwtGrantedAuthoritiesConverter.convert(jwt) .collectList() .map((authorities) -> { String principalName = jwt.getClaimAsString(this.principalClaimName); return new JwtAuthenticationToken(jwt, authorities, principalName); }); // @formatter:on } /** * Sets the {@link Converter Converter&lt;Jwt, Flux&lt;GrantedAuthority&gt;&gt;} to
* use. Defaults to a reactive {@link JwtGrantedAuthoritiesConverter}. * @param jwtGrantedAuthoritiesConverter The converter * @see JwtGrantedAuthoritiesConverter */ public void setJwtGrantedAuthoritiesConverter( Converter<Jwt, Flux<GrantedAuthority>> jwtGrantedAuthoritiesConverter) { Assert.notNull(jwtGrantedAuthoritiesConverter, "jwtGrantedAuthoritiesConverter cannot be null"); this.jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter; } /** * Sets the principal claim name. Defaults to {@link JwtClaimNames#SUB}. * @param principalClaimName The principal claim name * @since 6.1 */ public void setPrincipalClaimName(String principalClaimName) { Assert.hasText(principalClaimName, "principalClaimName cannot be empty"); this.principalClaimName = principalClaimName; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\ReactiveJwtAuthenticationConverter.java
1
请完成以下Java代码
public BigDecimal getNetAmtToInvoice() { return netAmtToInvoice; } @Override public BigDecimal getNetAmtInvoiced() { return netAmtInvoiced; } @Override public BigDecimal getDiscount() { return discount; } @Override public String getCurrencyISOCode() { return currencyISOCode; } @Override public String getInvoiceRuleName() { return invoiceRuleName; } @Override public String getHeaderAggregationKey() { return headerAggregationKey; } public static class Builder { private int C_Invoice_Candidate_ID; private String BPartnerName; private Date documentDate; // task 09643 private Date dateAcct; private Date dateToInvoice; private Date dateInvoiced; private BigDecimal netAmtToInvoice; private BigDecimal netAmtInvoiced; private BigDecimal discount; private String currencyISOCode; private String invoiceRuleName; private String headerAggregationKey; private Builder() { super(); } public InvoiceCandidateRow build() { return new InvoiceCandidateRow(this); } public Builder setC_Invoice_Candidate_ID(int C_Invoice_Candidate_ID) { this.C_Invoice_Candidate_ID = C_Invoice_Candidate_ID; return this; } public Builder setBPartnerName(String BPartnerName) { this.BPartnerName = BPartnerName; return this; } public Builder setDocumentDate(Date documentDate) {
this.documentDate = documentDate; return this; } /** * task 09643: separate accounting date from the transaction date * * @param dateAcct * @return */ public Builder setDateAcct(Date dateAcct) { this.dateAcct = dateAcct; return this; } public Builder setDateToInvoice(Date dateToInvoice) { this.dateToInvoice = dateToInvoice; return this; } public Builder setDateInvoiced(Date dateInvoiced) { this.dateInvoiced = dateInvoiced; return this; } public Builder setNetAmtToInvoice(BigDecimal netAmtToInvoice) { this.netAmtToInvoice = netAmtToInvoice; return this; } public Builder setNetAmtInvoiced(BigDecimal netAmtInvoiced) { this.netAmtInvoiced = netAmtInvoiced; return this; } public Builder setDiscount(BigDecimal discount) { this.discount = discount; return this; } public Builder setCurrencyISOCode(String currencyISOCode) { this.currencyISOCode = currencyISOCode; return this; } public Builder setInvoiceRuleName(String invoiceRuleName) { this.invoiceRuleName = invoiceRuleName; return this; } public Builder setHeaderAggregationKey(String headerAggregationKey) { this.headerAggregationKey = headerAggregationKey; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidateRow.java
1
请完成以下Java代码
public void setIsEuro (boolean IsEuro) { set_Value (COLUMNNAME_IsEuro, Boolean.valueOf(IsEuro)); } /** Get The Euro Currency. @return This currency is the Euro */ @Override public boolean isEuro () { Object oo = get_Value(COLUMNNAME_IsEuro); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Währungscode. @param ISO_Code Three letter ISO 4217 Code of the Currency */ @Override public void setISO_Code (java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code); } /** Get ISO Währungscode. @return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Round Off Factor. @param RoundOffFactor Used to Round Off Payment Amount */ @Override public void setRoundOffFactor (java.math.BigDecimal RoundOffFactor) { set_Value (COLUMNNAME_RoundOffFactor, RoundOffFactor); }
/** Get Round Off Factor. @return Used to Round Off Payment Amount */ @Override public java.math.BigDecimal getRoundOffFactor () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoundOffFactor); if (bd == null) return Env.ZERO; return bd; } /** Set Standardgenauigkeit. @param StdPrecision Rule for rounding calculated amounts */ @Override public void setStdPrecision (int StdPrecision) { set_Value (COLUMNNAME_StdPrecision, Integer.valueOf(StdPrecision)); } /** Get Standardgenauigkeit. @return Rule for rounding calculated amounts */ @Override public int getStdPrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_StdPrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency.java
1
请完成以下Java代码
public boolean isFocusable() { if (!isVisible()) { return false; } if (isSimpleSearchPanelActive()) { return m_editorFirst != null; } return false; } @Override public void setFocusable(final boolean focusable) { // ignore it } @Override public void requestFocus() { if (isSimpleSearchPanelActive()) { if (m_editorFirst != null) { m_editorFirst.requestFocus(); } } }
@Override public boolean requestFocusInWindow() { if (isSimpleSearchPanelActive()) { if (m_editorFirst != null) { return m_editorFirst.requestFocusInWindow(); } } return false; } private boolean disposed = false; boolean isDisposed() { return disposed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java
1
请完成以下Java代码
private final static int getJvm() { return JVM; } private final static short getCount() { synchronized (UUIDGenerator.class) { if (counter < 0) { counter = 0; } return counter++; } } /** * Unique in a local network */ private final static int getIp() { return IP; } /** * Unique down to millisecond */ private final static short getHiTime() {
return (short) (System.currentTimeMillis() >>> 32); } private final static int getLoTime() { return (int) System.currentTimeMillis(); } private final static int toInt(byte[] bytes) { int result = 0; int length = 4; for (int i = 0; i < length; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\UUIDGenerator.java
1
请完成以下Java代码
private static Object convertToPOValue( @NonNull final String columnName, @Nullable final Object value, @NonNull final POInfo poInfo, @NonNull final ZoneId zoneId) { final Class<?> columnTargetClass = poInfo.getColumnClass(columnName); if (columnTargetClass == null) { throw new AdempiereException("Cannot get the actual PO value if targetClass is missing!") .appendParametersToMessage() .setParameter("TableName", poInfo.getTableName()) .setParameter("ColumnName", columnName); } final int displayType = poInfo.getColumnDisplayType(columnName); return convertToPOValue(value, columnTargetClass, displayType, zoneId); } @Nullable private static Object convertToPOValue(@Nullable final Object value, @NonNull final Class<?> targetClass, final int displayType, @NonNull final ZoneId zoneId) { if (value == null) { return null; } if (String.class.equals(value.getClass())) { final String valueStr = (String)value; if (String.class.equals(targetClass)) { return valueStr; } // for all the other targetClass variants, an empty string or the "null" string are considered null values
else if (Check.isBlank(valueStr) || NULL_STRING.equalsIgnoreCase(valueStr)) { return null; } } return POValueConverters.convertToPOValue(value, targetClass, displayType, zoneId); } @Nullable public static Object convertFromPOValue(@NonNull final PO po, @NonNull final POInfoColumn poInfoColumn, @NonNull final ZoneId zoneId) { final Object poValue = po.get_Value(poInfoColumn.getColumnName()); return POValueConverters.convertFromPOValue(poValue, poInfoColumn.getDisplayType(), zoneId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnsConverters.java
1
请完成以下Java代码
public ResponseEntity<Object> mimicOriginalResponse( @ApiParam(required = true, value = "The API request audit ID to mimic response for") @PathVariable("requestId") @NonNull final String requestId) { try { final ApiResponseAudit apiResponse = apiAuditService .getLatestByRequestId(ApiRequestAuditId.ofRepoId(Integer.parseInt(requestId))) .orElse(null); if (apiResponse == null) { return ResponseEntity.notFound().build(); } final HttpStatus httpStatus = parseHttpStatus(apiResponse.getHttpCode()); final HttpHeaders headers = reconstructHeaders(apiResponse.getHttpHeaders()); return new ResponseEntity<>(apiResponse.getBody(), headers, httpStatus); } catch (final Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Error while mimicking original response: " + e.getMessage()); } } @NonNull private HttpStatus parseHttpStatus(@Nullable final String httpCode) { try { if (Check.isBlank(httpCode)) { throw new AdempiereException("HTTP Code is blank") .appendParametersToMessage() .setParameter("HttpCode", httpCode);
} final int statusCode = Integer.parseInt(httpCode.trim()); return HttpStatus.valueOf(statusCode); } catch (final Exception e) { throw new AdempiereException("Error while parsing HTTP Code", e) .appendParametersToMessage() .setParameter("HttpCode", httpCode); } } @NonNull private HttpHeaders reconstructHeaders(@Nullable final String httpHeadersJson) { final HttpHeaders headers = new HttpHeaders(); if (Check.isNotBlank(httpHeadersJson)) { final HttpHeadersWrapper headersWrapper = HttpHeadersWrapper .fromJson(httpHeadersJson, JsonObjectMapperHolder.sharedJsonObjectMapper()); headersWrapper.streamHeaders() .forEach(entry -> headers.add(entry.getKey(), entry.getValue())); } return headers; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\audit\ApiAuditController.java
1
请完成以下Java代码
public ImmutableList<I_AD_Process> getProcessesByType(@NonNull final Set<ProcessType> processTypeSet) { final Set<String> types = processTypeSet.stream().map(ProcessType::getCode).collect(Collectors.toSet()); return queryBL.createQueryBuilder(I_AD_Process.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_AD_Process.COLUMNNAME_Type, types) .create() .list() .stream() .collect(ImmutableList.toImmutableList()); } @NonNull public ImmutableList<I_AD_Process_Para> getProcessParamsByProcessIds(@NonNull final Set<Integer> processIDs) { return queryBL.createQueryBuilder(I_AD_Process_Para.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_AD_Process_Para.COLUMNNAME_AD_Process_ID, processIDs) .create() .list() .stream() .collect(ImmutableList.toImmutableList()); } @Override public void save(final I_AD_Process process) { InterfaceWrapperHelper.save(process); } @Override public void updateColumnNameByAdElementId( @NonNull final AdElementId adElementId, @Nullable final String newColumnName) { // NOTE: accept newColumnName to be null and expect to fail in case there is an AD_Process_Para which is using given AD_Element_ID DB.executeUpdateAndThrowExceptionOnFail( // Inline parameters because this sql will be logged into the migration script. "UPDATE " + I_AD_Process_Para.Table_Name + " SET ColumnName=" + DB.TO_STRING(newColumnName) + " WHERE AD_Element_ID=" + adElementId.getRepoId(), ITrx.TRXNAME_ThreadInherited); }
@Override public ProcessType retrieveProcessType(@NonNull final AdProcessId processId) { final I_AD_Process process = InterfaceWrapperHelper.loadOutOfTrx(processId, I_AD_Process.class); return ProcessType.ofCode(process.getType()); } @Override public ImmutableSet<AdProcessId> retrieveAllActiveAdProcesIds() { return queryBL.createQueryBuilderOutOfTrx(I_AD_Process.class) .addOnlyActiveRecordsFilter() .orderBy(I_AD_Process.COLUMNNAME_AD_Process_ID) .create() .idsAsSet(AdProcessId::ofRepoId); } @NonNull @Override public List<I_AD_Process> retrieveProcessRecordsByValRule(@NonNull final AdValRuleId valRuleId) { return queryBL.createQueryBuilder(I_AD_Process.class) .addOnlyActiveRecordsFilter() .filter(new ValidationRuleQueryFilter<>(I_AD_Process.Table_Name, valRuleId)) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADProcessDAO.java
1
请完成以下Java代码
public class MRPDAO implements IMRPDAO { @Override public IMRPQueryBuilder createMRPQueryBuilder() { return new MRPQueryBuilder(); } @Override public IMRPQueryBuilder retrieveQueryBuilder(final Object model, final String typeMRP, final String orderType) { final Optional<Integer> adClientId = InterfaceWrapperHelper.getValue(model, "AD_Client_ID"); Check.assume(adClientId.isPresent(), "param 'model'={} has an AD_Client_ID", model); final IMRPQueryBuilder queryBuilder = createMRPQueryBuilder() .setContextProvider(model) // use context from model .setAD_Client_ID(adClientId.get()) // use model's AD_Client_ID // Only those MRP records which are referencing our model .setReferencedModel(model) // Filter by TypeMRP (Demand/Supply) .setTypeMRP(typeMRP) // Filter by OrderType (i.e. like document base type) .setOrderType(orderType); // // In case we query for PP_Order and TypeMRP=Supply, we need to make sure only header Supply is returned (because that's what is expected). // The TypeMRP=D/S filter is not enough since a BOM Line can produce a supply (e.g. co-product) // TODO: get rid of this HARDCODED/particular case if (InterfaceWrapperHelper.isInstanceOf(model, I_PP_Order.class) && X_PP_MRP.TYPEMRP_Supply.equals(typeMRP)) { queryBuilder.setPP_Order_BOMLine_Null(); } //
// Return the query builder return queryBuilder; } protected BigDecimal getQtyOnHand(final Properties ctx, final int M_Warehouse_ID, final int M_Product_ID, final String trxName) { final int adClientId = Env.getAD_Client_ID(ctx); final String sql = "SELECT COALESCE(bomQtyOnHand (M_Product_ID,?,0),0) FROM M_Product" + " WHERE AD_Client_ID=? AND M_Product_ID=?"; final BigDecimal qtyOnHand = DB.getSQLValueBDEx(trxName, sql, M_Warehouse_ID, adClientId, M_Product_ID); if (qtyOnHand == null) { return BigDecimal.ZERO; } return qtyOnHand; } @Override public BigDecimal getQtyOnHand(final IContextAware context, final I_M_Warehouse warehouse, final I_M_Product product) { final Properties ctx = context.getCtx(); final String trxName = context.getTrxName(); final int warehouseId = warehouse.getM_Warehouse_ID(); final int productId = product.getM_Product_ID(); return getQtyOnHand(ctx, warehouseId, productId, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPDAO.java
1
请完成以下Java代码
public class ClusterStateSimpleEntity { private Integer mode; private Long lastModified; private Boolean clientAvailable; private Boolean serverAvailable; public Integer getMode() { return mode; } public ClusterStateSimpleEntity setMode(Integer mode) { this.mode = mode; return this; } public Long getLastModified() { return lastModified; } public ClusterStateSimpleEntity setLastModified(Long lastModified) { this.lastModified = lastModified; return this; } public Boolean getClientAvailable() { return clientAvailable; } public ClusterStateSimpleEntity setClientAvailable(Boolean clientAvailable) { this.clientAvailable = clientAvailable; return this; } public Boolean getServerAvailable() {
return serverAvailable; } public ClusterStateSimpleEntity setServerAvailable(Boolean serverAvailable) { this.serverAvailable = serverAvailable; return this; } @Override public String toString() { return "ClusterStateSimpleEntity{" + "mode=" + mode + ", lastModified=" + lastModified + ", clientAvailable=" + clientAvailable + ", serverAvailable=" + serverAvailable + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\ClusterStateSimpleEntity.java
1
请完成以下Java代码
public void removeCurrentPlanFragment() { this.planFragmentsStack.removeLast(); } public Stage getCurrentStage() { return stagesStack.peekLast(); } public void setCurrentStage(Stage currentStage) { if (currentStage != null) { this.stagesStack.add(currentStage); setCurrentPlanFragment(currentStage); } } public void removeCurrentStage() { this.stagesStack.removeLast(); removeCurrentPlanFragment(); } public void setCurrentCmmnElement(CmmnElement currentCmmnElement) { currentCmmnElements.add(currentCmmnElement); } public void removeCurrentCmmnElement() { currentCmmnElements.removeLast(); } public Sentry getCurrentSentry() { return currentSentry; } public void setCurrentSentry(Sentry currentSentry) { this.currentSentry = currentSentry; } public SentryOnPart getCurrentSentryOnPart() { return currentSentryOnPart; } public void setCurrentSentryOnPart(SentryOnPart currentSentryOnPart) { this.currentSentryOnPart = currentSentryOnPart; } public PlanItem getCurrentPlanItem() { return currentPlanItem; } public void setCurrentPlanItem(PlanItem currentPlanItem) { this.currentPlanItem = currentPlanItem; } public CmmnDiShape getCurrentDiShape() { return currentDiShape; } public void setCurrentDiShape(CmmnDiShape currentDiShape) { this.currentDiShape = currentDiShape; } public CmmnDiEdge getCurrentDiEdge() { return currentDiEdge; } public void setCurrentDiEdge(CmmnDiEdge currentDiEdge) { this.currentDiEdge = currentDiEdge; } public List<Stage> getStages() { return stages; }
public List<PlanFragment> getPlanFragments() { return planFragments; } public List<Criterion> getEntryCriteria() { return entryCriteria; } public List<Criterion> getExitCriteria() { return exitCriteria; } public List<Sentry> getSentries() { return sentries; } public List<SentryOnPart> getSentryOnParts() { return sentryOnParts; } public List<SentryIfPart> getSentryIfParts() { return sentryIfParts; } public List<PlanItem> getPlanItems() { return planItems; } public List<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitions; } public List<CmmnDiShape> getDiShapes() { return diShapes; } public List<CmmnDiEdge> getDiEdges() { return diEdges; } public GraphicInfo getCurrentLabelGraphicInfo() { return currentLabelGraphicInfo; } public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) { this.currentLabelGraphicInfo = labelGraphicInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
1
请完成以下Java代码
public boolean isSuccess(){ return SUCCESS_CODE == code; } public boolean isFailure(){ return !isSuccess(); } public int getCode() { return code; } public void setCode(int code) { this.code = code; }
public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getContent() { return content; } public void setContent(T content) { this.content = content; } }
repos\kkFileView-master\server\src\main\java\cn\keking\model\ReturnResponse.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONRange { public static final JSONRange of(final DateRangeValue range) { final LocalDate from = range.getFrom(); final String jsonFrom = from != null ? DateTimeConverters.toJson(from) : null; final LocalDate to = range.getTo(); final String jsonTo = to != null ? DateTimeConverters.toJson(to) : null; return new JSONRange(jsonFrom, jsonTo); } public static DateRangeValue dateRangeFromJSONMap(final Map<String, String> map) { final String jsonFrom = map.get("value"); final LocalDate from = DateTimeConverters.fromObjectToLocalDate(jsonFrom);
final String jsonTo = map.get("valueTo"); final LocalDate to = DateTimeConverters.fromObjectToLocalDate(jsonTo); return DateRangeValue.of(from, to); } @JsonProperty("value") private final String value; @JsonProperty("valueTo") private final String valueTo; @JsonCreator @Builder private JSONRange(@JsonProperty("value") final String value, @JsonProperty("valueTo") final String valueTo) { this.value = value; this.valueTo = valueTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONRange.java
2
请在Spring Boot框架中完成以下Java代码
public class LdapPasswordComparisonAuthenticationManagerFactory extends AbstractLdapAuthenticationManagerFactory<PasswordComparisonAuthenticator> { private PasswordEncoder passwordEncoder; private String passwordAttribute; public LdapPasswordComparisonAuthenticationManagerFactory(BaseLdapPathContextSource contextSource, PasswordEncoder passwordEncoder) { super(contextSource); setPasswordEncoder(passwordEncoder); } /** * Specifies the {@link PasswordEncoder} to be used when authenticating with password * comparison. * @param passwordEncoder the {@link PasswordEncoder} to use */ public void setPasswordEncoder(PasswordEncoder passwordEncoder) { Assert.notNull(passwordEncoder, "passwordEncoder must not be null."); this.passwordEncoder = passwordEncoder; } /**
* The attribute in the directory which contains the user password. Only used when * authenticating with password comparison. Defaults to "userPassword". * @param passwordAttribute the attribute in the directory which contains the user * password */ public void setPasswordAttribute(String passwordAttribute) { this.passwordAttribute = passwordAttribute; } @Override protected PasswordComparisonAuthenticator createDefaultLdapAuthenticator() { PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator(getContextSource()); if (this.passwordAttribute != null) { ldapAuthenticator.setPasswordAttributeName(this.passwordAttribute); } ldapAuthenticator.setPasswordEncoder(this.passwordEncoder); return ldapAuthenticator; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapPasswordComparisonAuthenticationManagerFactory.java
2
请完成以下Java代码
public class PMMPricingAware_QtyReportEvent implements IPMMPricingAware { public static final PMMPricingAware_QtyReportEvent of(final I_PMM_QtyReport_Event qtyReportEvent) { return new PMMPricingAware_QtyReportEvent(qtyReportEvent); } private final I_PMM_QtyReport_Event qtyReportEvent; private PMMPricingAware_QtyReportEvent(final I_PMM_QtyReport_Event qtyReportEvent) { super(); Check.assumeNotNull(qtyReportEvent, "qtyReportEvent not null"); this.qtyReportEvent = qtyReportEvent; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("qtyReportEvent", qtyReportEvent) .toString(); } @Override public Properties getCtx() { return InterfaceWrapperHelper.getCtx(qtyReportEvent); } @Override public I_C_BPartner getC_BPartner() { return qtyReportEvent.getC_BPartner(); } @Override public boolean isContractedProduct() { final String contractLine_uuid = qtyReportEvent.getContractLine_UUID(); return !Check.isEmpty(contractLine_uuid, true); } @Override public I_M_Product getM_Product() { return qtyReportEvent.getM_Product(); } @Override public int getProductId() { return qtyReportEvent.getM_Product_ID(); } @Override public I_C_UOM getC_UOM() { return qtyReportEvent.getC_UOM(); } @Override public I_C_Flatrate_Term getC_Flatrate_Term() { return qtyReportEvent.getC_Flatrate_Term(); }
@Override public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry() { return InterfaceWrapperHelper.create(qtyReportEvent.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class); } @Override public Object getWrappedModel() { return qtyReportEvent; } @Override public Timestamp getDate() { return qtyReportEvent.getDatePromised(); } @Override public BigDecimal getQty() { return qtyReportEvent.getQtyPromised(); } @Override public void setM_PricingSystem_ID(final int M_PricingSystem_ID) { qtyReportEvent.setM_PricingSystem_ID(M_PricingSystem_ID); } @Override public void setM_PriceList_ID(final int M_PriceList_ID) { qtyReportEvent.setM_PriceList_ID(M_PriceList_ID); } @Override public void setCurrencyId(final CurrencyId currencyId) { qtyReportEvent.setC_Currency_ID(CurrencyId.toRepoId(currencyId)); } @Override public void setPrice(final BigDecimal price) { qtyReportEvent.setPrice(price); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMPricingAware_QtyReportEvent.java
1
请完成以下Java代码
boolean is_projective() { return !is_non_projective(); } boolean is_non_projective() { for (int modifier = 0; modifier < heads.size(); ++modifier) { int head = heads.get(modifier); if (head < modifier) { for (int from = head + 1; from < modifier; ++from) { int to = heads.get(from); if (to < head || to > modifier) { return true; }
} } else { for (int from = modifier + 1; from < head; ++from) { int to = heads.get(from); if (to < modifier || to > head) { return true; } } } } return false; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Instance.java
1
请在Spring Boot框架中完成以下Java代码
public boolean matchesFilter(RateLimitsTrigger trigger, RateLimitsNotificationRuleTriggerConfig triggerConfig) { return trigger.getLimitLevel() != null && trigger.getApi().getLabel() != null && CollectionsUtil.emptyOrContains(triggerConfig.getApis(), trigger.getApi()); } @Override public RuleOriginatedNotificationInfo constructNotificationInfo(RateLimitsTrigger trigger) { EntityId limitLevel = trigger.getLimitLevel(); String tenantName = tenantService.findTenantById(trigger.getTenantId()).getName(); String limitLevelEntityName = null; if (limitLevel instanceof TenantId) { limitLevelEntityName = tenantName; } else if (limitLevel != null) { limitLevelEntityName = Optional.ofNullable(trigger.getLimitLevelEntityName()) .orElseGet(() -> entityService.fetchEntityName(trigger.getTenantId(), limitLevel).orElse(null)); }
return RateLimitsNotificationInfo.builder() .tenantId(trigger.getTenantId()) .tenantName(tenantName) .api(trigger.getApi()) .limitLevel(limitLevel) .limitLevelEntityName(limitLevelEntityName) .build(); } @Override public NotificationRuleTriggerType getTriggerType() { return NotificationRuleTriggerType.RATE_LIMITS; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\RateLimitsTriggerProcessor.java
2
请完成以下Java代码
private List<IQueryFilter<T>> getNonSqlFiltersToUse() { final List<ISqlQueryFilter> sqlFilters = getSqlFilters(); final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFilters(); if (!and && sqlFilters != null && !sqlFilters.isEmpty() && nonSqlFilters != null && !nonSqlFilters.isEmpty()) { throw new IllegalStateException("Cannot create a partial nonSQL filter when this filter has join method OR and it also have SQL filters: " + this); } if (!isDefaultAccept()) { throw new IllegalStateException("Cannot create a partial nonSQL filter when this filter DefaultAccept=false: " + this); } return nonSqlFilters; } @Override public final List<ISqlQueryFilter> getSqlFilters() { compileIfNeeded(); return _sqlFilters; } @Override public final boolean isPureSql() { // Case: a composite filter without any filters inside shall be considered pure SQL if (filters.isEmpty()) { return true; } final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFilters(); return nonSqlFilters == null || nonSqlFilters.isEmpty(); } @Override public final boolean isPureNonSql() { // Case: a composite filter without any filters inside shall not be considered pure nonSQL if (filters.isEmpty()) { return false; } final List<ISqlQueryFilter> sqlFilters = getSqlFilters(); return sqlFilters == null || sqlFilters.isEmpty(); } @Override public boolean isJoinAnd() { return and; } @Override public boolean isJoinOr() { return !and; } @Override public String getSql() { if (!isPureSql()) { throw new IllegalStateException("Cannot get SQL for a filter which is not pure SQL: " + this); } return getSqlFiltersWhereClause(); } @Override public List<Object> getSqlParams(final Properties ctx) { if (!isPureSql()) {
throw new IllegalStateException("Cannot get SQL Parameters for a filter which is not pure SQL: " + this); } return getSqlFiltersParams(ctx); } @Override public ISqlQueryFilter asSqlQueryFilter() { if (!isPureSql()) { throw new IllegalStateException("Cannot convert to pure SQL filter when this filter is not pure SQL: " + this); } return this; } @Override public ISqlQueryFilter asPartialSqlQueryFilter() { return partialSqlQueryFilter; } @Override public IQueryFilter<T> asPartialNonSqlFilterOrNull() { final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFiltersToUse(); if (nonSqlFilters == null || nonSqlFilters.isEmpty()) { return null; } return partialNonSqlQueryFilter; } @Override public CompositeQueryFilter<T> allowSqlFilters(final boolean allowSqlFilters) { if (this._allowSqlFilters == allowSqlFilters) { return this; } this._allowSqlFilters = allowSqlFilters; _compiled = false; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
static class AlreadyInitializedEngineConfiguration { @Bean public DmnEngine dmnEngine(@SuppressWarnings("unused") ProcessEngine processEngine) { // The process engine needs to be injected, as otherwise it won't be initialized, which means that the DmnEngine is not initialized yet if (!DmnEngines.isInitialized()) { throw new IllegalStateException("DMN engine has not been initialized"); } return DmnEngines.getDefaultDmnEngine(); } } /** * If an app engine is present that means that the DmnEngine was created as part of the app engine. * Therefore extract it from the DmnEngines. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(type = { "org.flowable.dmn.engine.DmnEngine" }) @ConditionalOnBean(type = { "org.flowable.app.engine.AppEngine" }) static class AlreadyInitializedAppEngineConfiguration { @Bean public DmnEngine dmnEngine(@SuppressWarnings("unused") AppEngine appEngine) { // The app engine needs to be injected, as otherwise it won't be initialized, which means that the DmnEngine is not initialized yet if (!DmnEngines.isInitialized()) { throw new IllegalStateException("DMN engine has not been initialized"); } return DmnEngines.getDefaultDmnEngine(); } } /** * If there is no process engine configuration, then trigger a creation of the dmn engine. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(type = { "org.flowable.dmn.engine.DmnEngine", "org.flowable.engine.ProcessEngine", "org.flowable.app.engine.AppEngine" }) static class StandaloneEngineConfiguration extends BaseEngineConfigurationWithConfigurers<SpringDmnEngineConfiguration> { @Bean public DmnEngineFactoryBean dmnEngine(SpringDmnEngineConfiguration dmnEngineConfiguration) { DmnEngineFactoryBean factory = new DmnEngineFactoryBean(); factory.setDmnEngineConfiguration(dmnEngineConfiguration); invokeConfigurers(dmnEngineConfiguration);
return factory; } } @Bean public DmnManagementService dmnManagementService(DmnEngine dmnEngine) { return dmnEngine.getDmnManagementService(); } @Bean public DmnRepositoryService dmnRepositoryService(DmnEngine dmnEngine) { return dmnEngine.getDmnRepositoryService(); } @Bean public DmnDecisionService dmnRuleService(DmnEngine dmnEngine) { return dmnEngine.getDmnDecisionService(); } @Bean public DmnHistoryService dmnHistoryService(DmnEngine dmnEngine) { return dmnEngine.getDmnHistoryService(); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\DmnEngineServicesAutoConfiguration.java
2
请完成以下Java代码
public JsonWFProcess reportCounting(@RequestBody @NonNull final JsonCountRequest request) { assertApplicationAccess(); final Inventory inventory = jobService.reportCounting(request, Env.getLoggedUserId()); return toJsonWFProcess(inventory); } private JsonWFProcess toJsonWFProcess(final Inventory inventory) { return workflowRestController.toJson(WFProcessMapper.toWFProcess(inventory)); } @GetMapping("/lineHU") public JsonInventoryLineHU getLineHU( @RequestParam("wfProcessId") @NonNull String wfProcessIdStr, @RequestParam("lineId") @NonNull String lineIdStr, @RequestParam("lineHUId") @NonNull String lineHUIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr); final InventoryLineHUId lineHUId = InventoryLineHUId.ofObject(lineHUIdStr); final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId); return mappers.newJsonInventoryJobMapper(newJsonOpts()) .loadAllDetails(true) .toJson(line, lineHUId); } @GetMapping("/lineHUs") public JsonGetLineHUsResponse getLineHUs(
@RequestParam("wfProcessId") @NonNull String wfProcessIdStr, @RequestParam("lineId") @NonNull String lineIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr); final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId); return JsonGetLineHUsResponse.builder() .wfProcessId(wfProcessId) .lineId(lineId) .lineHUs(mappers.newJsonInventoryJobMapper(newJsonOpts()).toJsonInventoryLineHUs(line)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\InventoryRestController.java
1
请完成以下Java代码
protected void onEventInternal(ActivitiEvent event) { ExecutionEntity execution = null; if (event.getExecutionId() != null) { // Get the execution based on the event's execution ID instead execution = Context.getCommandContext().getExecutionEntityManager().findById(event.getExecutionId()); } if (execution == null) { throw new ActivitiException( "No execution context active and event is not related to an execution. No compensation event can be thrown." ); } try {
ErrorPropagation.propagateError(errorCode, execution); } catch (Exception e) { throw new ActivitiException("Error while propagating error-event", e); } } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } @Override public boolean isFailOnException() { return true; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ErrorThrowingEventListener.java
1
请完成以下Java代码
public String getPinyinWithoutTone() { return pinyinWithoutTone; } /** * 获取输入法头 * @return */ public String getHeadString() { return head.toString(); } /** * 获取输入法头
* @return */ public Head getHead() { return head; } /** * 获取首字母 * @return */ public char getFirstChar() { return firstChar; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\Pinyin.java
1
请完成以下Java代码
public void setExecutor_UUID (java.lang.String Executor_UUID) { set_Value (COLUMNNAME_Executor_UUID, Executor_UUID); } @Override public java.lang.String getExecutor_UUID() { return (java.lang.String)get_Value(COLUMNNAME_Executor_UUID); } @Override public void setT_Query_Selection_ToDelete_ID (int T_Query_Selection_ToDelete_ID) { if (T_Query_Selection_ToDelete_ID < 1) set_ValueNoCheck (COLUMNNAME_T_Query_Selection_ToDelete_ID, null); else set_ValueNoCheck (COLUMNNAME_T_Query_Selection_ToDelete_ID, Integer.valueOf(T_Query_Selection_ToDelete_ID)); }
@Override public int getT_Query_Selection_ToDelete_ID() { return get_ValueAsInt(COLUMNNAME_T_Query_Selection_ToDelete_ID); } @Override public void setUUID (java.lang.String UUID) { set_ValueNoCheck (COLUMNNAME_UUID, UUID); } @Override public java.lang.String getUUID() { return (java.lang.String)get_Value(COLUMNNAME_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_ToDelete.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.lowerCaseAlphaNumeric.equals(((EndpointId) obj).lowerCaseAlphaNumeric); } @Override public int hashCode() { return this.lowerCaseAlphaNumeric.hashCode(); } /** * Return a lower-case version of the endpoint ID. * @return the lower-case endpoint ID */ public String toLowerCaseString() { return this.lowerCaseValue; } @Override public String toString() { return this.value; } /** * Factory method to create a new {@link EndpointId} of the specified value. * @param value the endpoint ID value * @return an {@link EndpointId} instance */ public static EndpointId of(String value) { return new EndpointId(value); } /** * Factory method to create a new {@link EndpointId} of the specified value. This * variant will respect the {@code management.endpoints.migrate-legacy-names} property * if it has been set in the {@link Environment}. * @param environment the Spring environment * @param value the endpoint ID value * @return an {@link EndpointId} instance * @since 2.2.0 */ public static EndpointId of(Environment environment, String value) { Assert.notNull(environment, "'environment' must not be null"); return new EndpointId(migrateLegacyId(environment, value)); }
private static String migrateLegacyId(Environment environment, String value) { if (environment.getProperty(MIGRATE_LEGACY_NAMES_PROPERTY, Boolean.class, false)) { return value.replaceAll("[-.]+", ""); } return value; } /** * Factory method to create a new {@link EndpointId} from a property value. More * lenient than {@link #of(String)} to allow for common "relaxed" property variants. * @param value the property value to convert * @return an {@link EndpointId} instance */ public static EndpointId fromPropertyValue(String value) { return new EndpointId(value.replace("-", "")); } static void resetLoggedWarnings() { loggedWarnings.clear(); } private static void logWarning(String value) { if (logger.isWarnEnabled() && loggedWarnings.add(value)) { logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format."); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\EndpointId.java
1
请完成以下Java代码
public void setObscureType (final @Nullable java.lang.String ObscureType) { set_Value (COLUMNNAME_ObscureType, ObscureType); } @Override public java.lang.String getObscureType() { return get_ValueAsString(COLUMNNAME_ObscureType); } @Override public void setSelectionColumnSeqNo (final @Nullable BigDecimal SelectionColumnSeqNo) { set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo); } @Override public BigDecimal getSelectionColumnSeqNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override
public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override public int getSpanX() { return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请完成以下Java代码
public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPostal (final @Nullable java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setSiteName (final @Nullable java.lang.String SiteName) { set_ValueNoCheck (COLUMNNAME_SiteName, SiteName); } @Override
public java.lang.String getSiteName() { return get_ValueAsString(COLUMNNAME_SiteName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_119_v.java
1
请完成以下Java代码
public int getC_Printing_Queue_ID() { return get_ValueAsInt(COLUMNNAME_C_Printing_Queue_ID); } @Override public de.metas.printing.model.I_C_Print_Job getC_Print_Job() { return get_ValueAsPO(COLUMNNAME_C_Print_Job_ID, de.metas.printing.model.I_C_Print_Job.class); } @Override public void setC_Print_Job(de.metas.printing.model.I_C_Print_Job C_Print_Job) { set_ValueFromPO(COLUMNNAME_C_Print_Job_ID, de.metas.printing.model.I_C_Print_Job.class, C_Print_Job); } @Override public void setC_Print_Job_ID (int C_Print_Job_ID) { if (C_Print_Job_ID < 1) set_Value (COLUMNNAME_C_Print_Job_ID, null); else set_Value (COLUMNNAME_C_Print_Job_ID, Integer.valueOf(C_Print_Job_ID)); } @Override public int getC_Print_Job_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_ID); } @Override public void setC_Print_Job_Line_ID (int C_Print_Job_Line_ID) { if (C_Print_Job_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Print_Job_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Print_Job_Line_ID, Integer.valueOf(C_Print_Job_Line_ID)); } @Override public int getC_Print_Job_Line_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Line_ID); }
@Override public de.metas.printing.model.I_C_Print_Package getC_Print_Package() { return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class); } @Override public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package) { set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package); } @Override public void setC_Print_Package_ID (int C_Print_Package_ID) { if (C_Print_Package_ID < 1) set_Value (COLUMNNAME_C_Print_Package_ID, null); else set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID)); } @Override public int getC_Print_Package_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID); } @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Line.java
1
请完成以下Java代码
public class CreateMatchInvoicePlan implements Iterable<CreateMatchInvoicePlanLine> { @Getter @NonNull private final ImmutableList<CreateMatchInvoicePlanLine> lines; private CreateMatchInvoicePlan(@NonNull final List<CreateMatchInvoicePlanLine> lines) { if (lines.isEmpty()) { throw new AdempiereException("No plan lines"); } this.lines = ImmutableList.copyOf(lines); } public static CreateMatchInvoicePlan ofList(List<CreateMatchInvoicePlanLine> lines) { return new CreateMatchInvoicePlan(lines); } public boolean isEmpty() { return lines.isEmpty(); } @Override public Iterator<CreateMatchInvoicePlanLine> iterator() { return lines.iterator(); } public void setCostAmountInvoiced(@NonNull final Money invoicedAmt, @NonNull final CurrencyPrecision precision) { final CurrencyId currencyId = invoicedAmt.getCurrencyId(); final Money totalCostAmountInOut = getCostAmountInOut(); final Money totalInvoicedAmtDiff = invoicedAmt.subtract(totalCostAmountInOut); if (totalInvoicedAmtDiff.isZero()) { return; } if (isEmpty()) { throw new AdempiereException("Cannot spread invoice amount difference if there is no line"); } Money totalInvoicedAmtDiffDistributed = Money.zero(currencyId); for (int i = 0, lastIndex = lines.size() - 1; i <= lastIndex; i++) { final CreateMatchInvoicePlanLine line = lines.get(i); final Money lineCostAmountInOut = line.getCostAmountInOut(); final Money lineInvoicedAmtDiff; if (i != lastIndex) {
final Percent percentage = lineCostAmountInOut.percentageOf(totalCostAmountInOut); lineInvoicedAmtDiff = totalInvoicedAmtDiff.multiply(percentage, precision); } else { lineInvoicedAmtDiff = totalInvoicedAmtDiff.subtract(totalInvoicedAmtDiffDistributed); } line.setCostAmountInvoiced(lineCostAmountInOut.add(lineInvoicedAmtDiff)); totalInvoicedAmtDiffDistributed = totalInvoicedAmtDiffDistributed.add(lineInvoicedAmtDiff); } } private Money getCostAmountInOut() { return lines.stream().map(CreateMatchInvoicePlanLine::getCostAmountInOut).reduce(Money::add) .orElseThrow(() -> new AdempiereException("No lines")); // shall not happen } public Money getInvoicedAmountDiff() { return lines.stream().map(CreateMatchInvoicePlanLine::getInvoicedAmountDiff).reduce(Money::add) .orElseThrow(() -> new AdempiereException("No lines")); // shall not happen } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\invoice\CreateMatchInvoicePlan.java
1
请完成以下Java代码
public int getM_HU_PI_Item_Product_ID() { return ddOrderLine.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { ddOrderLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return ddOrderLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return ddOrderLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { values.setC_UOM_ID(uomId); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { ddOrderLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() {
return ddOrderLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { ddOrderLine.setQtyEnteredTU(qtyPacks); values.setQtyTU(qtyPacks); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public void setC_BPartner_ID(final int partnerId) { // nothing } @Override public int getC_BPartner_ID() { return ddOrderLine.getDD_Order().getC_BPartner_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\lowlevel\model\DDOrderLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { Map<Long, Employee> employeeMap = new HashMap<>(); @RequestMapping(value = "/employee", method = RequestMethod.GET) public ModelAndView showForm() { return new ModelAndView("employeeHome", "employee", new Employee()); } @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } @RequestMapping(value = "/addEmployee", method = RequestMethod.POST, params = "submit") public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) {
return "error"; } model.addAttribute("name", employee.getName()); model.addAttribute("contactNumber", employee.getContactNumber()); model.addAttribute("id", employee.getId()); employeeMap.put(employee.getId(), employee); return "employeeView"; } @RequestMapping(value = "/addEmployee", method = RequestMethod.POST, params = "cancel") public String cancel(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { model.addAttribute("message", "You clicked cancel, please re-enter employee details:"); return "employeeHome"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\springmvcforms\controller\EmployeeController.java
2
请完成以下Java代码
public void setEnforceSameSizeOnAllLabels(boolean enforceSameSizeOnAllLabels) { this.enforceSameSizeOnAllLabels = enforceSameSizeOnAllLabels; } public void setLabelMinWidth(final int labelMinWidth) { this.labelMinWidth = labelMinWidth; } public void setLabelMaxWidth(final int labelMaxWidth) { this.labelMaxWidth = labelMaxWidth; } public void setFieldMinWidth(final int fieldMinWidth) { this.fieldMinWidth = fieldMinWidth; } public void setFieldMaxWidth(final int fieldMaxWidth) { this.fieldMaxWidth = fieldMaxWidth; } public void updateMinWidthFrom(final CLabel label) { final int labelWidth = label.getPreferredSize().width; labelMinWidth = labelWidth > labelMinWidth ? labelWidth : labelMinWidth;
logger.trace("LabelMinWidth={} ({})", new Object[] { labelMinWidth, label }); } public void updateMinWidthFrom(final VEditor editor) { final JComponent editorComp = swingEditorFactory.getEditorComponent(editor); final int editorCompWidth = editorComp.getPreferredSize().width; if (editorCompWidth > fieldMinWidth) { fieldMinWidth = editorCompWidth; } logger.trace("FieldMinWidth={} ({})", new Object[] { fieldMinWidth, editorComp }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelLayoutCallback.java
1
请完成以下Java代码
public void setUnrealizedGain_Acct (int UnrealizedGain_Acct) { set_Value (COLUMNNAME_UnrealizedGain_Acct, Integer.valueOf(UnrealizedGain_Acct)); } /** Get Nicht realisierte Währungsgewinne. @return Konto für nicht realisierte Währungsgewinne */ @Override public int getUnrealizedGain_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedGain_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A) { set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A); } /** Set Nicht realisierte Währungsverluste. @param UnrealizedLoss_Acct Konto für nicht realisierte Währungsverluste
*/ @Override public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct) { set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct)); } /** Get Nicht realisierte Währungsverluste. @return Konto für nicht realisierte Währungsverluste */ @Override public int getUnrealizedLoss_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource"); if (hasDataSourceUrlProperty(context)) { return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is set")); } if (anyMatches(context, metadata, this.pooledCondition)) { return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source")); } if (!ClassUtils.isPresent(EMBEDDED_DATABASE_TYPE, context.getClassLoader())) { return ConditionOutcome .noMatch(message.didNotFind("required class").items(Style.QUOTE, EMBEDDED_DATABASE_TYPE)); } EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType(); if (type == null) { return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll()); } return ConditionOutcome.match(message.found("embedded database").items(type)); }
private boolean hasDataSourceUrlProperty(ConditionContext context) { Environment environment = context.getEnvironment(); if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) { try { return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY)); } catch (IllegalArgumentException ex) { // NOTE: This should be PlaceholderResolutionException // Ignore unresolvable placeholder errors } } return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceAutoConfiguration.java
2
请完成以下Java代码
public class MapInitializer { public static Map<String, String> articleMapOne; static { articleMapOne = new HashMap<>(); articleMapOne.put("ar01", "Intro to Map"); articleMapOne.put("ar02", "Some article"); } public static Map<String, String> createSingletonMap() { Map<String, String> passwordMap = Collections.singletonMap("username1", "password1"); return passwordMap; } public Map<String, String> createEmptyMap() { Map<String, String> emptyMap = Collections.emptyMap(); return emptyMap; } public Map<String, String> createUsingDoubleBrace() { Map<String, String> doubleBraceMap = new HashMap<String, String>() { /** * */ private static final long serialVersionUID = 1L; { put("key1", "value1"); put("key2", "value2"); } }; return doubleBraceMap; } public Map<String, String> createMapUsingStreamStringArray() { Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.toMap(data -> data[0], data -> data[1])); return map; } public Map<String, Integer> createMapUsingStreamObjectArray() { Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }) .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); return map; } public Map<String, Integer> createMapUsingStreamSimpleEntry() { Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return map; } public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() { Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return map; } public Map<String, String> createImmutableMapWithStreams() { Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap)); return map; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\initialize\MapInitializer.java
1
请完成以下Java代码
private <V> Mono<V> forward(Instance instance, ForwardRequest forwardRequest, Function<ClientResponse, Mono<V>> responseHandler) { log.trace("Proxy-Request for instance {} with URL '{}'", instance.getId(), forwardRequest.getUri()); WebClient.RequestBodySpec bodySpec = this.instanceWebClient.instance(instance) .method(forwardRequest.getMethod()) .uri(forwardRequest.getUri()) .headers((h) -> h.addAll(forwardRequest.getHeaders())); WebClient.RequestHeadersSpec<?> headersSpec = bodySpec; if (requiresBody(forwardRequest.getMethod())) { headersSpec = bodySpec.body(forwardRequest.getBody()); } return headersSpec.exchangeToMono(responseHandler).onErrorResume(ResolveEndpointException.class, (ex) -> { log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(), forwardRequest.getUri()); return responseHandler.apply(ClientResponse.create(HttpStatus.NOT_FOUND, this.strategies).build()); }).onErrorResume((ex) -> { Throwable cause = ex; if (ex instanceof WebClientRequestException) { cause = ex.getCause(); } if (cause instanceof ReadTimeoutException || cause instanceof TimeoutException) { log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), forwardRequest.getUri()); return responseHandler .apply(ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, this.strategies).build()); } if (cause instanceof IOException) { log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), forwardRequest.getUri(), cause); return responseHandler.apply(ClientResponse.create(HttpStatus.BAD_GATEWAY, this.strategies).build()); } return Mono.error(ex); }); } private boolean requiresBody(HttpMethod method) { return List.of(PUT, POST, PATCH).contains(method); } @lombok.Data @lombok.Builder(builderClassName = "Builder") public static class InstanceResponse { private final InstanceId instanceId;
private final int status; @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) private final String body; @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) private final String contentType; } @lombok.Data @lombok.Builder(builderClassName = "Builder") public static class ForwardRequest { private final URI uri; private final HttpMethod method; private final HttpHeaders headers; private final BodyInserter<?, ? super ClientHttpRequest> body; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\InstanceWebProxy.java
1
请完成以下Java代码
private CurrencyId lookupCurrencyId(@NonNull final JsonPrice jsonPrice) { final CurrencyId result = currencyService.getCurrencyId(jsonPrice.getCurrencyCode()); if (result == null) { throw MissingResourceException.builder().resourceName("currency").resourceIdentifier(jsonPrice.getPriceUomCode()).parentResource(jsonPrice).build(); } return result; } private UomId lookupUomId( @Nullable final X12DE355 uomCode, @NonNull final ProductId productId, @NonNull final JsonCreateInvoiceCandidatesRequestItem item) { if (uomCode == null) { return productBL.getStockUOMId(productId); } final UomId priceUomId; try { priceUomId = uomDAO.getUomIdByX12DE355(uomCode); } catch (final AdempiereException e)
{ throw MissingResourceException.builder().resourceName("uom").resourceIdentifier("priceUomCode").parentResource(item).cause(e).build(); } return priceUomId; } private InvoiceCandidateLookupKey createInvoiceCandidateLookupKey(@NonNull final JsonCreateInvoiceCandidatesRequestItem item) { try { return InvoiceCandidateLookupKey.builder() .externalHeaderId(JsonExternalIds.toExternalIdOrNull(item.getExternalHeaderId())) .externalLineId(JsonExternalIds.toExternalIdOrNull(item.getExternalLineId())) .build(); } catch (final AdempiereException e) { throw InvalidEntityException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoicecandidates\impl\CreateInvoiceCandidatesService.java
1
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); if (route == null) { return chain.filter(exchange); } log.trace("RouteToRequestUrlFilter start"); URI uri = exchange.getRequest().getURI(); boolean encoded = containsEncodedParts(uri); URI routeUri = route.getUri(); if (hasAnotherScheme(routeUri)) { // this is a special url, save scheme to special attribute // replace routeUri with schemeSpecificPart exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, routeUri.getScheme()); routeUri = URI.create(routeUri.getSchemeSpecificPart()); } if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) { // Load balanced URIs should always have a host. If the host is null it is // most likely because the host name was invalid (for example included an // underscore)
throw new IllegalStateException("Invalid host: " + routeUri.toString()); } URI mergedUrl = UriComponentsBuilder.fromUri(uri) // .uri(routeUri) .scheme(routeUri.getScheme()) .host(routeUri.getHost()) .port(routeUri.getPort()) .build(encoded) .toUri(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl); return chain.filter(exchange); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\RouteToRequestUrlFilter.java
1
请在Spring Boot框架中完成以下Java代码
private void validateQueueConfiguration(TenantProfileQueueConfiguration queue) { validateQueueName(queue.getName()); validateQueueTopic(queue.getTopic()); if (queue.getPollInterval() < 1) { throw new DataValidationException("Queue poll interval should be more then 0!"); } if (queue.getPartitions() < 1) { throw new DataValidationException("Queue partitions should be more then 0!"); } if (queue.getPackProcessingTimeout() < 1) { throw new DataValidationException("Queue pack processing timeout should be more then 0!"); } SubmitStrategy submitStrategy = queue.getSubmitStrategy(); if (submitStrategy == null) { throw new DataValidationException("Queue submit strategy can't be null!"); } if (submitStrategy.getType() == null) { throw new DataValidationException("Queue submit strategy type can't be null!"); } if (submitStrategy.getType() == SubmitStrategyType.BATCH && submitStrategy.getBatchSize() < 1) { throw new DataValidationException("Queue submit strategy batch size should be more then 0!"); } ProcessingStrategy processingStrategy = queue.getProcessingStrategy(); if (processingStrategy == null) { throw new DataValidationException("Queue processing strategy can't be null!"); }
if (processingStrategy.getType() == null) { throw new DataValidationException("Queue processing strategy type can't be null!"); } if (processingStrategy.getRetries() < 0) { throw new DataValidationException("Queue processing strategy retries can't be less then 0!"); } if (processingStrategy.getFailurePercentage() < 0 || processingStrategy.getFailurePercentage() > 100) { throw new DataValidationException("Queue processing strategy failure percentage should be in a range from 0 to 100!"); } if (processingStrategy.getPauseBetweenRetries() < 0) { throw new DataValidationException("Queue processing strategy pause between retries can't be less then 0!"); } if (processingStrategy.getMaxPauseBetweenRetries() < processingStrategy.getPauseBetweenRetries()) { throw new DataValidationException("Queue processing strategy MAX pause between retries can't be less then pause between retries!"); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\TenantProfileDataValidator.java
2
请完成以下Java代码
public void unlock() { sync.releaseShared(1); } @Override public Condition newCondition() { return sync.newCondition(); } public static void main(String[] args) { final Lock lock = new SharedLock(5); // 启动10个线程 for (int i = 0; i < 100; i++) { new Thread(() -> { lock.lock(); try {
System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } catch (Exception e) { } finally { lock.unlock(); } }).start(); } // 每隔1秒换行 for (int i = 0; i < 20; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\SharedLock.java
1
请完成以下Java代码
public MigratingEventScopeInstance addEventScopeInstance( MigrationInstruction migrationInstruction, ExecutionEntity eventScopeExecution, ScopeImpl sourceScope, ScopeImpl targetScope, MigrationInstruction eventSubscriptionInstruction, EventSubscriptionEntity eventSubscription, ScopeImpl eventSubscriptionSourceScope, ScopeImpl eventSubscriptionTargetScope) { MigratingEventScopeInstance compensationInstance = new MigratingEventScopeInstance( migrationInstruction, eventScopeExecution, sourceScope, targetScope, eventSubscriptionInstruction, eventSubscription, eventSubscriptionSourceScope, eventSubscriptionTargetScope); migratingEventScopeInstances.add(compensationInstance); return compensationInstance; } public MigratingCompensationEventSubscriptionInstance addCompensationSubscriptionInstance(
MigrationInstruction eventSubscriptionInstruction, EventSubscriptionEntity eventSubscription, ScopeImpl sourceScope, ScopeImpl targetScope) { MigratingCompensationEventSubscriptionInstance compensationInstance = new MigratingCompensationEventSubscriptionInstance( eventSubscriptionInstruction, sourceScope, targetScope, eventSubscription); migratingCompensationSubscriptionInstances.add(compensationInstance); return compensationInstance; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingProcessInstance.java
1
请完成以下Java代码
public ProcessInstance getProcessInstance() { Execution execution = getExecution(); if (execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))) { return processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult(); } return (ProcessInstance) execution; } // internal implementation // ////////////////////////////////////////////////////////// protected void assertAssociated() { if (associationManager.getExecution() == null) { throw new FlowableCdiException("No execution associated. Call businessProcess.associateExecutionById() or businessProcess.startTask() first."); } } protected void assertTaskAssociated() { if (associationManager.getTask() == null) { throw new FlowableCdiException("No task associated. Call businessProcess.startTask() first.");
} } protected Map<String, Object> getCachedVariables() { return associationManager.getCachedVariables(); } protected Map<String, Object> getAndClearCachedVariables() { Map<String, Object> beanStore = getCachedVariables(); Map<String, Object> copy = new HashMap<>(beanStore); beanStore.clear(); return copy; } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\BusinessProcess.java
1
请在Spring Boot框架中完成以下Java代码
private static OAuthIdentity extractOAuthIdentity(final JsonExternalSystemOutboundEndpoint endpointParameters) { return OAuthIdentity.builder() .tokenUrl(extractBaseUrl(endpointParameters.getEndpointUrl()) + "/login") .clientId(endpointParameters.getClientId()) .username(endpointParameters.getUser()) .build(); } @NonNull private static String extractBaseUrl(@NonNull final String endpointUrl) { final URL url; try { url = new URL(endpointUrl); } catch (final MalformedURLException e) { throw new RuntimeCamelException("Failed to parse endpoint URL: " + endpointUrl, e); } final String protocol = url.getProtocol(); final String host = url.getHost(); final int port = url.getPort(); // returns -1 if not specified return port == -1 ? String.format("%s://%s", protocol, host) : String.format("%s://%s:%d", protocol, host, port); } private void forceRefreshOAuthToken(@NonNull final Exchange exchange) { final MsgFromMfContext msgFromMfContext = getMsgFromMfContext(exchange); final JsonExternalSystemOutboundEndpoint endpointParameters = msgFromMfContext.getEndpointParameters(); // Invalidate the cached token so the next request will get a fresh token oauthTokenManager.invalidateToken(extractOAuthIdentity(endpointParameters)); // Re-prepare request with fresh token prepareHttpRequestForOAuth(exchange); } private void prepareJsonAttachmentRequest(@NonNull final Exchange exchange) { final MsgFromMfContext msgFromMfContext = getMsgFromMfContext(exchange); final JsonAttachment attachment = JsonAttachment.builder() .fileName(ATTACHMENT_FILE_NAME) .data(buildBase64FileData(exchange)) .type(JsonAttachmentSourceType.Data) .build(); final JsonTableRecordReference jsonTableRecordReference = JsonTableRecordReference.builder()
.tableName(msgFromMfContext.getOutboundRecordTableName()) .recordId(JsonMetasfreshId.of(msgFromMfContext.getOutboundRecordId())) .build(); final JsonAttachmentRequest jsonAttachmentRequest = JsonAttachmentRequest.builder() .attachment(attachment) .orgCode(msgFromMfContext.getOrgCode()) .reference(jsonTableRecordReference) .build(); exchange.getIn().setBody(jsonAttachmentRequest); } @NonNull private String buildBase64FileData(@NonNull final Exchange exchange) { final MsgFromMfContext msgFromMfContext = getMsgFromMfContext(exchange); final String endpointResponse = exchange.getIn().getBody(String.class); final String fileContent = "=== Scripted Adapter Log ===\n" + "Timestamp: " + LocalDateTime.now() + "\n" + "Script Name: " + msgFromMfContext.getScriptIdentifier() + "\n" + "Script Returned Value: " + msgFromMfContext.getScriptReturnValue() + "\n" + "HTTP Endpoint: " + msgFromMfContext.getEndpointParameters().getEndpointUrl() + "\n" + "HTTP Response: " + endpointResponse + "\n"; return Base64.getEncoder().encodeToString(fileContent.getBytes()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\convertmsg\from_mf\ScriptedAdapterConvertMsgFromMFRouteBuilder.java
2
请完成以下Java代码
private void setAudioInputStream(AudioInputStream aStream) { this.audioInputStream = aStream; } public AudioInputStream convertToAudioIStream(final ByteArrayOutputStream out, int frameSizeInBytes) { byte audioBytes[] = out.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes); AudioInputStream audioStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes); long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format.getFrameRate()); duration = milliseconds / 1000.0; System.out.println("Recorded duration in seconds:" + duration); return audioStream; } public TargetDataLine getTargetDataLineForRecord() { TargetDataLine line; DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { return null; } try { line = (TargetDataLine) AudioSystem.getLine(info); line.open(format, line.getBufferSize()); } catch (final Exception ex) { return null; }
return line; } public AudioInputStream getAudioInputStream() { return audioInputStream; } public AudioFormat getFormat() { return format; } public void setFormat(AudioFormat format) { this.format = format; } public Thread getThread() { return thread; } public double getDuration() { return duration; } }
repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\example\soundapi\SoundRecorder.java
1