instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public CaseInstanceStartEventSubscriptionDeletionBuilder caseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; return this; } @Override public CaseInstanceStartEventSubscriptionDeletionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public CaseInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) { correlationParameterValues.put(parameterName, parameterValue); return this; } @Override public CaseInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValues(Map<String, Object> parameters) { correlationParameterValues.putAll(parameters); return this; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getTenantId() { return tenantId; }
public boolean hasCorrelationParameterValues() { return correlationParameterValues.size() > 0; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } @Override public void deleteSubscriptions() { checkValidInformation(); cmmnRuntimeService.deleteCaseInstanceStartEventSubscriptions(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(caseDefinitionId)) { throw new FlowableIllegalArgumentException("The case definition must be provided using the exact id of the version the subscription was registered for."); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionDeletionBuilderImpl.java
1
请完成以下Java代码
public class UmsResourceCategory implements Serializable { private Long id; @ApiModelProperty(value = "创建时间") private Date createTime; @ApiModelProperty(value = "分类名称") private String name; @ApiModelProperty(value = "排序") private Integer sort; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @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(", createTime=").append(createTime); sb.append(", name=").append(name); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsResourceCategory.java
1
请完成以下Java代码
protected Class<TbMsgPushToEdgeNodeConfiguration> getConfigClazz() { return TbMsgPushToEdgeNodeConfiguration.class; } @Override protected void processMsg(TbContext ctx, TbMsg msg) { try { if (EntityType.EDGE.equals(msg.getOriginator().getEntityType())) { EdgeEvent edgeEvent = buildEvent(msg, ctx); EdgeId edgeId = new EdgeId(msg.getOriginator().getId()); ListenableFuture<Void> future = notifyEdge(ctx, edgeEvent, edgeId); FutureCallback<Void> futureCallback = new FutureCallback<>() { @Override public void onSuccess(@Nullable Void result) { ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }; Futures.addCallback(future, futureCallback, ctx.getDbCallbackExecutor()); } else { List<ListenableFuture<Void>> futures = new ArrayList<>(); PageDataIterableByTenantIdEntityId<EdgeId> edgeIds = new PageDataIterableByTenantIdEntityId<>( ctx.getEdgeService()::findRelatedEdgeIdsByEntityId, ctx.getTenantId(), msg.getOriginator(), RELATED_EDGES_CACHE_ITEMS); for (EdgeId edgeId : edgeIds) { EdgeEvent edgeEvent = buildEvent(msg, ctx); futures.add(notifyEdge(ctx, edgeEvent, edgeId)); } if (futures.isEmpty()) { // ack in case no edges are related to provided entity ctx.ack(msg); } else { Futures.addCallback(Futures.allAsList(futures), new FutureCallback<>() { @Override public void onSuccess(@Nullable List<Void> voids) { ctx.tellSuccess(msg);
} @Override public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } }, ctx.getDbCallbackExecutor()); } } } catch (Exception e) { log.error("Failed to build edge event", e); ctx.tellFailure(msg, e); } } private ListenableFuture<Void> notifyEdge(TbContext ctx, EdgeEvent edgeEvent, EdgeId edgeId) { edgeEvent.setEdgeId(edgeId); return ctx.getEdgeEventService().saveAsync(edgeEvent); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\edge\TbMsgPushToEdgeNode.java
1
请完成以下Java代码
public List<String> getProcessKeyNotIn() { return processKeyNotIn; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public String getInvolvedUser() { return involvedUser; } public String getName() { return name; } public String getNameLike() { return nameLike; } public static long getSerialversionuid() { return serialVersionUID; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public boolean isDeleted() { return deleted; } public boolean isNotDeleted() { return notDeleted; }
public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isWithException() { return withJobException; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<String> getInvolvedGroups() { return involvedGroups; } public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
HazelcastInstance hazelcastInstance(HazelcastProperties properties, ResourceLoader resourceLoader, ObjectProvider<HazelcastConfigCustomizer> hazelcastConfigCustomizers) throws IOException { Resource configLocation = properties.resolveConfigLocation(); Config config = (configLocation != null) ? loadConfig(configLocation) : Config.load(); config.setClassLoader(resourceLoader.getClassLoader()); hazelcastConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(config)); return getHazelcastInstance(config); } private Config loadConfig(Resource configLocation) throws IOException { URL configUrl = configLocation.getURL(); Config config = loadConfig(configUrl); if (ResourceUtils.isFileURL(configUrl)) { config.setConfigurationFile(configLocation.getFile()); } else { config.setConfigurationUrl(configUrl); } return config; } private Config loadConfig(URL configUrl) throws IOException { try (InputStream stream = configUrl.openStream()) { return Config.loadFromStream(stream); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnSingleCandidate(Config.class) static class HazelcastServerConfigConfiguration { @Bean HazelcastInstance hazelcastInstance(Config config) { return getHazelcastInstance(config); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(SpringManagedContext.class) static class SpringManagedContextHazelcastConfigCustomizerConfiguration { @Bean @Order(0) HazelcastConfigCustomizer springManagedContextHazelcastConfigCustomizer(ApplicationContext applicationContext) { return (config) -> { SpringManagedContext managementContext = new SpringManagedContext(); managementContext.setApplicationContext(applicationContext); config.setManagedContext(managementContext); }; } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(org.slf4j.Logger.class) static class HazelcastLoggingConfigCustomizerConfiguration {
@Bean @Order(0) HazelcastConfigCustomizer loggingHazelcastConfigCustomizer() { return (config) -> { if (!config.getProperties().containsKey(HAZELCAST_LOGGING_TYPE)) { config.setProperty(HAZELCAST_LOGGING_TYPE, "slf4j"); } }; } } /** * {@link HazelcastConfigResourceCondition} that checks if the * {@code spring.hazelcast.config} configuration key is defined. */ static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml", "file:./hazelcast.yaml", "classpath:/hazelcast.yaml", "file:./hazelcast.yml", "classpath:/hazelcast.yml"); } } }
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\HazelcastServerConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private void prepareErrorFile(@NonNull final Exchange exchange) { final StringBuilder content = new StringBuilder(); content.append(" Exchange body when error occurred: ") .append(exchange.getIn().getBody(String.class)) .append("\n"); final Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); if (exception == null) { content.append(" No info available!"); } else { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); content.append(" Error Message: ").append(exception.getLocalizedMessage()).append("\n"); content.append(" Error Stacktrace: ").append(sw); } exchange.getIn().setBody(content.toString()); exchange.getIn().setHeader(Exchange.FILE_NAME, FILE_TIMESTAMP_FORMATTER.format(ZonedDateTime.now()) + "_error.txt"); } private void prepareJsonErrorRequest(@NonNull final Exchange exchange) { final String pInstanceId = exchange.getIn().getHeader(HEADER_PINSTANCE_ID, String.class); if (pInstanceId == null) { throw new RuntimeException("No PInstanceId available!"); } final JsonErrorItem errorItem = ErrorProcessor.getErrorItem(exchange); exchange.getIn().setBody(JsonError.ofSingleItem(errorItem)); } @NonNull private Optional<Integer> getAPIRequestId(@NonNull final Exchange exchange) { final Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); if (!(exception instanceof HttpOperationFailedException)) { return Optional.empty(); } final String response = ((HttpOperationFailedException)exception).getResponseBody(); if (Check.isBlank(response)) { return Optional.empty(); } try { final JsonApiResponse apiResponse = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(response, JsonApiResponse.class); return Optional.ofNullable(JsonMetasfreshId.toValue(apiResponse.getRequestId())); } catch (final JsonProcessingException e) { return Optional.empty();
} } private void prepareErrorLogMessage(@NonNull final Exchange exchange) { final Integer pInstanceId = exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class); if (pInstanceId == null) { throw new RuntimeException("No PInstanceId available!"); } final JsonErrorItem errorItem = ErrorProcessor.getErrorItem(exchange); final StringBuilder logMessageBuilder = new StringBuilder(); getAPIRequestId(exchange) .ifPresent(apiRequestId -> logMessageBuilder.append("ApiRequestAuditId: ") .append(apiRequestId) .append(";")); logMessageBuilder.append(" Error: ").append(StringUtils.removeCRLF(errorItem.toString())); final LogMessageRequest logMessageRequest = LogMessageRequest.builder() .logMessage(logMessageBuilder.toString()) .pInstanceId(JsonMetasfreshId.of(pInstanceId)) .build(); exchange.getIn().setBody(logMessageRequest); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\ErrorReportRouteBuilder.java
2
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } public int getAD_Session_ID() { return AD_Session_ID; } public String getTrxName() { return trxName; } public int getAD_Table_ID() { return AD_Table_ID; } public int getAD_Column_ID() { return AD_Column_ID; } public int getRecord_ID() { return record_ID; } public int getAD_Client_ID() { return AD_Client_ID; } public int getAD_Org_ID() { return AD_Org_ID; } public Object getOldValue() { return oldValue; } public Object getNewValue() { return newValue; } public String getEventType() { return eventType; } public int getAD_User_ID() { return AD_User_ID; } public PInstanceId getAD_PInstance_ID() { return AD_PInstance_ID; } public static final class Builder { private int AD_Session_ID; private String trxName; private int AD_Table_ID; private int AD_Column_ID; private int record_ID; private int AD_Client_ID; private int AD_Org_ID; private Object oldValue; private Object newValue; private String eventType; private int AD_User_ID; private PInstanceId AD_PInstance_ID; private Builder() { super(); } public ChangeLogRecord build() { return new ChangeLogRecord(this); } public Builder setAD_Session_ID(final int AD_Session_ID) { this.AD_Session_ID = AD_Session_ID; return this; } public Builder setTrxName(final String trxName) { this.trxName = trxName; return this; } public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID;
return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) { this.record_ID = record_ID; return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) { this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请完成以下Java代码
public class DiscordNotifier extends AbstractContentNotifier { private static final String DEFAULT_MESSAGE = "*#{name}* (#{id}) is *#{status}*"; private RestTemplate restTemplate; /** * Webhook URI for the Discord API (i.e. * https://discordapp.com/api/webhooks/{webhook.id}/{webhook.token}) */ @Nullable private URI webhookUrl; /** * If the message is a text to speech message. False by default. */ private boolean tts = false; /** * Optional username. Default is set in Discord. */ @Nullable private String username; /** * Optional URL to avatar. */ @Nullable private String avatarUrl; public DiscordNotifier(InstanceRepository repository, RestTemplate restTemplate) { super(repository); this.restTemplate = restTemplate; } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { if (webhookUrl == null) { return Mono.error(new IllegalStateException("'webhookUrl' must not be null.")); } return Mono.fromRunnable( () -> restTemplate.postForEntity(webhookUrl, createDiscordNotification(event, instance), Void.class)); } protected Object createDiscordNotification(InstanceEvent event, Instance instance) { Map<String, Object> body = new HashMap<>(); body.put("content", createContent(event, instance)); body.put("tts", tts); if (avatarUrl != null) { body.put("avatar_url", avatarUrl); } if (username != null) {
body.put("username", username); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add(HttpHeaders.USER_AGENT, "RestTemplate"); return new HttpEntity<>(body, headers); } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } @Nullable public URI getWebhookUrl() { return webhookUrl; } public void setWebhookUrl(@Nullable URI webhookUrl) { this.webhookUrl = webhookUrl; } public boolean isTts() { return tts; } public void setTts(boolean tts) { this.tts = tts; } @Nullable public String getUsername() { return username; } public void setUsername(@Nullable String username) { this.username = username; } @Nullable public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(@Nullable String avatarUrl) { this.avatarUrl = avatarUrl; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DiscordNotifier.java
1
请完成以下Java代码
public static class Builder extends PermissionsBuilder<OrgPermission, OrgPermissions> { private final AdTreeId orgTreeId; private final ImmutableSet.Builder<ClientId> adClientIds = ImmutableSet.builder(); private final ImmutableSet.Builder<OrgId> adOrgIds = ImmutableSet.builder(); private Builder(@Nullable final AdTreeId orgTreeId) { this.orgTreeId = orgTreeId; } @Override protected void buildPrepare() { for (final OrgPermission perm : getPermissionsInternalMap().values()) { adClientIds.add(perm.getClientId()); adOrgIds.add(perm.getOrgId()); } } @Override protected OrgPermissions createPermissionsInstance() { return new OrgPermissions(this); } private AdTreeId getOrgTreeId() { return orgTreeId; } /** * Load Org Access Add Tree to List */ public Builder addPermissionRecursively(final OrgPermission oa) { if (hasPermission(oa)) { return this; } addPermission(oa, CollisionPolicy.Override); // Do we look for trees? final AdTreeId adTreeOrgId = getOrgTreeId(); if (adTreeOrgId == null) { return this; } final OrgResource orgResource = oa.getResource(); if (!orgResource.isGroupingOrg()) { return this; } // Summary Org - Get Dependents final MTree_Base tree = MTree_Base.getById(adTreeOrgId); final String sql = "SELECT " + " AD_Client_ID"
+ ", AD_Org_ID" + ", " + I_AD_Org.COLUMNNAME_IsSummary + " FROM AD_Org " + " WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName() + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')"; final Object[] sqlParams = new Object[] { tree.getAD_Tree_ID(), orgResource.getOrgId() }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); while (rs.next()) { final ClientId clientId = ClientId.ofRepoId(rs.getInt(1)); final OrgId orgId = OrgId.ofRepoId(rs.getInt(2)); final boolean isGroupingOrg = StringUtils.toBoolean(rs.getString(3)); final OrgResource resource = OrgResource.of(clientId, orgId, isGroupingOrg); final OrgPermission childOrgPermission = oa.copyWithResource(resource); addPermissionRecursively(childOrgPermission); } return this; } catch (final SQLException e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermissions.java
1
请完成以下Java代码
protected Mono<ServerResponse> prepareResponse(ServerRequest request, WebGraphQlResponse response) { MediaType responseMediaType = selectResponseMediaType(request); HttpStatus responseStatus = selectResponseStatus(response, responseMediaType); ServerResponse.BodyBuilder builder = ServerResponse.status(responseStatus); builder.headers((headers) -> headers.putAll(response.getResponseHeaders())); builder.contentType(responseMediaType); return builder.bodyValue(encodeResponseIfNecessary(response)); } protected HttpStatus selectResponseStatus(WebGraphQlResponse response, MediaType responseMediaType) { if (!isHttpOkOnValidationErrors() && !response.getExecutionResult().isDataPresent() && MediaTypes.APPLICATION_GRAPHQL_RESPONSE.equals(responseMediaType)) { return HttpStatus.BAD_REQUEST; } return HttpStatus.OK; } private static MediaType selectResponseMediaType(ServerRequest serverRequest) { ServerRequest.Headers headers = serverRequest.headers(); List<MediaType> acceptedMediaTypes; try {
acceptedMediaTypes = headers.accept(); } catch (InvalidMediaTypeException ex) { throw new NotAcceptableStatusException("Could not parse " + "Accept header [" + headers.firstHeader(HttpHeaders.ACCEPT) + "]: " + ex.getMessage()); } for (MediaType accepted : acceptedMediaTypes) { if (SUPPORTED_MEDIA_TYPES.contains(accepted)) { return accepted; } } return MediaType.APPLICATION_JSON; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\GraphQlHttpHandler.java
1
请在Spring Boot框架中完成以下Java代码
public List<Parameter> retrieveParams(Properties ctx, String parentTable, int parentId, String parameterTable, String trxName) { final List<Parameter> result = new ArrayList<Parameter>(); final List<IParameterPO> paramPOs = Services.get(IParametersDAO.class).retrieveParamPOs(ctx, parentTable, parentId, parameterTable, trxName); for (final IParameterPO paramPO : paramPOs) { final String name = paramPO.getName(); final String displayName = paramPO.getDisplayName(); final String description = paramPO.getDescription(); final int displayType = paramPO.getAD_Reference_ID(); final int seqNo = paramPO.getSeqNo(); final Parameter param = new Parameter(name, displayName, description, displayType, seqNo); final String paramValue = paramPO.getParamValue(); param.setValue(mkParamValueObj(paramValue, displayType)); result.add(param); } return result; } private Object mkParamValueObj(final String valueStr, final int displayType) { final Object result; if (displayType == DisplayType.String) { result = valueStr; } else if (displayType == DisplayType.Integer) { result = Integer.parseInt(valueStr); } else if (displayType == DisplayType.Number) { result = new BigDecimal(valueStr); } else if (displayType == DisplayType.YesNo) { result = "Y".equals(valueStr); } else {
throw new IllegalArgumentException("Illegal displayType " + displayType); } return result; } private String mkParamValueStr(final Object valueObj, final int displayType) { final String result; if (displayType == DisplayType.String) { result = (String)valueObj; } else if (displayType == DisplayType.Integer) { result = Integer.toString((Integer)valueObj); } else if (displayType == DisplayType.Number) { result = ((BigDecimal)valueObj).toString(); } else if (displayType == DisplayType.YesNo) { result = ((Boolean)valueObj) ? "Y" : "N"; } else { throw new IllegalArgumentException("Illegal displayType " + displayType); } return result; } @Override public void deleteParameters(final Object parent, final String parameterTable) { for (final IParameterPO paramPO : Services.get(IParametersDAO.class).retrieveParamPOs(parent, parameterTable)) { InterfaceWrapperHelper.delete(paramPO); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\ParameterBL.java
2
请完成以下Java代码
static Handler.Wrapper createGzipHandlerWrapper(Compression compression) { CompressionHandler compressionHandler = new CompressionHandler(); GzipCompression gzip = new GzipCompression(); gzip.setMinCompressSize((int) compression.getMinResponseSize().toBytes()); compressionHandler.putCompression(gzip); Builder configBuilder = CompressionConfig.builder(); for (String mimeType : compression.getMimeTypes()) { configBuilder.compressIncludeMimeType(mimeType); } for (HttpMethod httpMethod : HttpMethod.values()) { configBuilder.compressIncludeMethod(httpMethod.name()); } compressionHandler.putConfiguration(PathSpec.from("/"), configBuilder.build()); return compressionHandler; } static Handler.Wrapper createServerHeaderHandlerWrapper(String header) { return new ServerHeaderHandler(header); } /** * {@link Handler.Wrapper} to add a custom {@code server} header. */ private static class ServerHeaderHandler extends Handler.Wrapper { private static final String SERVER_HEADER = "server";
private final String value; ServerHeaderHandler(String value) { this.value = value; } @Override public boolean handle(Request request, Response response, Callback callback) throws Exception { Mutable headers = response.getHeaders(); if (!headers.contains(SERVER_HEADER)) { headers.add(SERVER_HEADER, this.value); } return super.handle(request, response, callback); } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\JettyHandlerWrappers.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloWorldController { @RequestMapping("/hello") @RateLimiter(name="ratelimitApi",fallbackMethod = "fallback") public ResponseEntity<String> showHelloWorld(){ return new ResponseEntity<>("success",HttpStatus.OK); } public ResponseEntity fallback(Throwable e){ log.error("fallback exception , {}",e.getMessage()); return new ResponseEntity<>("your request is too fast,please low down", HttpStatus.OK); } int i=0; @RequestMapping("/retry") @Retry(name = "backendA")//use backendA ,if throw IOException ,it will be retried 3 times。 public ResponseEntity<String> retry(String name){ if(name.equals("test")){
i++; log.info("retry time:{}",i); throw new HttpServerErrorException(HttpStatusCode.valueOf(101)); } return new ResponseEntity<>("retry",HttpStatus.OK); } @RequestMapping("/bulkhead") @Bulkhead(name = "backendA") public ResponseEntity<String> bulkhead(){ return new ResponseEntity<>("bulkhead",HttpStatus.OK); } }
repos\springboot-demo-master\resilience4j\src\main\java\com\et\resilience4j\controller\HelloWorldController.java
2
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ReceiveTask.class, BPMN_ELEMENT_RECEIVE_TASK) .namespaceUri(BPMN20_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<ReceiveTask>() { public ReceiveTask newInstance(ModelTypeInstanceContext instanceContext) { return new ReceiveTaskImpl(instanceContext); } }); implementationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION) .defaultValue("##WebService") .build(); instantiateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_INSTANTIATE) .defaultValue(false) .build(); messageRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_MESSAGE_REF) .qNameAttributeReference(Message.class) .build(); operationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OPERATION_REF) .qNameAttributeReference(Operation.class) .build(); typeBuilder.build(); } public ReceiveTaskImpl(ModelTypeInstanceContext context) { super(context); } public ReceiveTaskBuilder builder() {
return new ReceiveTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) { implementationAttribute.setValue(this, implementation); } public boolean instantiate() { return instantiateAttribute.getValue(this); } public void setInstantiate(boolean instantiate) { instantiateAttribute.setValue(this, instantiate); } public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ReceiveTaskImpl.java
1
请完成以下Java代码
public byte[] addInterface() { addInterfaceAdapter = new AddInterfaceAdapter(writer); reader.accept(addInterfaceAdapter, 0); return writer.toByteArray(); } public class AddInterfaceAdapter extends ClassVisitor { public AddInterfaceAdapter(ClassVisitor cv) { super(ASM4, cv); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { String[] holding = new String[interfaces.length + 1]; holding[holding.length - 1] = CLONEABLE; System.arraycopy(interfaces, 0, holding, 0, interfaces.length); cv.visit(V1_5, access, name, signature, superName, holding); } } public class PublicizeMethodAdapter extends ClassVisitor { final Logger logger = Logger.getLogger("PublicizeMethodAdapter"); TraceClassVisitor tracer; PrintWriter pw = new PrintWriter(System.out); public PublicizeMethodAdapter(ClassVisitor cv) { super(ASM4, cv); this.cv = cv; tracer = new TraceClassVisitor(cv, pw); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (name.equals("toUnsignedString0")) { logger.info("Visiting unsigned method"); return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions); } return tracer.visitMethod(access, name, desc, signature, exceptions); } public void visitEnd() {
tracer.visitEnd(); System.out.println(tracer.p.getText()); } } public class AddFieldAdapter extends ClassVisitor { String fieldName; int access; boolean isFieldPresent; public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) { super(ASM4, cv); this.cv = cv; this.access = access; this.fieldName = fieldName; } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (name.equals(fieldName)) { isFieldPresent = true; } return cv.visitField(access, name, desc, signature, value); } @Override public void visitEnd() { if (!isFieldPresent) { FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null); if (fv != null) { fv.visitEnd(); } } cv.visitEnd(); } } }
repos\tutorials-master\libraries-bytecode\src\main\java\com\baeldung\asm\CustomClassWriter.java
1
请在Spring Boot框架中完成以下Java代码
ReactiveTenantExtension tenantExtension() { return ReactiveTenantExtension.INSTANCE; } /** * Extension that looks up a {@link Tenant} from the {@link reactor.util.context.Context}. */ enum ReactiveTenantExtension implements ReactiveEvaluationContextExtension { INSTANCE; @Override public Mono<? extends EvaluationContextExtension> getExtension() { return Mono.deferContextual(contextView -> Mono.just(new TenantExtension(contextView.get(Tenant.class)))); } @Override public String getExtensionId() { return "my-reactive-tenant-extension"; } } /** * Actual extension providing access to the {@link Tenant} value object. */ @RequiredArgsConstructor static class TenantExtension implements EvaluationContextExtension { private final Tenant tenant;
@Override public String getExtensionId() { return "my-tenant-extension"; } @Override public Tenant getRootObject() { return tenant; } } /** * The root object. */ @Value public static class Tenant { String tenantId; } }
repos\spring-data-examples-main\cassandra\reactive\src\main\java\example\springdata\cassandra\spel\ApplicationConfiguration.java
2
请完成以下Java代码
public HistoricIncidentQuery orderByConfiguration() { orderBy(HistoricIncidentQueryProperty.CONFIGURATION); return this; } public HistoricIncidentQuery orderByHistoryConfiguration() { orderBy(HistoricIncidentQueryProperty.HISTORY_CONFIGURATION); return this; } public HistoricIncidentQuery orderByIncidentState() { orderBy(HistoricIncidentQueryProperty.INCIDENT_STATE); return this; } public HistoricIncidentQuery orderByTenantId() { return orderBy(HistoricIncidentQueryProperty.TENANT_ID); } // results //////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricIncidentManager() .findHistoricIncidentCountByQueryCriteria(this); } public List<HistoricIncident> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIncidentManager() .findHistoricIncidentByQueryCriteria(this, page); } // getters ///////////////////////////////////////////////////// public String getId() { return id; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getExecutionId() { return executionId; } public String getActivityId() { return activityId; } public String getFailedActivityId() { return failedActivityId; }
public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } public String getCauseIncidentId() { return causeIncidentId; } public String getRootCauseIncidentId() { return rootCauseIncidentId; } public String getConfiguration() { return configuration; } public String getHistoryConfiguration() { return historyConfiguration; } public IncidentState getIncidentState() { return incidentState; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIncidentQueryImpl.java
1
请完成以下Java代码
private static List<LiquibaseDataType> getDataTypes() { return List.of( new BooleanType(), new TinyIntType(), new IntType(), new MediumIntType(), new BigIntType(), new FloatType(), new DoubleType(), new DecimalType(), new NumberType(), new BlobType(), new DateTimeType(), new TimeType(), new TimestampType(), new DateType(), new CharType(), new VarcharType(), new NCharType(), new NVarcharType(), new ClobType(), new CurrencyType(), new UUIDType()); }
private static List<AbstractJdbcDatabase> getDatabases() { return List.of( new MySQLDatabase(), new SQLiteDatabase(), new H2Database(), new PostgresDatabase(), new DB2Database(), new MSSQLDatabase(), new OracleDatabase(), new HsqlDatabase(), new FirebirdDatabase(), new DerbyDatabase(), new InformixDatabase(), new SybaseDatabase(), new SybaseASADatabase()); } }
repos\tutorials-master\persistence-modules\liquibase\src\main\java\com\baeldung\liquibase\utility\LiquibaseDatatypes.java
1
请在Spring Boot框架中完成以下Java代码
public class ProgramPayResultVo implements Serializable { private static final long serialVersionUID = 651601163997960632L; /** * 交易状态 */ private String status; /** * 支付信息 */ private String payMessage; /** * 银行返回信息 */ private String bankReturnMsg; /** * 签名结果 */ private String sign; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPayMessage() { return payMessage; } public void setPayMessage(String payMessage) { this.payMessage = payMessage; }
public String getBankReturnMsg() { return bankReturnMsg; } public void setBankReturnMsg(String bankReturnMsg) { this.bankReturnMsg = bankReturnMsg; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\ProgramPayResultVo.java
2
请完成以下Java代码
private Map<CacheKey, DataEntryRecord> loadRecords(final Collection<CacheKey> keys) { final DataEntryRecordQuery query = toDataEntryRecordQuery(keys); final List<DataEntryRecord> records = recordsRepo.stream(query) .map(DataEntryRecord::copyAsImmutable) .collect(ImmutableList.toImmutableList()); if (records.isEmpty()) { return ImmutableMap.of(); } final Map<CacheKey, DataEntryRecord> recordsMap = Maps.uniqueIndex( records, record -> CollectionUtils.singleElement(cacheIndex.extractCacheKeys(record))); return recordsMap; } private static DataEntryRecordQuery toDataEntryRecordQuery(final Collection<CacheKey> keys) { final int mainRecordId = CollectionUtils.extractSingleElement(keys, CacheKey::getMainRecordId); final ImmutableSet<DataEntrySubTabId> subTabIds = extractSubTabIds(keys); return DataEntryRecordQuery.builder() .dataEntrySubTabIds(subTabIds) .recordId(mainRecordId) .build(); } private static ImmutableSet<DataEntrySubTabId> extractSubTabIds(final Collection<CacheKey> keys) { final ImmutableSet<DataEntrySubTabId> subTabIds = keys.stream() .map(CacheKey::getSubTabId) .collect(ImmutableSet.toImmutableSet()); return subTabIds; } @VisibleForTesting int getDataEntryRecordIdIndexSize() { return cacheIndex.size(); } @Value(staticConstructor = "of") private static final class CacheKey {
int mainRecordId; DataEntrySubTabId subTabId; } @ToString @VisibleForTesting static final class DataEntryRecordIdIndex implements CacheIndexDataAdapter<DataEntryRecordId, CacheKey, DataEntryRecord> { @Override public DataEntryRecordId extractDataItemId(final DataEntryRecord dataItem) { return dataItem.getId().get(); } @Override public ImmutableSet<TableRecordReference> extractRecordRefs(final DataEntryRecord dataItem) { final DataEntryRecordId id = dataItem.getId().orElse(null); return id != null ? ImmutableSet.of(TableRecordReference.of(I_DataEntry_Record.Table_Name, id)) : ImmutableSet.of(); } @Override public List<CacheKey> extractCacheKeys(final DataEntryRecord dataItem) { final CacheKey singleCacheKey = CacheKey.of(dataItem.getMainRecord().getRecord_ID(), dataItem.getDataEntrySubTabId()); return ImmutableList.of(singleCacheKey); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRecordCache.java
1
请在Spring Boot框架中完成以下Java代码
private SecurityContext getContextByPath(String pathRegex) { return SecurityContext.builder() .securityReferences(defaultAuth()) .operationSelector(oc -> oc.requestMappingPattern().matches(pathRegex)) .build(); } private List<SecurityReference> defaultAuth() { List<SecurityReference> result = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; result.add(new SecurityReference("Authorization", authorizationScopes)); return result; } public BeanPostProcessor generateBeanPostProcessor(){ return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean)); } return bean; }
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { List<T> copy = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(copy); } @SuppressWarnings("unchecked") private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) { try { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); field.setAccessible(true); return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } }; } /** * 自定义Swagger配置 */ public abstract SwaggerProperties swaggerProperties(); }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\config\BaseSwaggerConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class MultipleRecipe { @Id @Column(name = "id") private Long id; @Column(name = "cocktail") private String cocktail; @Column(name = "instructions") private String instructions; @Column(name = "base_ingredient") private String baseIngredient; public MultipleRecipe() { } public MultipleRecipe(Long id, String cocktail, String instructions, String baseIngredient) { this.id = id; this.cocktail = cocktail; this.instructions = instructions; this.baseIngredient = baseIngredient; } public Long getId() { return id; } public String getCocktail() { return cocktail; } public String getInstructions() { return instructions; } public String getBaseIngredient() { return baseIngredient;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultipleRecipe that = (MultipleRecipe) o; return Objects.equals(id, that.id) && Objects.equals(cocktail, that.cocktail) && Objects.equals(instructions, that.instructions) && Objects.equals(baseIngredient, that.baseIngredient); } @Override public int hashCode() { return Objects.hash(id, cocktail, instructions, baseIngredient); } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\unrelated\entities\MultipleRecipe.java
2
请在Spring Boot框架中完成以下Java代码
public SessionAttributesProperties getAttributes() { return this.attributes; } public SessionExpirationProperties getExpiration() { return this.expiration; } public SessionRegionProperties getRegion() { return this.region; } public SessionSerializerProperties getSerializer() { return this.serializer; } } public static class SessionAttributesProperties { private String[] indexable; public String[] getIndexable() { return this.indexable; } public void setIndexable(String[] indexable) { this.indexable = indexable; } } public static class SessionExpirationProperties { private int maxInactiveIntervalSeconds; public int getMaxInactiveIntervalSeconds() { return this.maxInactiveIntervalSeconds; } public void setMaxInactiveIntervalSeconds(int maxInactiveIntervalSeconds) { this.maxInactiveIntervalSeconds = maxInactiveIntervalSeconds; } public void setMaxInactiveInterval(Duration duration) {
int maxInactiveIntervalInSeconds = duration != null ? Long.valueOf(duration.toSeconds()).intValue() : GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS; setMaxInactiveIntervalSeconds(maxInactiveIntervalInSeconds); } } public static class SessionRegionProperties { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } public static class SessionSerializerProperties { private String beanName; public String getBeanName() { return this.beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\SpringSessionProperties.java
2
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } final PlainContextAware other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .appendByRef(ctx, other.ctx) .append(trxName, other.trxName) .isEqual(); } @Override
public Properties getCtx() { return ctx; } @Override public String getTrxName() { return trxName; } @Override public boolean isAllowThreadInherited() { return allowThreadInherited; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\PlainContextAware.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID) { if (C_CostClassification_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID); } @Override public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description);
} @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CostClassification_Category.java
1
请完成以下Java代码
public class ADRAttributeGenerator extends AbstractAttributeValueGenerator { @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_List; } /** * @return <code>false</code>, because ADR is a List attribute. */ @Override public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return false; } /** * Creates an ADR attribute value for the C_BPartner which is specified by <code>tableId</code> and <code>recordId</code>. */ @Override public AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName) { final IContextAware context = new PlainContextAware(ctx, trxName); final ITableRecordReference record = TableRecordReference.of(tableId, recordId); final I_C_BPartner partner = record.getModel(context, I_C_BPartner.class); Check.assumeNotNull(partner, "partner not null"); final I_M_Attribute adrAttribute = Services.get(IADRAttributeDAO.class).retrieveADRAttribute(partner); if (adrAttribute == null) { // ADR Attribute was not configured, nothing to do return null; }
final String adrRegionValue = Services.get(IADRAttributeBL.class).getADRForBPartner(partner, isSOTrx); if (Check.isEmpty(adrRegionValue, true)) { return null; } // // Fetched AD_Ref_List record final ADRefListItem adRefList = ADReferenceService.get().retrieveListItemOrNull(I_C_BPartner.ADRZertifizierung_L_AD_Reference_ID, adrRegionValue); Check.assumeNotNull(adRefList, "adRefList not null"); final String adrRegionName = adRefList.getName().getDefaultValue(); return Services.get(IAttributeDAO.class).createAttributeValue(AttributeListValueCreateRequest.builder() .attributeId(AttributeId.ofRepoId(adrAttribute.getM_Attribute_ID())) .value(adrRegionValue) .name(adrRegionName) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\spi\impl\ADRAttributeGenerator.java
1
请完成以下Java代码
public CleanableHistoricBatchReport orderByFinishedBatchOperation() { orderBy(CleanableHistoricInstanceReportProperty.FINISHED_AMOUNT); return this; } @Override public long executeCount(CommandContext commandContext) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); checkPermissions(commandContext); Map<String, Integer> batchOperationsForHistoryCleanup = commandContext.getProcessEngineConfiguration().getParsedBatchOperationsForHistoryCleanup(); if (isHistoryCleanupStrategyRemovalTimeBased()) { addBatchOperationsWithoutTTL(batchOperationsForHistoryCleanup); } return commandContext.getHistoricBatchManager().findCleanableHistoricBatchesReportCountByCriteria(this, batchOperationsForHistoryCleanup); } @Override public List<CleanableHistoricBatchReportResult> executeList(CommandContext commandContext, Page page) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); checkPermissions(commandContext); Map<String, Integer> batchOperationsForHistoryCleanup = commandContext.getProcessEngineConfiguration().getParsedBatchOperationsForHistoryCleanup(); if (isHistoryCleanupStrategyRemovalTimeBased()) { addBatchOperationsWithoutTTL(batchOperationsForHistoryCleanup); } return commandContext.getHistoricBatchManager().findCleanableHistoricBatchesReportByCriteria(this, page, batchOperationsForHistoryCleanup); } protected void addBatchOperationsWithoutTTL(Map<String, Integer> batchOperations) { Map<String, BatchJobHandler<?>> batchJobHandlers = Context.getProcessEngineConfiguration().getBatchHandlers(); Set<String> batchOperationKeys = null; if (batchJobHandlers != null) { batchOperationKeys = batchJobHandlers.keySet(); }
if (batchOperationKeys != null) { for (String batchOperation : batchOperationKeys) { Integer ttl = batchOperations.get(batchOperation); batchOperations.put(batchOperation, ttl); } } } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } private void checkPermissions(CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadHistoricBatch(); } } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricBatchReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getBPartnerQtyItemCapacity() { return bPartnerQtyItemCapacity; } /** * Sets the value of the bPartnerQtyItemCapacity property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setBPartnerQtyItemCapacity(BigDecimal value) { this.bPartnerQtyItemCapacity = value; } /** * Gets the value of the upctu property. * * @return * possible object is * {@link String }
* */ public String getUPCTU() { return upctu; } /** * Sets the value of the upctu property. * * @param value * allowed object is * {@link String } * */ public void setUPCTU(String value) { this.upctu = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvLineType.java
2
请完成以下Java代码
public void setFirstname (final @Nullable java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return get_ValueAsString(COLUMNNAME_Firstname); } @Override public void setIsDefaultContact (final boolean IsDefaultContact) { set_Value (COLUMNNAME_IsDefaultContact, IsDefaultContact); } @Override public boolean isDefaultContact() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultContact); } /** * IsInvoiceEmailEnabled AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISINVOICEEMAILENABLED_AD_Reference_ID=319; /** Yes = Y */ public static final String ISINVOICEEMAILENABLED_Yes = "Y"; /** No = N */ public static final String ISINVOICEEMAILENABLED_No = "N"; @Override public void setIsInvoiceEmailEnabled (final @Nullable java.lang.String IsInvoiceEmailEnabled) { set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled); } @Override public java.lang.String getIsInvoiceEmailEnabled() { return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled); } @Override public void setIsMembershipContact (final boolean IsMembershipContact) { set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact); } @Override public boolean isMembershipContact() { return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact); } @Override public void setIsNewsletter (final boolean IsNewsletter) { set_Value (COLUMNNAME_IsNewsletter, IsNewsletter); } @Override public boolean isNewsletter() { return get_ValueAsBoolean(COLUMNNAME_IsNewsletter); } @Override public void setLastname (final @Nullable java.lang.String Lastname)
{ set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); } @Override 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 setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
1
请完成以下Java代码
public boolean isRunning() { return running.get(); } /** * Padding buffer in the thread pool */ public void asyncPadding() { bufferPadExecutors.submit(this::paddingBuffer); } /** * Padding buffer fill the slots until to catch the cursor */ public void paddingBuffer() { LOGGER.info("Ready to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); // is still running if (!running.compareAndSet(false, true)) { LOGGER.info("Padding buffer is still running. {}", ringBuffer); return; } // fill the rest slots until to catch the cursor boolean isFullRingBuffer = false; while (!isFullRingBuffer) { List<Long> uidList = uidProvider.provide(lastSecond.incrementAndGet()); for (Long uid : uidList) { isFullRingBuffer = !ringBuffer.put(uid); if (isFullRingBuffer) { break; } }
} // not running now running.compareAndSet(true, false); LOGGER.info("End to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); } /** * Setters */ public void setScheduleInterval(long scheduleInterval) { Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!"); this.scheduleInterval = scheduleInterval; } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\buffer\BufferPaddingExecutor.java
1
请完成以下Java代码
public int getAD_BusinessRule_Trigger_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID); } @Override public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setLevel (final java.lang.String Level) { set_ValueNoCheck (COLUMNNAME_Level, Level); } @Override public java.lang.String getLevel() { return get_ValueAsString(COLUMNNAME_Level); } @Override public void setModule (final @Nullable java.lang.String Module) { set_Value (COLUMNNAME_Module, Module); } @Override public java.lang.String getModule() { return get_ValueAsString(COLUMNNAME_Module); } @Override public void setMsgText (final @Nullable java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setSource_Record_ID (final int Source_Record_ID) { if (Source_Record_ID < 1) set_Value (COLUMNNAME_Source_Record_ID, null); else set_Value (COLUMNNAME_Source_Record_ID, Source_Record_ID); } @Override public int getSource_Record_ID() { return get_ValueAsInt(COLUMNNAME_Source_Record_ID); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID); } @Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTarget_Record_ID (final int Target_Record_ID) { if (Target_Record_ID < 1) set_Value (COLUMNNAME_Target_Record_ID, null); else set_Value (COLUMNNAME_Target_Record_ID, Target_Record_ID); } @Override public int getTarget_Record_ID() { return get_ValueAsInt(COLUMNNAME_Target_Record_ID); } @Override public void setTarget_Table_ID (final int Target_Table_ID) { if (Target_Table_ID < 1) set_Value (COLUMNNAME_Target_Table_ID, null); else set_Value (COLUMNNAME_Target_Table_ID, Target_Table_ID); } @Override public int getTarget_Table_ID() { return get_ValueAsInt(COLUMNNAME_Target_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Log.java
1
请在Spring Boot框架中完成以下Java代码
public class FooNameHelper { public static Foo concatAndSubstringFooName(Foo foo) { Foo concat = concatFooName(foo); return substringFooName(concat); } public static Foo concatFooName(Foo foo) { int random = ThreadLocalRandom.current() .nextInt(0, 80); String processedName = (random != 0) ? foo.getFormattedName() : foo.getFormattedName() + "-bael"; foo.setFormattedName(processedName); return foo; }
public static Foo substringFooName(Foo foo) { int random = ThreadLocalRandom.current() .nextInt(0, 100); String processedName = (random == 0) ? foo.getFormattedName().substring(10, 15) : foo.getFormattedName().substring(0, 5); foo.setFormattedName(processedName); return foo; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\debugging\consumer\service\FooNameHelper.java
2
请完成以下Java代码
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getAddress() {
return address; } public void setAddress(String address) { this.address = address; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\entity\Order.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public double getPrice() { return price; } public void setPrice(double price) {
this.price = price; } public double getDiscounted() { return discounted; } @PostLoad private void postLoad() { this.discounted = this.price - this.price * 0.25; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + ", discounted=" + discounted + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCalculatePropertyPostLoad\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public void setIsAddressLinesLocalReverse (boolean IsAddressLinesLocalReverse) { set_Value (COLUMNNAME_IsAddressLinesLocalReverse, Boolean.valueOf(IsAddressLinesLocalReverse)); } /** Get Reverse Local Address Lines. @return Print Local Address in reverse Order */ @Override public boolean isAddressLinesLocalReverse () { Object oo = get_Value(COLUMNNAME_IsAddressLinesLocalReverse); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reverse Address Lines. @param IsAddressLinesReverse Print Address in reverse Order */ @Override public void setIsAddressLinesReverse (boolean IsAddressLinesReverse) { set_Value (COLUMNNAME_IsAddressLinesReverse, Boolean.valueOf(IsAddressLinesReverse)); } /** Get Reverse Address Lines. @return Print Address in reverse Order */ @Override public boolean isAddressLinesReverse () { Object oo = get_Value(COLUMNNAME_IsAddressLinesReverse); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Media Size. @param MediaSize Java Media Size */ @Override public void setMediaSize (java.lang.String MediaSize) { set_Value (COLUMNNAME_MediaSize, MediaSize); } /** Get Media Size. @return Java Media Size
*/ @Override public java.lang.String getMediaSize () { return (java.lang.String)get_Value(COLUMNNAME_MediaSize); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Region. @param RegionName Name of the Region */ @Override public void setRegionName (java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } /** Get Region. @return Name of the Region */ @Override public java.lang.String getRegionName () { return (java.lang.String)get_Value(COLUMNNAME_RegionName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country.java
1
请完成以下Java代码
public void setInstrId(String value) { this.instrId = value; } /** * Gets the value of the endToEndId property. * * @return * possible object is * {@link String } * */ public String getEndToEndId() { return endToEndId; } /** * Sets the value of the endToEndId property. * * @param value * allowed object is * {@link String } * */ public void setEndToEndId(String value) { this.endToEndId = value; } /** * Gets the value of the txId property. * * @return * possible object is * {@link String } * */ public String getTxId() { return txId; } /** * Sets the value of the txId property. * * @param value * allowed object is * {@link String } * */ public void setTxId(String value) { this.txId = value; } /** * Gets the value of the mndtId property. * * @return * possible object is * {@link String } * */ public String getMndtId() { return mndtId; } /** * Sets the value of the mndtId property. * * @param value * allowed object is * {@link String } * */ public void setMndtId(String value) { this.mndtId = value; } /** * Gets the value of the chqNb property. * * @return * possible object is * {@link String } * */ public String getChqNb() { return chqNb; } /** * Sets the value of the chqNb property. * * @param value * allowed object is * {@link String } * */ public void setChqNb(String value) { this.chqNb = value; } /**
* Gets the value of the clrSysRef property. * * @return * possible object is * {@link String } * */ public String getClrSysRef() { return clrSysRef; } /** * Sets the value of the clrSysRef property. * * @param value * allowed object is * {@link String } * */ public void setClrSysRef(String value) { this.clrSysRef = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link ProprietaryReference1 } * */ public ProprietaryReference1 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryReference1 } * */ public void setPrtry(ProprietaryReference1 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionReferences2.java
1
请完成以下Java代码
public class POJOLookupMapRestorePoint { private final POJOLookupMap db; private final Map<String, Map<Integer, Object>> cachedObjects; private final Map<PInstanceId, ImmutableSet<Integer>> selectionId2selection; POJOLookupMapRestorePoint(final POJOLookupMap db) { super(); this.db = db; this.cachedObjects = copyCachedObjects(db.cachedObjects); this.selectionId2selection = copySelection(db.selectionId2selection); } private static final Map<String, Map<Integer, Object>> copyCachedObjects(Map<String, Map<Integer, Object>> cachedObjects) { final Map<String, Map<Integer, Object>> cachedObjectsCopy = new HashMap<>(cachedObjects); for (Map.Entry<String, Map<Integer, Object>> e : cachedObjectsCopy.entrySet()) { final Map<Integer, Object> value = e.getValue(); e.setValue(value == null ? null : new HashMap<>(value)); } return cachedObjectsCopy; }
private static final Map<PInstanceId, ImmutableSet<Integer>> copySelection(final Map<PInstanceId, ImmutableSet<Integer>> selectionId2selection) { return new HashMap<>(selectionId2selection); } /** * Restore the database as it was when this restore point was created. */ public void restore() { this.db.cachedObjects = copyCachedObjects(this.cachedObjects); this.db.selectionId2selection = copySelection(this.selectionId2selection); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOLookupMapRestorePoint.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsShowInMainMenu (final boolean IsShowInMainMenu) { set_Value (COLUMNNAME_IsShowInMainMenu, IsShowInMainMenu); } @Override public boolean isShowInMainMenu() { return get_ValueAsBoolean(COLUMNNAME_IsShowInMainMenu); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); } @Override public int getMobile_Application_ID()
{ return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application.java
1
请完成以下Java代码
public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abschreiben. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) {
set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Abschreiben. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java
1
请完成以下Java代码
public static boolean resourceIsContainedInArray(Integer resourceTypeId, Resource[] resources) { for (Resource resource : resources) { if (resourceTypeId == resource.resourceType()) { return true; } } return false; } /** * @return See {@link ResourceTypeUtil#PERMISSION_ENUMS} */ public static Map<Integer, Class<? extends Enum<? extends Permission>>> getPermissionEnums() { return PERMISSION_ENUMS; } /** * Retrieves the {@link Permission} array based on the predifined {@link ResourceTypeUtil#PERMISSION_ENUMS PERMISSION_ENUMS} */ public static Permission[] getPermissionsByResourceType(int givenResourceType) { Class<? extends Enum<? extends Permission>> clazz = PERMISSION_ENUMS.get(givenResourceType); if (clazz == null) { return Permissions.values(); } return ((Permission[]) clazz.getEnumConstants()); } /** * Currently used only in the Rest API * Returns a {@link Permission} based on the specified <code>permissionName</code> and <code>resourceType</code>
* @throws BadUserRequestException in case the permission is not valid for the specified resource type */ public static Permission getPermissionByNameAndResourceType(String permissionName, int resourceType) { for (Permission permission : getPermissionsByResourceType(resourceType)) { if (permission.getName().equals(permissionName)) { return permission; } } throw new BadUserRequestException( String.format("The permission '%s' is not valid for '%s' resource type.", permissionName, getResourceByType(resourceType)) ); } /** * Iterates over the {@link Resources} and * returns either the resource with specified <code>resourceType</code> or <code>null</code>. */ public static Resource getResourceByType(int resourceType) { for (Resource resource : Resources.values()) { if (resource.resourceType() == resourceType) { return resource; } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ResourceTypeUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class CandidateDeploymentImpl implements CandidateDeployment { protected String name; protected Map<String, Resource> resources; public CandidateDeploymentImpl(String name, Map<String, Resource> resources) { this.name = name; this.resources = resources; } @Override public String getName() { return name; } public void setName(String name) { this.name = name;
} @Override public Map<String, Resource> getResources() { return resources; } public void setResources(Map<String, Resource> resources) { this.resources = resources; } public static CandidateDeploymentImpl fromDeploymentEntity(DeploymentEntity deploymentEntity) { // first cast ResourceEntity map to Resource Map<String, Resource> resources = new HashMap<>((Map<String, ? extends Resource>) deploymentEntity.getResources()); return new CandidateDeploymentImpl(deploymentEntity.getName(), resources); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\CandidateDeploymentImpl.java
2
请完成以下Java代码
public class ProductsToPick_PickAndPackSelected extends ProductsToPickViewBasedProcess { private final ProductsToPickRowsService rowsService = SpringContextHolder.instance.getBean(ProductsToPickRowsService.class); private final AdMessageKey MSG_SET_DEFAULT_PACKING_INSTRUCTION = AdMessageKey.of("de.metas.ui.web.pickingV2.productsToPick.process.ProductsToPick_PickAndPackSelected.SetDefaultPackingInstruction"); private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isPickerProfile()) { return ProcessPreconditionsResolution.rejectWithInternalReason("only picker shall pick"); } if (rowsService.noRowsEligibleForPicking(getValidRowsForPickAndPack())) { return ProcessPreconditionsResolution.rejectWithInternalReason("select only rows that can be picked"); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { ensureDefaultPackingInstructionExists(); pick(); pack(); invalidateView(); return MSG_OK; } private void pick() {
final ImmutableList<WebuiPickHUResult> result = rowsService.pick(getValidRowsForPickAndPack()); updateViewRowFromPickingCandidate(result); } private void pack() { final ImmutableList<WebuiPickHUResult> result = rowsService.setPackingInstruction(getValidRowsForPickAndPack(), getPackToSpec()); updateViewRowFromPickingCandidate(result); } private List<ProductsToPickRow> getValidRowsForPickAndPack() { return getSelectedRows() .stream() .filter(row -> !row.getQtyEffective().isZero()) .collect(ImmutableList.toImmutableList()); } @NonNull private PackToSpec getPackToSpec() { final I_M_HU_PI defaultPIForPicking = handlingUnitsDAO.retrievePIDefaultForPicking(); if (defaultPIForPicking == null) { throw new AdempiereException(MSG_SET_DEFAULT_PACKING_INSTRUCTION); } return PackToSpec.ofGenericPackingInstructionsId(HuPackingInstructionsId.ofRepoId(defaultPIForPicking.getM_HU_PI_ID())); } private void ensureDefaultPackingInstructionExists() { getPackToSpec(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_PickAndPackSelected.java
1
请在Spring Boot框架中完成以下Java代码
public class TitleRepository { private static final Map<TitleRepository.CacheKey, Title> cache = new HashMap<>(); @Value private static class CacheKey { TitleId titleId; Language language; } public Title getByIdAndLang(@NonNull final TitleId id, @Nullable final Language language) { final I_C_Title titleRecord = loadOutOfTrx(id, I_C_Title.class); final I_C_Title titleTrlRecord; if (language == null)
{ titleTrlRecord = translate(titleRecord, I_C_Title.class); } else { titleTrlRecord = translate(titleRecord, I_C_Title.class, language.getAD_Language()); } return Title.builder() .id(id) .language(language) .title(titleTrlRecord.getName()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\title\TitleRepository.java
2
请完成以下Java代码
protected String doIt() { if (!I_AD_User.Table_Name.equals(getTableName())) { throw new AdempiereException("Call it from User window"); } // // Get the AD_User_ID and make sure it's the currently logged on. final Properties ctx = getCtx(); // logged in context final UserId adUserId = UserId.ofRepoId(getRecord_ID()); final UserId loggedUserId = Env.getLoggedUserId(ctx); if (!UserId.equals(adUserId, loggedUserId)) { throw new AdempiereException("Changing password for other user is not allowed"); }
// // Actually change it's password usersService.changePassword(ChangeUserPasswordRequest.builder() .userId(adUserId) .oldPassword(HashableString.ofPlainValue(oldPassword)) .newPassword(newPassword) .newPasswordRetype(newPasswordRetype) // .contextClientId(Env.getClientId(ctx)) .contextUserId(loggedUserId) .contextDate(Env.getLocalDate(ctx)) // .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_ChangeMyPassword.java
1
请完成以下Java代码
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); } private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties(); return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\HibernateUtil.java
1
请完成以下Java代码
public void setDatabaseType(String databaseType) { this.databaseType = databaseType; this.statementMappings = databaseSpecificStatements.get(databaseType); } // getters and setters ////////////////////////////////////////////////////// public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public String getDatabaseType() { return databaseType; } public Map<String, String> getStatementMappings() { return statementMappings; } public void setStatementMappings(Map<String, String> statementMappings) { this.statementMappings = statementMappings; } public Map<Class< ? >, String> getInsertStatements() { return insertStatements; } public void setInsertStatements(Map<Class< ? >, String> insertStatements) { this.insertStatements = insertStatements; } public Map<Class< ? >, String> getUpdateStatements() { return updateStatements; } public void setUpdateStatements(Map<Class< ? >, String> updateStatements) { this.updateStatements = updateStatements; } public Map<Class< ? >, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class< ? >, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class< ? >, String> selectStatements) { this.selectStatements = selectStatements;
} public boolean isDbIdentityUsed() { return isDbIdentityUsed; } public void setDbIdentityUsed(boolean isDbIdentityUsed) { this.isDbIdentityUsed = isDbIdentityUsed; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public boolean isCmmnEnabled() { return cmmnEnabled; } public void setCmmnEnabled(boolean cmmnEnabled) { this.cmmnEnabled = cmmnEnabled; } public boolean isDmnEnabled() { return dmnEnabled; } public void setDmnEnabled(boolean dmnEnabled) { this.dmnEnabled = dmnEnabled; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java
1
请完成以下Spring Boot application配置
server: port: 8079 spring: data: # MongoDB 配置项,对应 MongoProperties 类 mongodb: host: 127.0.0.1 port: 27017 database: yourdatabase
username: test01 password: password01 # 上述属性,也可以只配置 uri
repos\SpringBoot-Labs-master\lab-39\lab-39-mongodb\src\main\resources\application.yml
2
请完成以下Java代码
public void setM_HU_Attribute(final de.metas.handlingunits.model.I_M_HU_Attribute M_HU_Attribute) { set_ValueFromPO(COLUMNNAME_M_HU_Attribute_ID, de.metas.handlingunits.model.I_M_HU_Attribute.class, M_HU_Attribute); } @Override public void setM_HU_Attribute_ID (final int M_HU_Attribute_ID) { if (M_HU_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Attribute_ID, M_HU_Attribute_ID); } @Override public int getM_HU_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Attribute_ID); } @Override public de.metas.handlingunits.model.I_M_HU getM_HU() { return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Storage getM_HU_Storage() { return get_ValueAsPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class); } @Override public void setM_HU_Storage(final de.metas.handlingunits.model.I_M_HU_Storage M_HU_Storage) { set_ValueFromPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class, M_HU_Storage); } @Override public void setM_HU_Storage_ID (final int M_HU_Storage_ID) { if (M_HU_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID); } @Override public int getM_HU_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Stock_Detail_V.java
1
请完成以下Java代码
private long getNextSecond(long lastTimestamp) { long timestamp = getCurrentSecond(); while (timestamp <= lastTimestamp) { timestamp = getCurrentSecond(); } return timestamp; } /** * Get current second */ private long getCurrentSecond() { long currentSecond = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentSecond - epochSeconds > bitsAllocator.getMaxDeltaSeconds()) { throw new UidGenerateException("Timestamp bits is exhausted. Refusing UID generate. Now: " + currentSecond); } return currentSecond; } /** * Setters for spring property */ public void setWorkerIdAssigner(WorkerIdAssigner workerIdAssigner) { this.workerIdAssigner = workerIdAssigner; } public void setTimeBits(int timeBits) { if (timeBits > 0) {
this.timeBits = timeBits; } } public void setWorkerBits(int workerBits) { if (workerBits > 0) { this.workerBits = workerBits; } } public void setSeqBits(int seqBits) { if (seqBits > 0) { this.seqBits = seqBits; } } public void setEpochStr(String epochStr) { if (StringUtils.isNotBlank(epochStr)) { this.epochStr = epochStr; this.epochSeconds = TimeUnit.MILLISECONDS.toSeconds(DateUtils.parseByDayPattern(epochStr).getTime()); } } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\impl\DefaultUidGenerator.java
1
请完成以下Java代码
public OAuth2ClientRegistration convert(Map<String, Object> source) { Map<String, Object> parsedClaims = this.claimTypeConverter.convert(source); Object clientSecretExpiresAt = parsedClaims.get(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT); if (clientSecretExpiresAt instanceof Number && clientSecretExpiresAt.equals(0)) { parsedClaims.remove(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT); } return OAuth2ClientRegistration.withClaims(parsedClaims).build(); } private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) { return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor); } private static Instant convertClientSecretExpiresAt(Object clientSecretExpiresAt) { if (clientSecretExpiresAt != null && String.valueOf(clientSecretExpiresAt).equals("0")) { // 0 indicates that client_secret_expires_at does not expire return null; } return (Instant) INSTANT_CONVERTER.convert(clientSecretExpiresAt); } private static List<String> convertScope(Object scope) { if (scope == null) { return Collections.emptyList(); } return Arrays.asList(StringUtils.delimitedListToStringArray(scope.toString(), " ")); } } private static final class OAuth2ClientRegistrationMapConverter implements Converter<OAuth2ClientRegistration, Map<String, Object>> { @Override public Map<String, Object> convert(OAuth2ClientRegistration source) { Map<String, Object> responseClaims = new LinkedHashMap<>(source.getClaims()); if (source.getClientIdIssuedAt() != null) { responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_ID_ISSUED_AT, source.getClientIdIssuedAt().getEpochSecond());
} if (source.getClientSecret() != null) { long clientSecretExpiresAt = 0; if (source.getClientSecretExpiresAt() != null) { clientSecretExpiresAt = source.getClientSecretExpiresAt().getEpochSecond(); } responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT, clientSecretExpiresAt); } if (!CollectionUtils.isEmpty(source.getScopes())) { responseClaims.put(OAuth2ClientMetadataClaimNames.SCOPE, StringUtils.collectionToDelimitedString(source.getScopes(), " ")); } return responseClaims; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\http\converter\OAuth2ClientRegistrationHttpMessageConverter.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<List<PmsProduct>> recommendProductList(@RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProduct> productList = homeService.recommendProductList(pageSize, pageNum); return CommonResult.success(productList); } @ApiOperation("获取首页商品分类") @RequestMapping(value = "/productCateList/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductCategory>> getProductCateList(@PathVariable Long parentId) { List<PmsProductCategory> productCategoryList = homeService.getProductCateList(parentId); return CommonResult.success(productCategoryList); } @ApiOperation("根据分类分页获取专题") @RequestMapping(value = "/subjectList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<CmsSubject>> getSubjectList(@RequestParam(required = false) Long cateId, @RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<CmsSubject> subjectList = homeService.getSubjectList(cateId,pageSize,pageNum); return CommonResult.success(subjectList);
} @ApiOperation("分页获取人气推荐商品") @RequestMapping(value = "/hotProductList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> hotProductList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) { List<PmsProduct> productList = homeService.hotProductList(pageNum,pageSize); return CommonResult.success(productList); } @ApiOperation("分页获取新品推荐商品") @RequestMapping(value = "/newProductList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> newProductList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) { List<PmsProduct> productList = homeService.newProductList(pageNum,pageSize); return CommonResult.success(productList); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\HomeController.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isAccepted(String profile) { return getAccepted().contains(profile); } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("active", getActive().toString()); creator.append("default", getDefault().toString()); creator.append("accepted", getAccepted().toString()); return creator.toString(); } /** * A profiles type that can be obtained. */ private enum Type { ACTIVE(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, Environment::getActiveProfiles, true, Collections.emptySet()), DEFAULT(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, Environment::getDefaultProfiles, false, Collections.singleton("default")); private final Function<Environment, String[]> getter; private final boolean mergeWithEnvironmentProfiles; private final String name; private final Set<String> defaultValue; Type(String name, Function<Environment, String[]> getter, boolean mergeWithEnvironmentProfiles, Set<String> defaultValue) { this.name = name; this.getter = getter; this.mergeWithEnvironmentProfiles = mergeWithEnvironmentProfiles; this.defaultValue = defaultValue; }
String getName() { return this.name; } String[] get(Environment environment) { return this.getter.apply(environment); } Set<String> getDefaultValue() { return this.defaultValue; } boolean isMergeWithEnvironmentProfiles() { return this.mergeWithEnvironmentProfiles; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\Profiles.java
2
请完成以下Java代码
public String computeCaption(@NonNull final ITranslatableString originalProcessCaption, @NonNull final String adLanguage) { final ITranslatableString caption = captionMapper != null ? captionMapper.computeCaption(originalProcessCaption) : originalProcessCaption; return caption.translate(adLanguage); } /** * Derive this resolution, overriding the caption. * * @param captionOverride caption override; null value will be considered as no override */ public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final String captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final ITranslatableString captionOverride) { return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride)); } @Value private static class ProcessCaptionOverrideMapper implements ProcessCaptionMapper { @NonNull ITranslatableString captionOverride; public ProcessCaptionOverrideMapper(@NonNull final ITranslatableString captionOverride) { this.captionOverride = captionOverride; } public ProcessCaptionOverrideMapper(@NonNull final String captionOverride) { this.captionOverride = TranslatableStrings.anyLanguage(captionOverride); } @Override public ITranslatableString computeCaption(final ITranslatableString originalProcessCaption) { return captionOverride; } } public ProcessPreconditionsResolution withCaptionMapper(@Nullable final ProcessCaptionMapper captionMapper) {
return toBuilder().captionMapper(captionMapper).build(); } /** * Override default SortNo used with ordering related processes */ public ProcessPreconditionsResolution withSortNo(final int sortNo) { return !this.sortNo.isPresent() || this.sortNo.getAsInt() != sortNo ? toBuilder().sortNo(OptionalInt.of(sortNo)).build() : this; } public @NonNull OptionalInt getSortNo() {return this.sortNo;} public ProcessPreconditionsResolution and(final Supplier<ProcessPreconditionsResolution> resolutionSupplier) { if (isRejected()) { return this; } return resolutionSupplier.get(); } public void throwExceptionIfRejected() { if (isRejected()) { throw new AdempiereException(getRejectReason()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionsResolution.java
1
请完成以下Java代码
public void setLastName(String userLastName) { this.lastName = userLastName; } @CamundaQueryParam("lastNameLike") public void setLastNameLike(String userLastNameLike) { this.lastNameLike = userLastNameLike; } @CamundaQueryParam("email") public void setEmail(String userEmail) { this.email = userEmail; } @CamundaQueryParam("emailLike") public void setEmailLike(String userEmailLike) { this.emailLike = userEmailLike; } @CamundaQueryParam("memberOfGroup") public void setMemberOfGroup(String memberOfGroup) { this.memberOfGroup = memberOfGroup; } @CamundaQueryParam("potentialStarter") public void setPotentialStarter(String potentialStarter) { this.potentialStarter = potentialStarter; } @CamundaQueryParam("memberOfTenant") public void setMemberOfTenant(String tenantId) { this.tenantId = tenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected UserQuery createNewQuery(ProcessEngine engine) { return engine.getIdentityService().createUserQuery(); } @Override protected void applyFilters(UserQuery query) { if (id != null) { query.userId(id); } if(idIn != null) { query.userIdIn(idIn); } if (firstName != null) { query.userFirstName(firstName); } if (firstNameLike != null) { query.userFirstNameLike(firstNameLike); } if (lastName != null) {
query.userLastName(lastName); } if (lastNameLike != null) { query.userLastNameLike(lastNameLike); } if (email != null) { query.userEmail(email); } if (emailLike != null) { query.userEmailLike(emailLike); } if (memberOfGroup != null) { query.memberOfGroup(memberOfGroup); } if (potentialStarter != null) { query.potentialStarter(potentialStarter); } if (tenantId != null) { query.memberOfTenant(tenantId); } } @Override protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_USER_ID_VALUE)) { query.orderByUserId(); } else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) { query.orderByUserFirstName(); } else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) { query.orderByUserLastName(); } else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) { query.orderByUserEmail(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
1
请完成以下Java代码
public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** * PostingType AD_Reference_ID=125 * Reference name: _Posting Type */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Actual Year End = Y */ public static final String POSTINGTYPE_ActualYearEnd = "Y"; /** Set Buchungsart. @param PostingType
Die Art des gebuchten Betrages dieser Transaktion */ @Override public void setPostingType (java.lang.String PostingType) { set_ValueNoCheck (COLUMNNAME_PostingType, PostingType); } /** Get Buchungsart. @return Die Art des gebuchten Betrages dieser Transaktion */ @Override public java.lang.String getPostingType () { return (java.lang.String)get_Value(COLUMNNAME_PostingType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_EndingBalance.java
1
请完成以下Java代码
public class InvoiceCandidateCompensationGroupUtils { public static void assertInGroup(final I_C_Invoice_Candidate invoiceCandidate) { if (!isInGroup(invoiceCandidate)) { throw new AdempiereException("Invoice candidate " + invoiceCandidate + " shall be part of a compensation group"); } } public static void assertNotInGroup(final I_C_Invoice_Candidate invoiceCandidate) { if (isInGroup(invoiceCandidate)) { throw new AdempiereException("Invoice candidate " + invoiceCandidate + " shall NOT be part of a compensation group"); }
} public static boolean isInGroup(final I_C_Invoice_Candidate invoiceCandidate) { return invoiceCandidate.getC_Order_CompensationGroup_ID() > 0; } public static void assertCompensationLine(final I_C_Invoice_Candidate invoiceCandidate) { if (!invoiceCandidate.isGroupCompensationLine()) { throw new AdempiereException("Invoice candidate " + invoiceCandidate.getLine() + " shall be a compensation line"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateCompensationGroupUtils.java
1
请在Spring Boot框架中完成以下Java代码
public static I_M_ProductPrice createProductPriceOrUpdateExistentOne(@NonNull final ProductPriceCreateRequest ppRequest, @NonNull final I_M_PriceList_Version plv) { final IProductDAO productDAO = Services.get(IProductDAO.class); final BigDecimal price = ppRequest.getPrice().setScale(2); I_M_ProductPrice pp = ProductPrices.retrieveMainProductPriceOrNull(plv, ProductId.ofRepoId(ppRequest.getProductId())); if (pp == null) { pp = newInstance(I_M_ProductPrice.class, plv); } // do not update the price with value 0; 0 means that no price was changed else if (pp != null && price.signum() == 0) { return pp; }
pp.setM_PriceList_Version_ID(plv.getM_PriceList_Version_ID()); pp.setM_Product_ID(ppRequest.getProductId()); pp.setSeqNo(ppRequest.getSeqNo()); pp.setPriceLimit(price); pp.setPriceList(price); pp.setPriceStd(price); final org.compiere.model.I_M_Product product = productDAO.getById(ppRequest.getProductId()); pp.setC_UOM_ID(product.getC_UOM_ID()); pp.setC_TaxCategory_ID(ppRequest.getTaxCategoryId()); save(pp); return pp; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductPrices.java
2
请在Spring Boot框架中完成以下Java代码
public class RestAuthController { @Value("${google.client-id}") private String clientid; @Value("${google.client-secret}") private String clientsecret; @Value("${google.redirect-uri}") private String redirecturi; @RequestMapping("/render") public void renderAuth(HttpServletResponse response) throws IOException { AuthRequest authRequest = getAuthRequest(); response.sendRedirect(authRequest.authorize(AuthStateUtils.createState())); } @RequestMapping("/callback") public Object login(AuthCallback callback) {
AuthRequest authRequest = getAuthRequest(); return authRequest.login(callback); } private AuthRequest getAuthRequest() { return new AuthGoogleRequest(AuthConfig.builder() .clientId(clientid) .clientSecret(clientsecret) .redirectUri(redirecturi) .httpConfig(HttpConfig.builder() .timeout(15000) //proxy host and port .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1087))) .build()) .build()); } }
repos\springboot-demo-master\socia-login\google\src\main\java\com\et\google\controller\RestAuthController.java
2
请在Spring Boot框架中完成以下Java代码
public class Bar implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private String name; @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @OrderBy("name ASC") List<Foo> fooList; public Bar() { super(); } public Bar(final String name) { super(); this.name = name; } // API public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public List<Foo> getFooList() { return fooList; } public void setFooList(final List<Foo> fooList) { this.fooList = fooList; }
// @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Bar other = (Bar) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Bar [name=").append(name).append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\model\Bar.java
2
请完成以下Java代码
private String printKeys(Set<String> keys) { return Stream.ofNullable(keys).map(String::valueOf).collect(Collectors.joining(", ")); } @SuppressWarnings("unchecked") @Override public <T> T getInBoundVariable(String name) { return Optional.ofNullable(inBoundVariables) .map(it -> (T) inBoundVariables.get(name)) .orElse(null); } @SuppressWarnings("unchecked") @Override public <T> T getInBoundVariable(String name, Class<T> type) { return Optional.ofNullable(inBoundVariables) .map(it -> (T) inBoundVariables.get(name)) .orElse(null); } @SuppressWarnings("unchecked") @Override public <T> T getOutBoundVariable(String name) { return Optional.ofNullable(outBoundVariables) .map(it -> (T) it.get(name))
.orElse(null); } @SuppressWarnings("unchecked") @Override public <T> T getOutBoundVariable(String name, Class<T> type) { return Optional.ofNullable(outBoundVariables) .map(it -> (T) it.get(name)) .orElse(null); } @Override @JsonProperty("ephemeralVariables") public boolean hasEphemeralVariables() { return Boolean.TRUE.equals(this.ephemeralVariables); } public void clearOutBoundVariables() { this.outBoundVariables.clear(); } public void clearInBoundVariables() { this.inBoundVariables.clear(); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\IntegrationContextImpl.java
1
请完成以下Java代码
protected Class<?> findClass(String name) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); final ClassLoaderFile file = this.updatedFiles.getFile(path); if (file == null) { return super.findClass(name); } if (file.getKind() == Kind.DELETED) { throw new ClassNotFoundException(name); } byte[] bytes = file.getContents(); Assert.state(bytes != null, "'bytes' must not be null"); return defineClass(name, bytes, 0, bytes.length); } @Override public Class<?> publicDefineClass(String name, byte[] b, @Nullable ProtectionDomain protectionDomain) { return defineClass(name, b, 0, b.length, protectionDomain); } @Override public ClassLoader getOriginalClassLoader() { return getParent(); } private URL createFileUrl(String name, ClassLoaderFile file) { try { return new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); } } @Override public boolean isClassReloadable(Class<?> classType) { return (classType.getClassLoader() instanceof RestartClassLoader); } /** * Compound {@link Enumeration} that adds an item to the front.
*/ private static class CompoundEnumeration<E> implements Enumeration<E> { private @Nullable E firstElement; private final Enumeration<E> enumeration; CompoundEnumeration(@Nullable E firstElement, Enumeration<E> enumeration) { this.firstElement = firstElement; this.enumeration = enumeration; } @Override public boolean hasMoreElements() { return (this.firstElement != null || this.enumeration.hasMoreElements()); } @Override public E nextElement() { if (this.firstElement == null) { return this.enumeration.nextElement(); } E element = this.firstElement; this.firstElement = null; return element; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\RestartClassLoader.java
1
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; }
public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public String getLockTime() { return lockTime; } public void setLockTime(String lockTime) { this.lockTime = lockTime; } public int getProcessed() { return isProcessed; } public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isValidateTransactionState() { return this.validateTransactionState; } public void setValidateTransactionState(boolean validateTransactionState) { this.validateTransactionState = validateTransactionState; } public @Nullable Isolation getIsolationLevelForCreate() { return this.isolationLevelForCreate; } public void setIsolationLevelForCreate(@Nullable Isolation isolationLevelForCreate) { this.isolationLevelForCreate = isolationLevelForCreate; }
public @Nullable String getTablePrefix() { return this.tablePrefix; } public void setTablePrefix(@Nullable String tablePrefix) { this.tablePrefix = tablePrefix; } @Override public String getDefaultSchemaLocation() { return DEFAULT_SCHEMA_LOCATION; } }
repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcProperties.java
2
请完成以下Java代码
protected Endpoint createEndpoint(String s, String s1, Map<String, Object> parameters) throws Exception { FlowableEndpoint ae = new FlowableEndpoint(s, getCamelContext()); ae.setComponent(this); ae.setIdentityService(identityService); ae.setRuntimeService(runtimeService); ae.setRepositoryService(repositoryService); ae.setManagementService(managementService); ae.setCopyVariablesToProperties(this.copyVariablesToProperties); ae.setCopyVariablesToBodyAsMap(this.copyVariablesToBodyAsMap); ae.setCopyCamelBodyToBody(this.copyCamelBodyToBody); Map<String, Object> returnVars = PropertiesHelper.extractProperties(parameters, "var.return."); if (returnVars != null && returnVars.size() > 0) { ae.getReturnVarMap().putAll(returnVars); } return ae; } public boolean isCopyVariablesToProperties() { return copyVariablesToProperties; }
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) { this.copyVariablesToProperties = copyVariablesToProperties; } public boolean isCopyCamelBodyToBody() { return copyCamelBodyToBody; } public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) { this.copyCamelBodyToBody = copyCamelBodyToBody; } public boolean isCopyVariablesToBodyAsMap() { return copyVariablesToBodyAsMap; } public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) { this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap; } }
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableComponent.java
1
请完成以下Java代码
public Optional<ResourceId> getPlantOfWarehouse(@NonNull final WarehouseId warehouseId) { final I_M_Warehouse warehouse = Services.get(IWarehouseBL.class).getById(warehouseId); return ResourceId.optionalOfRepoId(warehouse.getPP_Plant_ID()); } public Optional<PPRoutingId> getDefaultRoutingId(@NonNull final PPRoutingType type) { return routingRepository.getDefaultRoutingIdByType(type); } public int calculateDurationDays( @NonNull final ProductPlanning productPlanning, @NonNull final BigDecimal qty) { final int leadTimeDays = calculateLeadTimeDays(productPlanning, qty); return calculateDurationDays(leadTimeDays, productPlanning); } private int calculateLeadTimeDays( @NonNull final ProductPlanning productPlanningRecord,
@NonNull final BigDecimal qty) { final int leadTimeDays = productPlanningRecord.getLeadTimeDays(); if (leadTimeDays > 0) { // LeadTime was set in Product Planning/ take the leadtime as it is return leadTimeDays; } final PPRoutingId routingId = productPlanningRecord.getWorkflowId(); final ResourceId plantId = productPlanningRecord.getPlantId(); final RoutingService routingService = RoutingServiceFactory.get().getRoutingService(); return routingService.calculateDurationDays(routingId, plantId, qty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ProductPlanningService.java
1
请在Spring Boot框架中完成以下Java代码
protected final F getAuthenticationFilter() { return this.authFilter; } /** * Sets the Authentication Filter * @param authFilter the Authentication Filter */ protected final void setAuthenticationFilter(F authFilter) { this.authFilter = authFilter; } /** * Gets the login page * @return the login page */ protected final String getLoginPage() { return this.loginPage; } /** * Gets the Authentication Entry Point * @return the Authentication Entry Point */ protected final AuthenticationEntryPoint getAuthenticationEntryPoint() { return this.authenticationEntryPoint; } /** * Gets the URL to submit an authentication request to (i.e. where username/password * must be submitted) * @return the URL to submit an authentication request to */ protected final String getLoginProcessingUrl() { return this.loginProcessingUrl; } /** * Gets the URL to send users to if authentication fails * @return the URL to send users if authentication fails (e.g. "/login?error"). */ protected final String getFailureUrl() { return this.failureUrl; } /** * Updates the default values for authentication. */ protected final void updateAuthenticationDefaults() { if (this.loginProcessingUrl == null) { loginProcessingUrl(this.loginPage); } if (this.failureHandler == null) { failureUrl(this.loginPage + "?error"); }
LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class); if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) { logoutConfigurer.logoutSuccessUrl(this.loginPage + "?logout"); } } /** * Updates the default values for access. */ protected final void updateAccessDefaults(B http) { if (this.permitAll) { PermitAllSupport.permitAll(http, this.loginPage, this.loginProcessingUrl, this.failureUrl); } } /** * Sets the loginPage and updates the {@link AuthenticationEntryPoint}. * @param loginPage */ private void setLoginPage(String loginPage) { this.loginPage = loginPage; this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage); } private <C> C getBeanOrNull(B http, Class<C> clazz) { ApplicationContext context = http.getSharedObject(ApplicationContext.class); if (context == null) { return null; } return context.getBeanProvider(clazz).getIfUnique(); } @SuppressWarnings("unchecked") private T getSelf() { return (T) this; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractAuthenticationFilterConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public class RequestFilter extends OncePerRequestFilter implements Filter { @Autowired TokenService tokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { //每个请求记录一个traceId,可以根据traceId搜索出本次请求的全部相关日志 MDC.put("traceId", UUID.randomUUID().toString().replace("-", "").substring(0, 12)); setUsername(request); setProductId(request); //使request中的body可以重复读取 https://juejin.im/post/6858037733776949262#heading-4 request = new ContentCachingRequestWrapper(request); filterChain.doFilter(request, response); } catch (Exception e) { throw e; } finally { //清理ThreadLocal MDC.clear(); } } /** * 将url参数中的productId放入ThreadLocal */ private void setProductId(HttpServletRequest request) { String productIdStr = request.getParameter("productId"); if (!StringTools.isNullOrEmpty(productIdStr)) { log.debug("url中productId = {}", productIdStr); MDC.put("productId", productIdStr); } }
private void setUsername(HttpServletRequest request) { //通过token解析出username String token = request.getHeader("token"); if (!StringTools.isNullOrEmpty(token)) { MDC.put("token", token); try { SessionUserInfo info = tokenService.getUserInfo(); if (info != null) { String username = info.getUsername(); MDC.put("username", username); } } catch (CommonJsonException e) { log.info("无效的token:{}", token); } } } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\filter\RequestFilter.java
2
请完成以下Java代码
public class VariableCreatedListenerDelegate implements ActivitiEventListener { private final List<VariableEventListener<VariableCreatedEvent>> listeners; private final ToVariableCreatedConverter converter; private final VariableEventFilter variableEventFilter; public VariableCreatedListenerDelegate( List<VariableEventListener<VariableCreatedEvent>> listeners, ToVariableCreatedConverter converter, VariableEventFilter variableEventFilter ) { this.listeners = listeners; this.converter = converter; this.variableEventFilter = variableEventFilter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiVariableEvent) { ActivitiVariableEvent internalEvent = (ActivitiVariableEvent) event; if (variableEventFilter.shouldEmmitEvent(internalEvent)) {
converter .from(internalEvent) .ifPresent(convertedEvent -> { if (listeners != null) { for (VariableEventListener<VariableCreatedEvent> listener : listeners) { listener.onEvent(convertedEvent); } } }); } } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-runtime-shared-impl\src\main\java\org\activiti\runtime\api\event\internal\VariableCreatedListenerDelegate.java
1
请完成以下Java代码
public Set<DocumentId> process(final QuickInput quickInput) { final I_C_Invoice invoice = quickInput.getRootDocumentAs(I_C_Invoice.class); final IInvoiceLineQuickInput invoiceLineQuickInput = quickInput.getQuickInputDocumentAs(IInvoiceLineQuickInput.class); // 3834 final ProductId productId = ProductId.ofRepoId(invoiceLineQuickInput.getM_Product_ID()); final BPartnerId partnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final SOTrx soTrx = SOTrx.ofBooleanNotNull(invoice.isSOTrx()); partnerProductBL.assertNotExcludedFromTransaction(soTrx, productId, partnerId); final I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, invoice); invoiceLine.setC_Invoice(invoice); invoiceBL.setProductAndUOM(invoiceLine, productId); final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setBpartnerId(partnerId); huPackingAware.setInDispute(false); huPackingAware.setProductId(productId); huPackingAware.setUomId(UomId.ofRepoIdOrNull(invoiceLine.getC_UOM_ID())); huPackingAware.setPiItemProductId(invoiceLineQuickInput.getM_HU_PI_Item_Product_ID() > 0 ? HUPIItemProductId.ofRepoId(invoiceLineQuickInput.getM_HU_PI_Item_Product_ID())
: HUPIItemProductId.VIRTUAL_HU); huPackingAwareBL.computeAndSetQtysForNewHuPackingAware(huPackingAware, invoiceLineQuickInput.getQty()); huPackingAwareBL.prepareCopyFrom(huPackingAware) .overridePartner(false) .copyTo(InvoiceLineHUPackingAware.of(invoiceLine)); invoiceLineBL.updatePrices(invoiceLine); // invoiceBL.setLineNetAmt(invoiceLine); // not needed; will be called on save // invoiceBL.setTaxAmt(invoiceLine);// not needed; will be called on save InterfaceWrapperHelper.save(invoiceLine); final DocumentId documentId = DocumentId.of(invoiceLine.getC_InvoiceLine_ID()); return ImmutableSet.of(documentId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\invoiceline\InvoiceLineQuickInputProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public static class DmnEngineProcessConfiguration extends BaseEngineConfigurationWithConfigurers<SpringDmnEngineConfiguration> { @Bean @ConditionalOnMissingBean(name = "dmnProcessEngineConfigurationConfigurer") public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> dmnProcessEngineConfigurationConfigurer( DmnEngineConfigurator dmnEngineConfigurator ) { return processEngineConfiguration -> processEngineConfiguration.addConfigurator(dmnEngineConfigurator); } @Bean @ConditionalOnMissingBean public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(type = {
"org.flowable.app.spring.SpringAppEngineConfiguration" }) public static class DmnEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringDmnEngineConfiguration> { @Bean @ConditionalOnMissingBean(name = "dmnAppEngineConfigurationConfigurer") public EngineConfigurationConfigurer<SpringAppEngineConfiguration> dmnAppEngineConfigurationConfigurer( DmnEngineConfigurator dmnEngineConfigurator ) { return appEngineConfiguration -> appEngineConfiguration.addConfigurator(dmnEngineConfigurator); } @Bean @ConditionalOnMissingBean public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\DmnEngineAutoConfiguration.java
2
请完成以下Java代码
public class OrderCreatedEvent { private final String orderId; public OrderCreatedEvent(String orderId) { this.orderId = orderId; } public String getOrderId() { return orderId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} OrderCreatedEvent that = (OrderCreatedEvent) o; return Objects.equals(orderId, that.orderId); } @Override public int hashCode() { return Objects.hash(orderId); } @Override public String toString() { return "OrderCreatedEvent{" + "orderId='" + orderId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\events\OrderCreatedEvent.java
1
请完成以下Java代码
public boolean appliesTo(@NonNull final MappingCriteria mappingCriteria) { return appliesToCustomer(mappingCriteria.getCustomerId()) && appliesToProduct(mappingCriteria.getProductId()) && appliesToProductCategory(mappingCriteria.getProductCategoryId()); } private boolean appliesToCustomer(@NonNull final BPartnerId customerCandidateId) { if (this.customerId == null) { return true; } return this.customerId.equals(customerCandidateId); } private boolean appliesToProduct(@NonNull final ProductId productId) { if (this.productId == null) { return true; } return this.productId.equals(productId); } private boolean appliesToProductCategory(@NonNull final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) {
return true; } return this.productCategoryId.equals(productCategoryId); } @NonNull public Percent getPercent() { return Percent.of(this.marginPercent); } @Value @Builder public static class MappingCriteria { @NonNull BPartnerId customerId; @NonNull ProductId productId; @NonNull ProductCategoryId productCategoryId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginLine.java
1
请完成以下Java代码
default void setProductId(final ProductId productId) { setM_Product_ID(ProductId.toRepoId(productId)); } int getC_BPartner_ID(); /** * Match only those {@link I_M_HU_PI_Item_Product}s which are about this partner or any bpartner. */ void setC_BPartner_ID(final int bpartnerId); default void setBPartnerId(@Nullable final BPartnerId bpartnerId) { setC_BPartner_ID(BPartnerId.toRepoId(bpartnerId)); } /** * Match only those {@link I_M_HU_PI_Item_Product}s which belong to a {@link I_M_ProductPrice} of this PLV. */ void setPriceListVersionId(@Nullable final PriceListVersionId priceListVersionId); @Nullable PriceListVersionId getPriceListVersionId(); void setDate(@Nullable ZonedDateTime date); ZonedDateTime getDate(); boolean isAllowAnyProduct(); void setAllowAnyProduct(final boolean allowAnyProduct); boolean isAllowInfiniteCapacity(); void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity); String getHU_UnitType(); void setHU_UnitType(final String huUnitType); boolean isAllowVirtualPI(); void setAllowVirtualPI(final boolean allowVirtualPI); boolean isOneConfigurationPerPI(); /** * If true, it will retain only one configuration (i.e. {@link I_M_HU_PI_Item_Product}) for each distinct {@link I_M_HU_PI} found. */ void setOneConfigurationPerPI(final boolean oneConfigurationPerPI); boolean isAllowDifferentCapacities(); /** * In case {@link #isOneConfigurationPerPI()}, if <code>allowDifferentCapacities</code> is true, it will retain one configuration for each distinct {@link I_M_HU_PI} <b>AND</b>
* {@link I_M_HU_PI_Item_Product#getQty()}. * </ul> */ void setAllowDifferentCapacities(boolean allowDifferentCapacities); // 08393 // the possibility to create the query for any partner (not just for a given one or null) boolean isAllowAnyPartner(); void setAllowAnyPartner(final boolean allowAnyPartner); /** * task: https://metasfresh.atlassian.net/browse/FRESH-386 */ // @formatter:off void setM_Product_Packaging_ID(int packagingProductId); int getM_Product_Packaging_ID(); // @formatter:on // @formatter:off void setDefaultForProduct(final boolean defaultForProduct); boolean isDefaultForProduct(); // @formatter:on }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUPIItemProductQuery.java
1
请在Spring Boot框架中完成以下Java代码
public EndpointDetectionTrigger endpointDetectionTrigger(EndpointDetector endpointDetector, Publisher<InstanceEvent> events) { return new EndpointDetectionTrigger(endpointDetector, events); } @Bean @ConditionalOnMissingBean public InfoUpdater infoUpdater(InstanceRepository instanceRepository, InstanceWebClient.Builder instanceWebClientBuilder) { return new InfoUpdater(instanceRepository, instanceWebClientBuilder.build(), new ApiMediaTypeHandler()); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public InfoUpdateTrigger infoUpdateTrigger(InfoUpdater infoUpdater, Publisher<InstanceEvent> events) { return new InfoUpdateTrigger(infoUpdater, events, this.adminServerProperties.getMonitor().getInfoInterval(), this.adminServerProperties.getMonitor().getInfoLifetime(),
this.adminServerProperties.getMonitor().getInfoMaxBackoff()); } @Bean @ConditionalOnMissingBean(InstanceEventStore.class) public InMemoryEventStore eventStore() { return new InMemoryEventStore(); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean(InstanceRepository.class) public SnapshottingInstanceRepository instanceRepository(InstanceEventStore eventStore) { return new SnapshottingInstanceRepository(eventStore); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerAutoConfiguration.java
2
请完成以下Java代码
public final class LocalMessages { private static final String BUNDLE_NAME = "org.activiti.core.el.juel.misc.LocalStrings"; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, Locale.US); public static String get(String key, Object... args) { String template = null; try { template = RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { StringBuilder b = new StringBuilder(); try { b.append(RESOURCE_BUNDLE.getString("message.unknown")); b.append(": "); } catch (MissingResourceException e2) {}
b.append(key); if (args != null && args.length > 0) { b.append("("); b.append(args[0]); for (int i = 1; i < args.length; i++) { b.append(", "); b.append(args[i]); } b.append(")"); } return b.toString(); } return MessageFormat.format(template, args); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\LocalMessages.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserService userService; /** * 查询用户列表 * * @return 用户列表 */ @GetMapping("/list") public Flux<UserVO> list() { // 查询列表 List<UserVO> result = new ArrayList<>(); result.add(new UserVO().setId(1).setUsername("yudaoyuanma")); result.add(new UserVO().setId(2).setUsername("woshiyutou")); result.add(new UserVO().setId(3).setUsername("chifanshuijiao")); // 返回列表 return Flux.fromIterable(result); } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get") public Mono<UserVO> get(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return Mono.just(user); } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/v2/get") public Mono<UserVO> get2(@RequestParam("id") Integer id) { // 查询用户 UserVO user = userService.get(id); // 返回 return Mono.just(user); } /** * 添加用户 * * @param addDTO 添加用户信息 DTO * @return 添加成功的用户编号 */ @PostMapping("add") public Mono<Integer> add(@RequestBody Publisher<UserAddDTO> addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return Mono.just(returnId); } /**
* 添加用户 * * @param addDTO 添加用户信息 DTO * @return 添加成功的用户编号 */ @PostMapping("add2") public Mono<Integer> add2(Mono<UserAddDTO> addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return Mono.just(returnId); } /** * 更新指定用户编号的用户 * * @param updateDTO 更新用户信息 DTO * @return 是否修改成功 */ @PostMapping("/update") public Mono<Boolean> update(@RequestBody Publisher<UserUpdateDTO> updateDTO) { // 更新用户记录 Boolean success = true; // 返回更新是否成功 return Mono.just(success); } /** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE public Mono<Boolean> delete(@RequestParam("id") Integer id) { // 删除用户记录 Boolean success = true; // 返回是否更新成功 return Mono.just(success); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请完成以下Java代码
public EventSubscriptionEntity createSubscriptionForExecution(ExecutionEntity execution) { EventSubscriptionEntity eventSubscriptionEntity = new EventSubscriptionEntity(execution, eventType); String eventName = resolveExpressionOfEventName(execution); eventSubscriptionEntity.setEventName(eventName); if (activityId != null) { ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId); eventSubscriptionEntity.setActivity(activity); } eventSubscriptionEntity.insert(); LegacyBehavior.removeLegacySubscriptionOnParent(execution, eventSubscriptionEntity); return eventSubscriptionEntity; } /** * Resolves the event name within the given scope. */ public String resolveExpressionOfEventName(VariableScope scope) { if (isExpressionAvailable()) { if(scope instanceof BaseDelegateExecution) { // the variable scope execution is also the current context execution
// during expression evaluation the current context is updated with the scope execution return (String) eventName.getValue(scope, (BaseDelegateExecution) scope); } else { return (String) eventName.getValue(scope); } } else { return null; } } protected boolean isExpressionAvailable() { return eventName != null; } public void updateSubscription(EventSubscriptionEntity eventSubscription) { String eventName = resolveExpressionOfEventName(eventSubscription.getExecution()); eventSubscription.setEventName(eventName); eventSubscription.setActivityId(activityId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java
1
请完成以下Java代码
public class OccurPlanItemInstanceOperation extends AbstractMovePlanItemInstanceToTerminalStateOperation { public OccurPlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { super(commandContext, planItemInstanceEntity); } @Override public String getNewState() { return PlanItemInstanceState.COMPLETED; } @Override public String getLifeCycleTransition() { return PlanItemTransition.OCCUR; } @Override public boolean isEvaluateRepetitionRule() { // Only event listeners can be repeating on occur return planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener; } @Override protected boolean shouldAggregateForSingleInstance() { return true; }
@Override protected boolean shouldAggregateForMultipleInstances() { return true; } @Override protected void internalExecute() { planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext)); planItemInstanceEntity.setOccurredTime(planItemInstanceEntity.getEndedTime()); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceOccurred(planItemInstanceEntity); } @Override protected Map<String, String> getAsyncLeaveTransitionMetadata() { throw new UnsupportedOperationException("Occur does not support async leave"); } @Override public String getOperationName() { return "[Occur plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\OccurPlanItemInstanceOperation.java
1
请完成以下Java代码
final class Doc_GLJournal_FactTrxStrategy implements FactTrxStrategy { public static final Doc_GLJournal_FactTrxStrategy instance = new Doc_GLJournal_FactTrxStrategy(); private Doc_GLJournal_FactTrxStrategy() {} @Override public List<FactTrxLines> createFactTrxLines(final List<FactLine> factLines) { if (factLines.isEmpty()) { return ImmutableList.of(); } final Map<Integer, FactTrxLines.FactTrxLinesBuilder> factTrxLinesByKey = new LinkedHashMap<>(); for (final FactLine factLine : factLines) { factTrxLinesByKey.computeIfAbsent(extractGroupNo(factLine), key -> FactTrxLines.builder()) .factLine(factLine); } return factTrxLinesByKey.values() .stream()
.map(FactTrxLines.FactTrxLinesBuilder::build) .collect(ImmutableList.toImmutableList()); } private static int extractGroupNo(final FactLine factLine) { final DocLine<?> docLine = factLine.getDocLine(); if (docLine instanceof DocLine_GLJournal) { return ((DocLine_GLJournal)docLine).getGroupNo(); } else { throw new AdempiereException("Expected a DocLine_GLJournal: " + docLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_GLJournal_FactTrxStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public LocationEntity getLocationEntity() { return locationEntity; } public void setLocationEntity(LocationEntity locationEntity) { this.locationEntity = locationEntity; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getExpressNo() { return expressNo; } public void setExpressNo(String expressNo) { this.expressNo = expressNo; } public UserEntity getBuyer() { return buyer;
} public void setBuyer(UserEntity buyer) { this.buyer = buyer; } @Override public String toString() { return "OrdersEntity{" + "id='" + id + '\'' + ", buyer=" + buyer + ", company=" + company + ", productOrderList=" + productOrderList + ", orderStateEnum=" + orderStateEnum + ", orderStateTimeList=" + orderStateTimeList + ", payModeEnum=" + payModeEnum + ", totalPrice='" + totalPrice + '\'' + ", receiptEntity=" + receiptEntity + ", locationEntity=" + locationEntity + ", remark='" + remark + '\'' + ", expressNo='" + expressNo + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java
2
请在Spring Boot框架中完成以下Java代码
public DecisionRequirementsDefinitionXmlDto getDecisionRequirementsDefinitionDmnXml() { InputStream decisionRequirementsModelInputStream = null; try { decisionRequirementsModelInputStream = engine.getRepositoryService().getDecisionRequirementsModel(decisionRequirementsDefinitionId); byte[] decisionRequirementsModel = IoUtil.readInputStream(decisionRequirementsModelInputStream, "decisionRequirementsModelDmnXml"); return DecisionRequirementsDefinitionXmlDto.create(decisionRequirementsDefinitionId, new String(decisionRequirementsModel, "UTF-8")); } catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e); } catch (UnsupportedEncodingException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e); } finally { IoUtil.closeSilently(decisionRequirementsModelInputStream);
} } @Override public Response getDecisionRequirementsDefinitionDiagram() { DecisionRequirementsDefinition definition = engine.getRepositoryService().getDecisionRequirementsDefinition(decisionRequirementsDefinitionId); InputStream decisionRequirementsDiagram = engine.getRepositoryService().getDecisionRequirementsDiagram(decisionRequirementsDefinitionId); if (decisionRequirementsDiagram == null) { return Response.noContent().build(); } else { String fileName = definition.getDiagramResourceName(); return Response.ok(decisionRequirementsDiagram).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileName)) .type(ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix(fileName)).build(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DecisionRequirementsDefinitionResourceImpl.java
2
请完成以下Java代码
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException { try { Alarm alarm = JacksonUtil.fromString(msg.getData(), Alarm.class); Objects.requireNonNull(alarm, "alarm is null"); ListenableFuture<Alarm> latest = ctx.getAlarmService().findAlarmByIdAsync(ctx.getTenantId(), alarm.getId()); Futures.addCallback(latest, new FutureCallback<>() { @Override public void onSuccess(@Nullable Alarm result) { if (result == null) { ctx.tellFailure(msg, new TbNodeException("No such alarm found.")); return; } boolean isPresent = config.getAlarmStatusList().stream() .anyMatch(alarmStatus -> result.getStatus() == alarmStatus); ctx.tellNext(msg, isPresent ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); } @Override
public void onFailure(Throwable t) { ctx.tellFailure(msg, t); } }, ctx.getDbCallbackExecutor()); } catch (Exception e) { if (e instanceof IllegalArgumentException || e instanceof NullPointerException) { log.debug("[{}][{}] Failed to parse alarm: [{}] error [{}]", ctx.getTenantId(), ctx.getRuleChainName(), msg.getData(), e.getMessage()); } else { log.error("[{}][{}] Failed to parse alarm: [{}]", ctx.getTenantId(), ctx.getRuleChainName(), msg.getData(), e); } throw new TbNodeException(e); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\filter\TbCheckAlarmStatusNode.java
1
请完成以下Java代码
public CaseInstanceChangeState setChangePlanItemIdsWithDefinitionId(Set<ChangePlanItemIdWithDefinitionIdMapping> changePlanItemIdsWithDefinitionId) { this.changePlanItemIdsWithDefinitionId = changePlanItemIdsWithDefinitionId; return this; } public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() { return changePlanItemDefinitionWithNewTargetIds; } public CaseInstanceChangeState setChangePlanItemDefinitionWithNewTargetIds(Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> changePlanItemDefinitionWithNewTargetIds) { this.changePlanItemDefinitionWithNewTargetIds = changePlanItemDefinitionWithNewTargetIds; return this; } public Map<String, Map<String, Object>> getChildInstanceTaskVariables() { return childInstanceTaskVariables; } public CaseInstanceChangeState setChildInstanceTaskVariables(Map<String, Map<String, Object>> childInstanceTaskVariables) { this.childInstanceTaskVariables = childInstanceTaskVariables; return this; } public Map<String, PlanItemInstanceEntity> getCreatedStageInstances() { return createdStageInstances; }
public CaseInstanceChangeState setCreatedStageInstances(HashMap<String, PlanItemInstanceEntity> createdStageInstances) { this.createdStageInstances = createdStageInstances; return this; } public void addCreatedStageInstance(String key, PlanItemInstanceEntity planItemInstance) { this.createdStageInstances.put(key, planItemInstance); } public Map<String, PlanItemInstanceEntity> getTerminatedPlanItemInstances() { return terminatedPlanItemInstances; } public CaseInstanceChangeState setTerminatedPlanItemInstances(HashMap<String, PlanItemInstanceEntity> terminatedPlanItemInstances) { this.terminatedPlanItemInstances = terminatedPlanItemInstances; return this; } public void addTerminatedPlanItemInstance(String key, PlanItemInstanceEntity planItemInstance) { this.terminatedPlanItemInstances.put(key, planItemInstance); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceChangeState.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; }
public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public boolean isDetached() { return jobEntity.getExecutionId() == null; } public void detachState() { jobEntity.setExecution(null); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.detachState(); } } public void attachState(MigratingScopeInstance newOwningInstance) { attachTo(newOwningInstance.resolveRepresentativeExecution()); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.attachState(newOwningInstance); } } public void attachState(MigratingTransitionInstance targetTransitionInstance) { attachTo(targetTransitionInstance.resolveRepresentativeExecution()); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.attachState(targetTransitionInstance); } } protected void attachTo(ExecutionEntity execution) { jobEntity.setExecution(execution); } public void migrateState() { // update activity reference String activityId = targetScope.getId(); jobEntity.setActivityId(activityId); migrateJobHandlerConfiguration(); if (targetJobDefinitionEntity != null) { jobEntity.setJobDefinition(targetJobDefinitionEntity); } // update process definition reference ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) targetScope.getProcessDefinition(); jobEntity.setProcessDefinitionId(processDefinition.getId()); jobEntity.setProcessDefinitionKey(processDefinition.getKey()); // update deployment reference jobEntity.setDeploymentId(processDefinition.getDeploymentId()); }
public void migrateDependentEntities() { for (MigratingInstance migratingDependentInstance : migratingDependentInstances) { migratingDependentInstance.migrateState(); } } public void remove() { jobEntity.delete(); } public boolean migrates() { return targetScope != null; } public ScopeImpl getTargetScope() { return targetScope; } public JobDefinitionEntity getTargetJobDefinitionEntity() { return targetJobDefinitionEntity; } protected abstract void migrateJobHandlerConfiguration(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingJobInstance.java
1
请在Spring Boot框架中完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getSubScopeId() { return subScopeId; }
public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryResponse.java
2
请完成以下Java代码
protected void stopExecutingJobs() { super.stopExecutingJobs(); // Ask the thread pool to finish and exit threadPoolExecutor.shutdown(); // Waits for 1 minute to finish all currently executing jobs try { if(!threadPoolExecutor.awaitTermination(60L, TimeUnit.SECONDS)) { LOG.timeoutDuringShutdown(); } } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownjobExecutor(e); } } // getters and setters ////////////////////////////////////////////////////// public int getQueueSize() { return queueSize; }
public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\DefaultJobExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType;
} public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Long getFromLogNumber() { return fromLogNumber; } public void setFromLogNumber(Long fromLogNumber) { this.fromLogNumber = fromLogNumber; } public Long getToLogNumber() { return toLogNumber; } public void setToLogNumber(Long toLogNumber) { this.toLogNumber = toLogNumber; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public CountryId getCountryId() { return countryId; } @Override public IEditablePricingContext setCountryId(@Nullable final CountryId countryId) { this.countryId = countryId; return this; } @Override public boolean isFailIfNotCalculated() { return failIfNotCalculated; } @Override public IEditablePricingContext setFailIfNotCalculated() { this.failIfNotCalculated = true; return this; } @Override public IEditablePricingContext setSkipCheckingPriceListSOTrxFlag(final boolean skipCheckingPriceListSOTrxFlag) { this.skipCheckingPriceListSOTrxFlag = skipCheckingPriceListSOTrxFlag; return this; } @Nullable public BigDecimal getManualPrice() { return manualPrice; } @Override public IEditablePricingContext setManualPrice(@Nullable final BigDecimal manualPrice) { this.manualPrice = manualPrice; return this; } @Override public boolean isSkipCheckingPriceListSOTrxFlag() { return skipCheckingPriceListSOTrxFlag; } /** If set to not-{@code null}, then the {@link de.metas.pricing.rules.Discount} rule with go with this break as opposed to look for the currently matching break. */
@Override public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak) { this.forcePricingConditionsBreak = forcePricingConditionsBreak; return this; } @Override public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware() { final Object referencedObj = getReferencedObject(); if (referencedObj == null) { return Optional.empty(); } final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class); final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj); return Optional.ofNullable(asiAware); } @Override public Quantity getQuantity() { final BigDecimal ctxQty = getQty(); if (ctxQty == null) { return null; } final UomId ctxUomId = getUomId(); if (ctxUomId == null) { return null; } return Quantitys.of(ctxQty, ctxUomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
2
请完成以下Java代码
public class ReturnWhileValidIterator<T> implements Iterator<T>, IteratorWrapper<T> { private final Predicate<T> isValidPredicate; private final Iterator<T> iterator; private T current; public ReturnWhileValidIterator(final Iterator<T> iterator, final Predicate<T> isValidPredicate) { super(); Check.assumeNotNull(iterator, "iterator not null"); this.iterator = iterator; Check.assumeNotNull(isValidPredicate, "isValidPredicate not null"); this.isValidPredicate = isValidPredicate; } @Override public final Iterator<T> getParentIterator() { return iterator; } @Override public final boolean hasNext() { clearCurrentIfNotValid(); if (current != null) { return true; } return iterator.hasNext(); } private final void clearCurrentIfNotValid() { if (current == null) { return; } final boolean valid = isValidPredicate.test(current); if (!valid) { current = null; } }
@Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } // NOTE: we assume "current" was also checked if it's still valid (in hasNext() method) if (current != null) { return current; } return iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\ReturnWhileValidIterator.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaConfig { private final KafkaProperties kafkaProperties; @Bean public KafkaTemplate<String, String> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } @Bean public ProducerFactory<String, String> producerFactory() { return new DefaultKafkaProducerFactory<>(kafkaProperties.buildProducerProperties()); } @Bean public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(KafkaConsts.DEFAULT_PARTITION_NUM); factory.setBatchListener(true); factory.getContainerProperties().setPollTimeout(3000); return factory; }
@Bean public ConsumerFactory<String, String> consumerFactory() { return new DefaultKafkaConsumerFactory<>(kafkaProperties.buildConsumerProperties()); } @Bean("ackContainerFactory") public ConcurrentKafkaListenerContainerFactory<String, String> ackContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); factory.setConcurrency(KafkaConsts.DEFAULT_PARTITION_NUM); return factory; } }
repos\spring-boot-demo-master\demo-mq-kafka\src\main\java\com\xkcoding\mq\kafka\config\KafkaConfig.java
2
请完成以下Java代码
public Decision getRequiredDecision() { return requiredDecisionRef.getReferenceTargetElement(this); } public void setRequiredDecision(Decision requiredDecision) { requiredDecisionRef.setReferenceTargetElement(this, requiredDecision); } public InputData getRequiredInput() { return requiredInputRef.getReferenceTargetElement(this); } public void setRequiredInput(InputData requiredInput) { requiredInputRef.setReferenceTargetElement(this, requiredInput); } public KnowledgeSource getRequiredAuthority() { return requiredAuthorityRef.getReferenceTargetElement(this); } public void setRequiredAuthority(KnowledgeSource requiredAuthority) { requiredAuthorityRef.setReferenceTargetElement(this, requiredAuthority); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(AuthorityRequirement.class, DMN_ELEMENT_AUTHORITY_REQUIREMENT) .namespaceUri(LATEST_DMN_NS) .instanceProvider(new ModelTypeInstanceProvider<AuthorityRequirement>() {
public AuthorityRequirement newInstance(ModelTypeInstanceContext instanceContext) { return new AuthorityRequirementImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); requiredDecisionRef = sequenceBuilder.element(RequiredDecisionReference.class) .uriElementReference(Decision.class) .build(); requiredInputRef = sequenceBuilder.element(RequiredInputReference.class) .uriElementReference(InputData.class) .build(); requiredAuthorityRef = sequenceBuilder.element(RequiredAuthorityReference.class) .uriElementReference(KnowledgeSource.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\AuthorityRequirementImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return forceCacheable; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return mappings.isJPAEntity(value); } @Override public void setValue(Object value, ValueFields valueFields) { EntityManagerSession entityManagerSession = Context.getCommandContext().getSession(EntityManagerSession.class); if (entityManagerSession == null) { throw new FlowableException("Cannot set JPA variable: " + EntityManagerSession.class + " not configured"); } else { // Before we set the value we must flush all pending changes from // the entitymanager // If we don't do this, in some cases the primary key will not yet // be set in the object // which will cause exceptions down the road. entityManagerSession.flush(); } if (value != null) { String className = mappings.getJPAClassString(value); String idString = mappings.getJPAIdString(value); valueFields.setTextValue(className); valueFields.setTextValue2(idString);
} else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } @Override public Object getValue(ValueFields valueFields) { if (valueFields.getTextValue() != null && valueFields.getTextValue2() != null) { return mappings.getJPAEntity(valueFields.getTextValue(), valueFields.getTextValue2()); } return null; } /** * Force the value to be cacheable. */ @Override public void setForceCacheable(boolean forceCachedValue) { this.forceCacheable = forceCachedValue; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JPAEntityVariableType.java
2
请在Spring Boot框架中完成以下Java代码
public class MSV3ServerConfigRepository { private final CCache<Integer, MSV3ServerConfig> serverConfigCache = CCache.<Integer, MSV3ServerConfig> builder() .tableName(I_MSV3_Server.Table_Name) .initialCapacity(1) .additionalTableNameToResetFor(I_MSV3_Server_Product_Category.Table_Name) .build(); public MSV3ServerConfig getServerConfig() { return serverConfigCache.getOrLoad(0, this::retrieveServerConfig); } private MSV3ServerConfig retrieveServerConfig() { final MSV3ServerConfigBuilder serverConfigBuilder = MSV3ServerConfig.builder(); final I_MSV3_Server serverConfigRecord = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_MSV3_Server.class) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_MSV3_Server.class);
if (serverConfigRecord != null) { final int fixedQtyAvailableToPromise = serverConfigRecord.getFixedQtyAvailableToPromise(); serverConfigBuilder.fixedQtyAvailableToPromise(fixedQtyAvailableToPromise); final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); final WarehousePickingGroupId warehousePickingGroupId = WarehousePickingGroupId.ofRepoId(serverConfigRecord.getM_Warehouse_PickingGroup_ID()); // note that the DAO method invoked by this supplier is cached serverConfigBuilder.warehousePickingGroupSupplier(() -> warehouseDAO.getWarehousePickingGroupById(warehousePickingGroupId)); } Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_MSV3_Server_Product_Category.class) .addOnlyActiveRecordsFilter() .create() .list(I_MSV3_Server_Product_Category.class) .forEach(productCategoryRecord -> serverConfigBuilder.productCategoryId(ProductCategoryId.ofRepoId(productCategoryRecord.getM_Product_Category_ID()))); return serverConfigBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3ServerConfigRepository.java
2
请完成以下Java代码
static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Kansas City"); JsonDocument upserted = bucket.upsert(document); return upserted; } static JsonDocument replaceExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Milwaukee"); JsonDocument replaced = bucket.replace(document); return replaced; } static JsonDocument removeExample(Bucket bucket, String id) { JsonDocument removed = bucket.remove(id); return removed; } static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { try { return bucket.get(id); } catch (CouchbaseException e) { List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
if (!list.isEmpty()) { return list.get(0); } } return null; } static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) { long maxCasValue = -1; JsonDocument latest = null; for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { if (replica.cas() > maxCasValue) { latest = replica; maxCasValue = replica.cas(); } } return latest; } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\intro\CodeSnippets.java
1
请完成以下Java代码
public SuspendedJobQueryImpl jobWithoutTenantId() { this.withoutTenantId = true; return this; } // sorting ////////////////////////////////////////// public SuspendedJobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public SuspendedJobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public SuspendedJobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public SuspendedJobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public SuspendedJobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public SuspendedJobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobCountByQueryCriteria(this); } public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\SuspendedJobQueryImpl.java
1
请完成以下Java代码
public Builder setProcessId(final ProcessId processId) { this.processId = processId; return this; } public Builder setLayoutType(final PanelLayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = caption; return this; } public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public ITranslatableString getDescription() { return description; } public Builder addElement(final DocumentLayoutElementDescriptor element) { Check.assumeNotNull(element, "Parameter element is not null"); elements.add(element); return this; }
public Builder addElement(final DocumentFieldDescriptor processParaDescriptor) { Check.assumeNotNull(processParaDescriptor, "Parameter processParaDescriptor is not null"); final DocumentLayoutElementDescriptor element = DocumentLayoutElementDescriptor.builder() .setCaption(processParaDescriptor.getCaption()) .setDescription(processParaDescriptor.getDescription()) .setWidgetType(processParaDescriptor.getWidgetType()) .setAllowShowPassword(processParaDescriptor.isAllowShowPassword()) .barcodeScannerType(processParaDescriptor.getBarcodeScannerType()) .addField(DocumentLayoutElementFieldDescriptor.builder(processParaDescriptor.getFieldName()) .setLookupInfos(processParaDescriptor.getLookupDescriptor().orElse(null)) .setPublicField(true) .setSupportZoomInto(processParaDescriptor.isSupportZoomInto())) .build(); addElement(element); return this; } public Builder addElements(@Nullable final DocumentEntityDescriptor parametersDescriptor) { if (parametersDescriptor != null) { parametersDescriptor.getFields().forEach(this::addElement); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessLayout.java
1
请完成以下Java代码
public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public GroupEntity getGroup() { return group; } public void setGroup(GroupEntity group) { this.group = group; } // required for mybatis public String getUserId(){
return user.getId(); } // required for mybatis public String getGroupId(){ return group.getId(); } @Override public String toString() { return this.getClass().getSimpleName() + "[user=" + user + ", group=" + group + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MembershipEntity.java
1
请完成以下Java代码
public ResourceLoader getResourceLoader() { return resourceLoader; } /** * @param resourceLoader * the resourceLoader to set */ public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /** * @return the webappProperty */ public WebappProperty getWebappProperty() { return webappProperty; } /** * @param webappProperty * webappProperty to set
*/ public void setWebappProperty(WebappProperty webappProperty) { this.webappProperty = webappProperty; } /** * @param input - String to trim * @param charachter - Char to trim * @return the trimmed String */ protected String trimChar(String input, char charachter) { input = StringUtils.trimLeadingCharacter(input, charachter); input = StringUtils.trimTrailingCharacter(input, charachter); return input; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\ResourceLoadingProcessEnginesFilter.java
1
请完成以下Java代码
private Optional<Quantity> getTrxCatchWeight( @NonNull final IHUContext huContext, @NonNull final Quantity qtyPicked, @NonNull final I_M_HU hu, @NonNull final I_M_HU_Trx_Line trxLine) { final AttributeId weightNetAttributeId = Services.get(IAttributeDAO.class) .getAttributeIdByCode(Weightables.ATTR_WeightNet); final List<IHUTransactionAttribute> trxAttributeCandidates = huContext.getProperty(IHUContext.PROPERTY_AttributeTrxCandidates); if (Check.isEmpty(trxAttributeCandidates)) { return Optional.empty(); } final HuId targetHUId = qtyPicked.signum() < 0 ? HuId.ofRepoId(Services.get(IHUTrxDAO.class).retrieveCounterpartTrxLine(trxLine).getM_HU_ID()) : HuId.ofRepoId(trxLine.getM_HU_ID());
final Function<BigDecimal, Quantity> toNetWeightQty = netWeight -> { final IAttributeStorage attributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final IWeightable weightable = Weightables.wrap(attributeStorage); return Quantity.of(netWeight, weightable.getWeightNetUOM()); }; return trxAttributeCandidates .stream() .filter(trx -> trx.getAttributeId().equals(weightNetAttributeId)) .filter(trx -> trx.getReferencedObject() instanceof I_M_HU) .filter(trx -> ((I_M_HU)trx.getReferencedObject()).getM_HU_ID() == targetHUId.getRepoId()) .findFirst() .map(IHUTransactionAttribute::getValueNumber) .map(toNetWeightQty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\CatchWeightHelper.java
1