instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private void handlePubrel(Channel channel, MqttMessage message) { var future = Futures.immediateVoidFuture(); if (this.client.getQos2PendingIncomingPublishes().containsKey(((MqttMessageIdVariableHeader) message.variableHeader()).messageId())) { MqttIncomingQos2Publish incomingQos2Publish = this.client.getQos2PendingIncomingPublishes().get(((MqttMessageIdVariableHeader) message.variableHeader()).messageId()); future = invokeHandlersForIncomingPublish(incomingQos2Publish.getIncomingPublish()); future = Futures.transform(future, x -> { this.client.getQos2PendingIncomingPublishes().remove(incomingQos2Publish.getIncomingPublish().variableHeader().packetId()); return null; }, MoreExecutors.directExecutor()); } future.addListener(() -> { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(((MqttMessageIdVariableHeader) message.variableHeader()).messageId()); channel.writeAndFlush(new MqttMessage(fixedHeader, variableHeader)); }, MoreExecutors.directExecutor()); } private void handlePubcomp(MqttMessage message) { MqttMessageIdVariableHeader variableHeader = (MqttMessageIdVariableHeader) message.variableHeader(); MqttPendingPublish pendingPublish = this.client.getPendingPublishes().get(variableHeader.messageId()); pendingPublish.getFuture().setSuccess(null); this.client.getPendingPublishes().remove(variableHeader.messageId()); pendingPublish.getPayload().release(); pendingPublish.onPubcompReceived(); } private void handleDisconnect(MqttMessage message) { log.debug("{} Handling DISCONNECT", client.getClientConfig().getOwnerId()); if (this.client.getCallback() != null) { this.client.getCallback().onDisconnect(message);
} } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { try { if (cause instanceof IOException) { if (log.isDebugEnabled()) { log.debug("[{}] IOException: ", client.getClientConfig().getOwnerId(), cause); } else { log.info("[{}] IOException: {}", client.getClientConfig().getOwnerId(), cause.getMessage()); } } else { log.warn("[{}] exceptionCaught", client.getClientConfig().getOwnerId(), cause); } } finally { ReferenceCountUtil.release(cause); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttChannelHandler.java
1
请完成以下Java代码
public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public BigDecimal getDiscount() { return discount; } public void setDiscount(BigDecimal discount) { this.discount = discount; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", count=").append(count); sb.append(", discount=").append(discount); sb.append(", price=").append(price); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductLadder.java
1
请在Spring Boot框架中完成以下Java代码
public class RouteProperties { /** * The Route ID. */ private @Nullable String id; /** * List of predicates for matching the Route. */ @NotEmpty @Valid private List<PredicateProperties> predicates = new ArrayList<>(); /** * List of filters to be applied to the Route. */ @Valid private List<FilterProperties> filters = new ArrayList<>(); /** * The destination URI. */ @NotNull private @Nullable URI uri; /** * Metadata associated with the Route. */ private Map<String, Object> metadata = new HashMap<>(); /** * The order of the Route, defaults to zero. */ private int order = 0; public RouteProperties() { } public RouteProperties(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { throw new ValidationException( "Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value"); } setId(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); setUri(URI.create(args[0])); for (int i = 1; i < args.length; i++) { this.predicates.add(new PredicateProperties(args[i])); } } public @Nullable String getId() { return id; } public void setId(String id) { this.id = id; } public List<PredicateProperties> getPredicates() { return predicates; } public void setPredicates(List<PredicateProperties> predicates) { this.predicates = predicates; } public List<FilterProperties> getFilters() { return filters; } public void setFilters(List<FilterProperties> filters) { this.filters = filters; } public @Nullable URI getUri() { return uri; }
public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteProperties that = (RouteProperties) o; return this.order == that.order && Objects.equals(this.id, that.id) && Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters) && Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata); } @Override public int hashCode() { return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\RouteProperties.java
2
请在Spring Boot框架中完成以下Java代码
public static class DirectExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo11Queue() { return new Queue(Demo11Message.QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Direct Exchange @Bean public DirectExchange demo11Exchange() { return new DirectExchange(Demo11Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo11Message.EXCHANGE // Routing key:Demo11Message.ROUTING_KEY // Queue:Demo11Message.QUEUE @Bean public Binding demo11Binding() {
return BindingBuilder.bind(demo11Queue()).to(demo11Exchange()).with(Demo11Message.ROUTING_KEY); } } @Bean public RabbitTransactionManager rabbitTransactionManager(ConnectionFactory connectionFactory, RabbitTemplate rabbitTemplate) { // 设置 RabbitTemplate 支持事务 rabbitTemplate.setChannelTransacted(true); // 创建 RabbitTransactionManager 对象 return new RabbitTransactionManager(connectionFactory); } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-transaction\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请在Spring Boot框架中完成以下Java代码
public long genId() { return idService.genId(); } public Id explainId( long id ) { return idService.expId(id); } public String transTime( long time ) { return idService.transTime(time).toString(); } public long makeId( long version, long type, long genMethod, long machine, long time, long seq ) { long madeId = -1; if (time == -1 || seq == -1) throw new IllegalArgumentException( "Both time and seq are required." ); else if (version == -1) { if (type == -1) { if (genMethod == -1) { if (machine == -1) { madeId = idService.makeId(time, seq); } else {
madeId = idService.makeId(machine, time, seq); } } else { madeId = idService.makeId(genMethod, machine, time, seq); } } else { madeId = idService.makeId(type, genMethod, machine, time, seq); } } else { madeId = idService.makeId(version, type, genMethod, time, seq, machine); } return madeId; } }
repos\Spring-Boot-In-Action-master\springbt_vesta\src\main\java\cn\codesheep\springbt_vesta\service\UidService.java
2
请完成以下Java代码
public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqualsAndComparable> { private String firstName; private String lastName; private LocalDate birthDate; public PersonWithEqualsAndComparable(String firstName, String lastName) { if (firstName == null || lastName == null) { throw new NullPointerException("Names can't be null"); } this.firstName = firstName; this.lastName = lastName; } public PersonWithEqualsAndComparable(String firstName, String lastName, LocalDate birthDate) { this(firstName, lastName); this.birthDate = birthDate; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public LocalDate getBirthDate() { return birthDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o; return firstName.equals(that.firstName) && lastName.equals(that.lastName) && Objects.equals(birthDate, that.birthDate); } @Override
public int hashCode() { return Objects.hash(firstName, lastName); } @Override public int compareTo(PersonWithEqualsAndComparable o) { int lastNamesComparison = this.lastName.compareTo(o.lastName); if (lastNamesComparison == 0) { int firstNamesComparison = this.firstName.compareTo(o.firstName); if (firstNamesComparison == 0) { if (this.birthDate != null && o.birthDate != null) { return this.birthDate.compareTo(o.birthDate); } else if (this.birthDate != null) { return 1; } else if (o.birthDate != null) { return -1; } else { return 0; } } else { return firstNamesComparison; } } else { return lastNamesComparison; } } }
repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\comparing\PersonWithEqualsAndComparable.java
1
请完成以下Java代码
public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; }
public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId=" + taskId + ", deploymentId=" + deploymentId + ", processDefinitionKey=" + processDefinitionKey + ", jobId=" + jobId + ", jobDefinitionId=" + jobDefinitionId + ", batchId=" + batchId + ", operationId=" + operationId + ", operationType=" + operationType + ", userId=" + userId + ", timestamp=" + timestamp + ", property=" + property + ", orgValue=" + orgValue + ", newValue=" + newValue + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", externalTaskId=" + externalTaskId + ", tenantId=" + tenantId + ", entityType=" + entityType + ", category=" + category + ", annotation=" + annotation + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:h2:mem:baeldung # JPA-Schema-Generation # Use below configuration to generate database schema create commands based on the entity models # and export them into the create.sql file #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create #spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql #spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata #spring.jpa.properties.hibernate.format_sql=true spring.jpa.show-sql=false #hibernate.d
ialect=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=create spring.jpa.properties.hibernate.id.new_generator_mappings=false spring.jta.atomikos.properties.log-base-name=atomikos-log spring.jta.log-dir=target/transaction-logs
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\resources\application.properties
2
请完成以下Java代码
private static a toLinkOrNull(final String text) { if (text == null) { return null; } final String textNorm = text.trim(); final String textLC = textNorm.toLowerCase(); if (textLC.startsWith("http://") || textLC.startsWith("https://")) { final String href; final String title; final int idx = textNorm.lastIndexOf(URL_TITLE_SEPARATOR); if (idx > 0) { href = textNorm.substring(0, idx); title = textNorm.substring(idx + URL_TITLE_SEPARATOR.length()); } else { href = textNorm; title = textNorm; } return new a(href, title); } else { return null; } } public NotificationMessageFormatter bottomUrl(final String bottomURL) { this.bottomURL = bottomURL; return this; } private String getBottomText() { if (Check.isEmpty(bottomURL, true)) { return null; } final String bottomURLText; if (html)
{ bottomURLText = new a(bottomURL, bottomURL).toString(); } else { bottomURLText = bottomURL; } String bottomText = msgBL.getTranslatableMsgText(MSG_BottomText, bottomURLText) .translate(getLanguage()); return bottomText; } // // // // // private static final class ReplaceAfterFormatCollector { private final Map<String, String> map = new HashMap<>(); public String addAndGetKey(@NonNull final String partToReplace) { final String key = "#{" + map.size() + 1 + "}"; map.put(key, partToReplace); return key; } public String replaceAll(@NonNull final String string) { if (map.isEmpty()) { return string; } String result = string; for (final Map.Entry<String, String> e : map.entrySet()) { result = result.replace(e.getKey(), e.getValue()); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\NotificationMessageFormatter.java
1
请完成以下Java代码
private static final class WebResourcePatternResolverFactory extends ResourcePatternResolverFactory { @Override public ResourcePatternResolver getResourcePatternResolver(AbstractApplicationContext applicationContext, @Nullable ResourceLoader resourceLoader) { if (applicationContext instanceof WebApplicationContext) { return getServletContextResourcePatternResolver(applicationContext, resourceLoader); } return super.getResourcePatternResolver(applicationContext, resourceLoader); } private ResourcePatternResolver getServletContextResourcePatternResolver( AbstractApplicationContext applicationContext, @Nullable ResourceLoader resourceLoader) { ResourceLoader targetResourceLoader = (resourceLoader != null) ? resourceLoader : new WebApplicationContextResourceLoader(applicationContext::getProtocolResolvers, (WebApplicationContext) applicationContext); return new ServletContextResourcePatternResolver(targetResourceLoader); } } private static class ApplicationContextResourceLoader extends DefaultResourceLoader { private final Supplier<Collection<ProtocolResolver>> protocolResolvers; ApplicationContextResourceLoader(Supplier<Collection<ProtocolResolver>> protocolResolvers) { super(null); this.protocolResolvers = protocolResolvers; } @Override public Collection<ProtocolResolver> getProtocolResolvers() { return this.protocolResolvers.get(); } } /** * {@link ResourceLoader} that optionally supports {@link ServletContextResource * ServletContextResources}.
*/ private static class WebApplicationContextResourceLoader extends ApplicationContextResourceLoader { private final WebApplicationContext applicationContext; WebApplicationContextResourceLoader(Supplier<Collection<ProtocolResolver>> protocolResolvers, WebApplicationContext applicationContext) { super(protocolResolvers); this.applicationContext = applicationContext; } @Override protected Resource getResourceByPath(String path) { if (this.applicationContext.getServletContext() != null) { return new ServletContextResource(this.applicationContext.getServletContext(), path); } return super.getResourceByPath(path); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\ClassLoaderFilesResourcePatternResolver.java
1
请完成以下Java代码
public static boolean sortAndThenCheck(String str) { char[] chars = str.toUpperCase().toCharArray(); Arrays.sort(chars); for (int i = 0; i < chars.length - 1; i++) { if(chars[i] == chars[i+1]) { return false; } } return true; } public static boolean useSetCheck(String str) { char[] chars = str.toUpperCase().toCharArray(); Set <Character> set = new HashSet <>(); for (char c: chars) { if (!set.add(c)) { return false; } } return true; } public static boolean useStreamCheck(String str) {
boolean isUnique = str.toUpperCase().chars() .mapToObj(c -> (char)c) .collect(Collectors.toSet()) .size() == str.length(); return isUnique; } public static boolean useStringUtilscheck(String str) { for (int i = 0; i < str.length(); i++) { String curChar = String.valueOf(str.charAt(i)); String remainingStr = str.substring(i+1); if(StringUtils.containsIgnoreCase(remainingStr, curChar)) { return false; } } return true; } }
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\uniquecharcheck\UniqueCharChecker.java
1
请完成以下Java代码
public class UserResponse { private Long id; private String username; private String name; private String phone; private String email; private String city; public UserResponse(User user){ this.id = user.getId();
this.username = user.getUsername(); this.name = user.getName(); this.phone = user.getPhone(); this.email = user.getEmail(); this.city = user.getCity(); } public UserResponse(Long id, String username, String name, String phone, String email) { this.id = id; this.username = username; this.phone = phone; this.email = email; } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\payload\user\UserResponse.java
1
请在Spring Boot框架中完成以下Java代码
public java.lang.String getRequestURI() { return get_ValueAsString(COLUMNNAME_RequestURI); } @Override public void setResponseBody (final @Nullable java.lang.String ResponseBody) { set_Value (COLUMNNAME_ResponseBody, ResponseBody); } @Override public java.lang.String getResponseBody() { return get_ValueAsString(COLUMNNAME_ResponseBody); } @Override public void setResponseCode (final int ResponseCode) { set_Value (COLUMNNAME_ResponseCode, ResponseCode); } @Override public int getResponseCode() { return get_ValueAsInt(COLUMNNAME_ResponseCode); } @Override public void setSUMUP_API_Log_ID (final int SUMUP_API_Log_ID) { if (SUMUP_API_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_API_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_API_Log_ID, SUMUP_API_Log_ID); } @Override public int getSUMUP_API_Log_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_API_Log_ID); } @Override
public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config() { return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class); } @Override public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config) { set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } @Override public void setSUMUP_merchant_code (final @Nullable java.lang.String SUMUP_merchant_code) { set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code); } @Override public java.lang.String getSUMUP_merchant_code() { return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_API_Log.java
2
请完成以下Java代码
private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { logRequest(request, body); ClientHttpResponse response = execution.execute(request, body); logResponse(response); return response; } private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { log.info("URI: " + request.getURI()); log.info("HTTP Method: " + request.getMethod()); log.info("HTTP Headers: " + headersToString(request.getHeaders())); log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); } private void logResponse(ClientHttpResponse response) throws IOException { log.info("HTTP Status Code: " + response.getRawStatusCode()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); } private String headersToString(HttpHeaders headers) {
StringBuilder builder = new StringBuilder(); for(Entry<String, List<String>> entry : headers.entrySet()) { builder.append(entry.getKey()).append("=["); for(String value : entry.getValue()) { builder.append(value).append(","); } builder.setLength(builder.length() - 1); // Get rid of trailing comma builder.append("],"); } builder.setLength(builder.length() - 1); // Get rid of trailing comma return builder.toString(); } private String bodyToString(InputStream body) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); String line = bufferedReader.readLine(); while (line != null) { builder.append(line).append(System.lineSeparator()); line = bufferedReader.readLine(); } bufferedReader.close(); return builder.toString(); } } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\invoker\ApiClient.java
1
请完成以下Java代码
public String getSummary() { final StringBuilder sb = new StringBuilder(); sb.append(getDocumentNo()); // : Grand Total = 123.00 (#1) sb.append(": ").append(Services.get(IMsgBL.class).translate(getCtx(), "GrandTotal")).append("=").append(getGrandTotal()); final List<MOrderLine> lines = _lines; if (lines != null) { sb.append(" (#").append(lines.size()).append(")"); } // - Description if (getDescription() != null && getDescription().length() > 0) { sb.append(" - ").append(getDescription()); } return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateOrdered()); } /** * Get Process Message * * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible)
*/ @Override public int getDoc_User_ID() { return getSalesRep_ID(); } /** * Get Document Approval Amount * * @return amount */ @Override public BigDecimal getApprovalAmt() { return getGrandTotal(); } // getApprovalAmt /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { final DocStatus docStatus = DocStatus.ofCode(getDocStatus()); return docStatus.isCompletedOrClosedOrReversed(); } // isComplete } // MOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MOrder.java
1
请在Spring Boot框架中完成以下Java代码
public String getFilename() { return this.resource.getFilename(); } @Override public String getDescription() { return this.resource.getDescription(); } } } private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { CriteriaSetResolverWrapper(MetadataResolver metadataResolver) {
super(metadataResolver); } @Override EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); } @Override Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception { return super.metadataResolver.resolve(new CriteriaSet(role)); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
2
请完成以下Java代码
protected boolean isUseForward() { return this.forwardToDestination; } /** * If set to <tt>true</tt>, performs a forward to the failure destination URL instead * of a redirect. Defaults to <tt>false</tt>. */ public void setUseForward(boolean forwardToDestination) { this.forwardToDestination = forwardToDestination; } /** * Allows overriding of the behaviour when redirecting to a target URL. */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy;
} protected RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } protected boolean isAllowSessionCreation() { return this.allowSessionCreation; } public void setAllowSessionCreation(boolean allowSessionCreation) { this.allowSessionCreation = allowSessionCreation; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SimpleUrlAuthenticationFailureHandler.java
1
请完成以下Java代码
public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestID (final java.lang.String RequestID) { set_Value (COLUMNNAME_RequestID, RequestID); } @Override public java.lang.String getRequestID() { return get_ValueAsString(COLUMNNAME_RequestID); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); }
@Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Log.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } /** * Determine when the task executor is to be created. * * @since 3.5.0 */
public enum Mode { /** * Create the task executor if no user-defined executor is present. */ AUTO, /** * Create the task executor even if a user-defined executor is present. */ FORCE } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskExecutionProperties.java
2
请完成以下Java代码
protected I_AD_MigrationStep createMigrationStep(final IMigrationLoggerContext migrationCtx, final PO po, final String event) { final I_AD_MigrationStep migrationStep = createMigrationStep(migrationCtx, po); migrationStep.setStepType(X_AD_MigrationStep.STEPTYPE_ApplicationDictionary); migrationStep.setAction(event); migrationStep.setAD_Table_ID(po.get_Table_ID()); migrationStep.setTableName(po.get_TableName()); migrationStep.setRecord_ID(po.get_ID()); Services.get(IMigrationBL.class).setSeqNo(migrationStep); InterfaceWrapperHelper.save(migrationStep); return migrationStep; } private I_AD_Migration getCreateMigration(final IMigrationLoggerContext mctx, final String entityType) { String entityTypeActual = entityType; if (entityTypeActual == null) { entityTypeActual = getDefaultEntityType(); } final String key = entityTypeActual; I_AD_Migration migration = mctx.getMigration(key); if (migration == null || !migration.isActive()) // migration was closed, open another one { migration = createMigration(Env.getCtx(), entityTypeActual); mctx.putMigration(key, migration); } return migration; } protected I_AD_Migration createMigration(final Properties ctx, final String entityType) { // this record shall be created out of transaction since it will accessible in more then one transaction final String trxName = null; final I_AD_Migration migration = InterfaceWrapperHelper.create(ctx, I_AD_Migration.class, trxName);
migration.setEntityType(entityType); Services.get(IMigrationBL.class).setSeqNo(migration); setName(migration); InterfaceWrapperHelper.save(migration); return migration; } protected void setName(final I_AD_Migration migration) { final String name = Services.get(ISysConfigBL.class).getValue("DICTIONARY_ID_COMMENTS"); migration.setName(name); } protected String getDefaultEntityType() { boolean dict = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); return dict ? "D" : "U"; } protected IMigrationLoggerContext getSessionMigrationLoggerContext(final MFSession session) { final String key = getClass().getCanonicalName(); IMigrationLoggerContext mctx = session.getTransientProperty(key); if (mctx == null) { mctx = new SessionMigrationLoggerContext(); session.putTransientProperty(key, mctx); } return mctx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\MigrationLogger.java
1
请完成以下Java代码
public String getName() { return (String) get(1); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached StoreRecord
*/ public StoreRecord() { super(Store.STORE); } /** * Create a detached, initialised StoreRecord */ public StoreRecord(Integer id, String name) { super(Store.STORE); setId(id); setName(name); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\StoreRecord.java
1
请完成以下Java代码
public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void setIsStdUserWorkflow (final boolean IsStdUserWorkflow) { set_Value (COLUMNNAME_IsStdUserWorkflow, IsStdUserWorkflow); } @Override public boolean isStdUserWorkflow() { return get_ValueAsBoolean(COLUMNNAME_IsStdUserWorkflow); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() {
return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTransitionCode (final java.lang.String TransitionCode) { set_Value (COLUMNNAME_TransitionCode, TransitionCode); } @Override public java.lang.String getTransitionCode() { return get_ValueAsString(COLUMNNAME_TransitionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NodeNext.java
1
请完成以下Java代码
public class RefreshTokenProcessingFilter extends AbstractAuthenticationProcessingFilter { private final AuthenticationSuccessHandler successHandler; private final AuthenticationFailureHandler failureHandler; public RefreshTokenProcessingFilter(String defaultProcessUrl, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) { super(defaultProcessUrl); this.successHandler = successHandler; this.failureHandler = failureHandler; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if (log.isDebugEnabled()) { log.debug("Authentication method not supported. Request method: {}", request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } RefreshTokenRequest refreshTokenRequest; try { refreshTokenRequest = JacksonUtil.fromReader(request.getReader(), RefreshTokenRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid refresh token request payload"); } if (refreshTokenRequest == null || StringUtils.isBlank(refreshTokenRequest.refreshToken())) { throw new AuthenticationServiceException("Refresh token is not provided"); } RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.refreshToken());
return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token)); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { successHandler.onAuthenticationSuccess(request, response, authResult); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); failureHandler.onAuthenticationFailure(request, response, failed); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\RefreshTokenProcessingFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof DataSource && !(bean instanceof ProxyDataSource)) { // Instead of directly returning a less specific datasource bean // (e.g.: HikariDataSource -> DataSource), return a proxy object. // See following links for why: // https://stackoverflow.com/questions/44237787/how-to-use-user-defined-database-proxy-in-datajpatest // https://gitter.im/spring-projects/spring-boot?at=5983602d2723db8d5e70a904 // http://blog.arnoldgalovics.com/2017/06/26/configuring-a-datasource-proxy-in-spring-boot/ final ProxyFactory factory = new ProxyFactory(bean); factory.setProxyTargetClass(true); factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); return factory.getProxy(); } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } private static class ProxyDataSourceInterceptor implements MethodInterceptor { private final DataSource dataSource;
public ProxyDataSourceInterceptor(final DataSource dataSource) { this.dataSource = ProxyDataSourceBuilder.create(dataSource) .name("MyDS") .multiline() .logQueryBySlf4j(SLF4JLogLevel.DEBUG) .listener(new DataSourceQueryCountListener()) .build(); } @Override public Object invoke(final MethodInvocation invocation) throws Throwable { final Method proxyMethod = ReflectionUtils.findMethod(this.dataSource.getClass(), invocation.getMethod().getName()); if (proxyMethod != null) { return proxyMethod.invoke(this.dataSource, invocation.getArguments()); } return invocation.proceed(); } } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2db\lazy_load_no_trans\config\DatasourceProxyBeanPostProcessor.java
2
请完成以下Java代码
public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_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 setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_ValueNoCheck (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt) { set_ValueNoCheck (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt); } @Override public BigDecimal getPlannedMarginAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedPrice (final BigDecimal PlannedPrice) { set_ValueNoCheck (COLUMNNAME_PlannedPrice, PlannedPrice); } @Override public BigDecimal getPlannedPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedQty (final BigDecimal PlannedQty) { set_ValueNoCheck (COLUMNNAME_PlannedQty, PlannedQty); }
@Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setSKU (final @Nullable java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); } @Override public java.lang.String getSKU() { return get_ValueAsString(COLUMNNAME_SKU); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
1
请在Spring Boot框架中完成以下Java代码
public synchronized String update(RouteDefinition definition) { try { log.info("gateway update route {}", definition); } catch (Exception e) { return "update fail,not find route routeId: " + definition.getId(); } try { repository.save(Mono.just(definition)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); return "success"; } catch (Exception e) { return "update route fail"; } } /**
* 增加路由 * * @param definition * @return */ public synchronized String add(RouteDefinition definition) { log.info("gateway add route {}", definition); try { repository.save(Mono.just(definition)).subscribe(); } catch (Exception e) { log.warn(e.getMessage(),e); } return "success"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\repository\DynamicRouteService.java
2
请完成以下Java代码
public void setGroups(List<String> groups) { this.groups = groups; } public List<String> getUsers() { return users; } public void setUsers(List<String> users) { this.users = users; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; }
public SecurityPolicyAccess getAccess() { return access; } public void setAccess(SecurityPolicyAccess access) { this.access = access; } public List<String> getKeys() { return keys; } public void setKeys(List<String> keys) { this.keys = keys; } }
repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\SecurityPolicy.java
1
请完成以下Java代码
public List<V> remove(final Object key) { return map.remove(key); } @Override public void putAll(Map<? extends K, ? extends List<V>> m) { map.putAll(m); } @Override public void clear() { map.clear(); } @Override public Set<K> keySet() { return map.keySet();
} @Override public Collection<List<V>> values() { return map.values(); } @Override public Set<Map.Entry<K, List<V>>> entrySet() { return map.entrySet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MultiValueMap.java
1
请在Spring Boot框架中完成以下Java代码
public int rightMostModifier(int index) { return (rightMostArcs[index] == 0 ? -1 : rightMostArcs[index]); } public int leftMostModifier(int index) { return (leftMostArcs[index] == 0 ? -1 : leftMostArcs[index]); } /** * @param head * @return the current index of dependents */ public int valence(int head) { return rightValency(head) + leftValency(head); } /** * @param head * @return the current index of right modifiers */ public int rightValency(int head) { return rightValency[head]; } /** * @param head * @return the current index of left modifiers */ public int leftValency(int head) { return leftValency[head]; } public int getHead(int index) { if (arcs[index] != null) return arcs[index].headIndex; return -1; } public int getDependent(int index) { if (arcs[index] != null) return arcs[index].relationId; return -1; } public void setMaxSentenceSize(int maxSentenceSize) { this.maxSentenceSize = maxSentenceSize; } public void incrementBufferHead() { if (bufferHead == maxSentenceSize)
bufferHead = -1; else bufferHead++; } public void setBufferHead(int bufferHead) { this.bufferHead = bufferHead; } @Override public State clone() { State state = new State(arcs.length - 1); state.stack = new ArrayDeque<Integer>(stack); for (int dependent = 0; dependent < arcs.length; dependent++) { if (arcs[dependent] != null) { Edge head = arcs[dependent]; state.arcs[dependent] = head; int h = head.headIndex; if (rightMostArcs[h] != 0) { state.rightMostArcs[h] = rightMostArcs[h]; state.rightValency[h] = rightValency[h]; state.rightDepLabels[h] = rightDepLabels[h]; } if (leftMostArcs[h] != 0) { state.leftMostArcs[h] = leftMostArcs[h]; state.leftValency[h] = leftValency[h]; state.leftDepLabels[h] = leftDepLabels[h]; } } } state.rootIndex = rootIndex; state.bufferHead = bufferHead; state.maxSentenceSize = maxSentenceSize; state.emptyFlag = emptyFlag; return state; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\State.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Category category = (Category) o; return Objects.equals(this.id, category.id) && Objects.equals(this.name, category.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Category.java
1
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set User Query. @param AD_UserQuery_ID Saved User Query */ @Override public void setAD_UserQuery_ID (int AD_UserQuery_ID) { if (AD_UserQuery_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UserQuery_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UserQuery_ID, Integer.valueOf(AD_UserQuery_ID)); } /** Get User Query. @return Saved User Query */ @Override public int getAD_UserQuery_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserQuery_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validierungscode. @param Code Validation Code */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validierungscode. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Mandatory Parameters. @param IsManadatoryParams Mandatory Parameters */ @Override public void setIsManadatoryParams (boolean IsManadatoryParams) { set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams)); } /** Get Mandatory Parameters. @return Mandatory Parameters */ @Override public boolean isManadatoryParams () { Object oo = get_Value(COLUMNNAME_IsManadatoryParams); if (oo != null)
{ if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Display All Parameters. @param IsShowAllParams Display All Parameters */ @Override public void setIsShowAllParams (boolean IsShowAllParams) { set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams)); } /** Get Display All Parameters. @return Display All Parameters */ @Override public boolean isShowAllParams () { Object oo = get_Value(COLUMNNAME_IsShowAllParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
1
请完成以下Java代码
public class TransactionCommandContextCloseListener implements CommandContextCloseListener { protected TransactionContext transactionContext; public TransactionCommandContextCloseListener(TransactionContext transactionContext) { this.transactionContext = transactionContext; } @Override public void closing(CommandContext commandContext) { } @Override public void afterSessionsFlush(CommandContext commandContext) { transactionContext.commit(); } @Override public void closed(CommandContext commandContext) {
} @Override public void closeFailure(CommandContext commandContext) { transactionContext.rollback(); } @Override public Integer order() { return 10000; } @Override public boolean multipleAllowed() { return false; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\TransactionCommandContextCloseListener.java
1
请完成以下Java代码
public Object getPrincipal() { return this.clientPrincipal; } @Override public Object getCredentials() { return ""; } /** * Returns the token. * @return the token */ public String getToken() { return this.token; } /** * Returns the token type hint. * @return the token type hint */ @Nullable public String getTokenTypeHint() { return this.tokenTypeHint; } /**
* Returns the additional parameters. * @return the additional parameters */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } /** * Returns the token claims. * @return the {@link OAuth2TokenIntrospection} */ public OAuth2TokenIntrospection getTokenClaims() { return this.tokenClaims; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenIntrospectionAuthenticationToken.java
1
请完成以下Java代码
public final boolean isReadOnly(Bindings bindings, ELContext context) { return true; } /** * non-lvalues are always readonly, so throw an exception */ @Override public final void setValue(Bindings bindings, ELContext context, Object value) { throw new ELException(LocalMessages.get("error.value.set.rvalue", getStructuralId(bindings))); } @Override public final MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return null; } @Override public final Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) { throw new ELException(LocalMessages.get("error.method.invalid", getStructuralId(bindings))); }
@Override public final boolean isLeftValue() { return false; } @Override public boolean isMethodInvocation() { return false; } @Override public final ValueReference getValueReference(Bindings bindings, ELContext context) { return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstRightValue.java
1
请在Spring Boot框架中完成以下Java代码
protected String getRedisNamespace() { return this.redisNamespace; } public void setFlushMode(FlushMode flushMode) { Assert.notNull(flushMode, "flushMode must not be null"); this.flushMode = flushMode; } protected FlushMode getFlushMode() { return this.flushMode; } public void setSaveMode(SaveMode saveMode) { Assert.notNull(saveMode, "saveMode must not be null"); this.saveMode = saveMode; } protected SaveMode getSaveMode() { return this.saveMode; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<RedisConnectionFactory> redisConnectionFactory) { this.redisConnectionFactory = springSessionRedisConnectionFactory .getIfAvailable(redisConnectionFactory::getObject); } protected RedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } protected RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; } @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() {
return this.sessionRepositoryCustomizers; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected RedisTemplate<String, Object> createRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); if (getDefaultRedisSerializer() != null) { redisTemplate.setDefaultSerializer(getDefaultRedisSerializer()); } redisTemplate.setConnectionFactory(getRedisConnectionFactory()); redisTemplate.setBeanClassLoader(this.classLoader); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter { private final PasswordEncoder passwordEncoder; @Autowired public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, jwtSecretKey)) .addFilterAfter(new JwtTokenVerifier(), JwtUsernameAndPasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers("/", "index", "/css/*", "/js/*").permitAll() .antMatchers("/api/**").hasRole(ADMIN.name()) // managing role here based on enum categories. .anyRequest() .authenticated(); } @Override @Bean protected UserDetailsService userDetailsService() { // Permission User(s) UserDetails urunovUser = User.builder() .username("urunov") .password(passwordEncoder.encode("urunov1987")) .roles(ADMIN.name()) // ROLE_STUDENT .build(); UserDetails lindaUser = User.builder() .username("linda") .password(passwordEncoder.encode("linda333")) .authorities(STUDENT.name()) .roles(STUDENT.name()) // ROLE_ADMIN .build(); UserDetails tomUser = User.builder() .username("tom") .password(passwordEncoder.encode("tom555"))
.authorities(ADMINTRAINEE.name()) // .authorities(ADMINTRAINEE.getGrantedAuthorities()) .roles(ADMINTRAINEE.name()) // ROLE ADMINTRAINEE .build(); // UserDetails hotamboyUser = User.builder() .username("hotam") .password(passwordEncoder.encode("hotamboy")) .authorities(ADMIN.name()) // .authorities(ADMIN.getGrantedAuthorities()) .roles(ADMIN.name()) // ROLE ADMIN .build(); return new InMemoryUserDetailsManager( urunovUser, lindaUser, tomUser, hotamboyUser ); } }
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\jwt-secure\spring-jwt-secure\src\main\java\uz\bepro\springjwtsecure\security\ApplicationSecurityConfig.java
2
请完成以下Java代码
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) { Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } if (request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken) { parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE); parameters.put("error_description", "The request requires higher privileges than provided by the access token."); parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1"); } String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatus(HttpStatus.FORBIDDEN.value()); } /** * Set the default realm name to use in the bearer token error response * @param realmName */ public void setRealmName(String realmName) { this.realmName = realmName; }
private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry<String, String> entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } return wwwAuthenticate.toString(); } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\access\BearerTokenAccessDeniedHandler.java
1
请完成以下Java代码
private String buildMessage() { final StringBuilder out = new StringBuilder(); final String adMessageTrl = getAD_Message_Translated(); if (!Check.isEmpty(adMessageTrl)) { out.append(adMessageTrl); } final String additionalMessage = getAdditionalMessage(); if (!Check.isEmpty(additionalMessage)) { out.append("\n").append(additionalMessage); } return out.toString(); } private Properties getCtx() { return Env.getCtx(); } @Override public IAskDialogBuilder setParentComponent(final Object parentCompObj) { this._parentCompObj = parentCompObj; return this; } @Override public IAskDialogBuilder setParentWindowNo(final int windowNo) { this._parentWindowNo = windowNo; return this; } private Window getParentWindowOrNull() { Window parent = null; if (_parentCompObj instanceof Component) { parent = SwingUtils.getParentWindow((Component)_parentCompObj); } if (parent == null && Env.isRegularOrMainWindowNo(_parentWindowNo)) { parent = Env.getWindow(_parentWindowNo); } return parent; } @Override
public IAskDialogBuilder setAD_Message(final String adMessage, Object ... params) { this._adMessage = adMessage; this._adMessageParams = params; return this; } private String getAD_Message_Translated() { if (Check.isEmpty(_adMessage, true)) { return ""; } final Properties ctx = getCtx(); if (Check.isEmpty(_adMessageParams)) { return msgBL.getMsg(ctx, _adMessage); } else { return msgBL.getMsg(ctx, _adMessage, _adMessageParams); } } @Override public IAskDialogBuilder setAdditionalMessage(final String additionalMessage) { this._additionalMessage = additionalMessage; return this; } private String getAdditionalMessage() { return this._additionalMessage; } @Override public IAskDialogBuilder setDefaultAnswer(final boolean defaultAnswer) { this._defaultAnswer = defaultAnswer; return this; } private boolean getDefaultAnswer() { return this._defaultAnswer; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingAskDialogBuilder.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; } public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } @Override public void setRevision(int revision) {
this.revision = revision; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public boolean hasEditorSource() { return this.editorSourceValueId != null; } @Override public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntity.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsMenuRoleServiceImpl implements PmsMenuRoleService { @Autowired private PmsMenuRoleDao pmsMenuRoleDao; /** * 根据角色ID统计关联到此角色的菜单数. * * @param roleId * 角色ID. * @return count. */ public int countMenuByRoleId(Long roleId) { List<PmsMenuRole> meunList = pmsMenuRoleDao.listByRoleId(roleId); if (meunList == null || meunList.isEmpty()) { return 0; } else { return meunList.size(); } } /** * 根据角色id,删除该角色关联的所有菜单权限 * * @param roleId */ public void deleteByRoleId(Long roleId) { pmsMenuRoleDao.deleteByRoleId(roleId);
} @Transactional(rollbackFor = Exception.class) public void saveRoleMenu(Long roleId, String roleMenuStr){ // 删除原来的角色与权限关联 pmsMenuRoleDao.deleteByRoleId(roleId); if (!StringUtils.isEmpty(roleMenuStr)) { // 创建新的关联 String[] menuIds = roleMenuStr.split(","); for (int i = 0; i < menuIds.length; i++) { Long menuId = Long.valueOf(menuIds[i]); PmsMenuRole item = new PmsMenuRole(); item.setMenuId(menuId); item.setRoleId(roleId); pmsMenuRoleDao.insert(item); } } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuRoleServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
default @Nullable MasterReplica getMasterReplica() { return null; } /** * Redis standalone configuration. */ interface Standalone { /** * Redis server host. * @return the redis server host */ String getHost(); /** * Redis server port. * @return the redis server port */ int getPort(); /** * Database index used by the connection factory. * @return the database index used by the connection factory */ default int getDatabase() { return 0; } /** * Creates a new instance with the given host and port. * @param host the host * @param port the port * @return the new instance */ static Standalone of(String host, int port) { return of(host, port, 0); } /** * Creates a new instance with the given host, port and database. * @param host the host * @param port the port * @param database the database * @return the new instance */ static Standalone of(String host, int port, int database) { Assert.hasLength(host, "'host' must not be empty"); return new Standalone() { @Override public String getHost() { return host; } @Override public int getPort() { return port; } @Override public int getDatabase() { return database; } }; } } /** * Redis sentinel configuration. */ interface Sentinel { /** * Database index used by the connection factory. * @return the database index used by the connection factory */ int getDatabase(); /** * Name of the Redis server. * @return the name of the Redis server */ String getMaster(); /** * List of nodes. * @return the list of nodes */ List<Node> getNodes(); /** * Login username for authenticating with sentinel(s). * @return the login username for authenticating with sentinel(s) or {@code null} */ @Nullable String getUsername(); /** * Password for authenticating with sentinel(s). * @return the password for authenticating with sentinel(s) or {@code null}
*/ @Nullable String getPassword(); } /** * Redis cluster configuration. */ interface Cluster { /** * Nodes to bootstrap from. This represents an "initial" list of cluster nodes and * is required to have at least one entry. * @return nodes to bootstrap from */ List<Node> getNodes(); } /** * Redis master replica configuration. */ interface MasterReplica { /** * Static nodes to use. This represents the full list of cluster nodes and is * required to have at least one entry. * @return the nodes to use */ List<Node> getNodes(); } /** * A node in a sentinel or cluster configuration. * * @param host the hostname of the node * @param port the port of the node */ record Node(String host, int port) { } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionDetails.java
2
请完成以下Java代码
public BigDecimal getQty() { return quantity.toBigDecimal(); } @Override public boolean isZeroQty() { return quantity.isZero(); } @Override public boolean isInfiniteQty() { return quantity.isInfinite(); } @Override public I_C_UOM getC_UOM()
{ return quantity.getUOM(); } @Override public TableRecordReference getReference() { return fromTableRecord; } @Override public boolean isDeleteEmptyAndJustCreatedAggregatedTUs() { return deleteEmptyAndJustCreatedAggregatedTUs; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequest.java
1
请完成以下Java代码
public void setUOMSymbol (String UOMSymbol) { set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol); } /** Get Symbol. @return Symbol for a Unit of Measure */ public String getUOMSymbol () { return (String)get_Value(COLUMNNAME_UOMSymbol); } /** Set UPC/EAN. @param UPC Bar Code (Universal Product Code or its superset European Article Number) */ public void setUPC (String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN. @return Bar Code (Universal Product Code or its superset European Article Number) */ public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value);
} /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Warehouse. @param WarehouseName Warehouse Name */ public void setWarehouseName (String WarehouseName) { set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName); } /** Get Warehouse. @return Warehouse Name */ public String getWarehouseName () { return (String)get_Value(COLUMNNAME_WarehouseName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
1
请在Spring Boot框架中完成以下Java代码
public RpAccountHistory getAccountHistoryByAccountNo_requestNo_trxType(String accountNo, String requestNo, Integer trxType) { Map<String, Object> map = new HashMap<String, Object>(); map.put("accountNo", accountNo); map.put("requestNo", requestNo); map.put("trxType", trxType); return rpAccountHistoryDao.getBy(map); } /** * 日汇总账户待结算金额 . * * @param accountNo * 账户编号 * @param statDate * 统计日期 * @param riskDay * 风险预测期 * @param fundDirection * 资金流向 * @return */ public List<DailyCollectAccountHistoryVo> listDailyCollectAccountHistoryVo(String accountNo, String statDate, Integer riskDay, Integer fundDirection) { Map<String, Object> params = new HashMap<String, Object>(); params.put("accountNo", accountNo); params.put("statDate", statDate); params.put("riskDay", riskDay); params.put("fundDirection", fundDirection); return rpAccountHistoryDao.listDailyCollectAccountHistoryVo(params); } /** * 根据参数分页查询账户. * * @param pageParam * 分页参数.
* @param params * 查询参数,可以为null. * @return AccountList. * @throws BizException */ public PageBean queryAccountListPage(PageParam pageParam, Map<String, Object> params) { return rpAccountDao.listPage(pageParam, params); } /** * 根据参数分页查询账户历史. * * @param pageParam * 分页参数. * @param params * 查询参数,可以为null. * @return AccountHistoryList. * @throws BizException */ public PageBean queryAccountHistoryListPage(PageParam pageParam, Map<String, Object> params) { return rpAccountHistoryDao.listPage(pageParam, params); } /** * 获取所有账户 * @return */ @Override public List<RpAccount> listAll(){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpAccountDao.listBy(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpAccountQueryServiceImpl.java
2
请完成以下Java代码
public void setIsGroupBy (final boolean IsGroupBy) { set_Value (COLUMNNAME_IsGroupBy, IsGroupBy); } @Override public boolean isGroupBy() { return get_ValueAsBoolean(COLUMNNAME_IsGroupBy); } @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 setOffsetName (final @Nullable java.lang.String OffsetName) { set_Value (COLUMNNAME_OffsetName, OffsetName); } @Override public java.lang.String getOffsetName() { return get_ValueAsString(COLUMNNAME_OffsetName); } @Override public void setSQL_Select (final @Nullable java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } @Override public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol) { set_Value (COLUMNNAME_UOMSymbol, UOMSymbol); } @Override public java.lang.String getUOMSymbol() { return get_ValueAsString(COLUMNNAME_UOMSymbol); } @Override public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID) { if (WEBUI_KPI_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID);
} @Override public int getWEBUI_KPI_Field_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class); } @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java
1
请在Spring Boot框架中完成以下Java代码
public String getPostIds(String tenantId, String postNames) { return null; } @Override public List<String> getPostNames(String postIds) { return null; } @Override public Role getRole(Long id) { return null; } @Override public String getRoleIds(String tenantId, String roleNames) { return null; } @Override public String getRoleName(Long id) { return null; } @Override public List<String> getRoleNames(String roleIds) { return null; }
@Override public String getRoleAlias(Long id) { return null; } @Override public R<Tenant> getTenant(Long id) { return null; } @Override public R<Tenant> getTenant(String tenantId) { return null; } }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\feign\ISysClientFallback.java
2
请完成以下Java代码
public class DebugSettings { private static DebugSettings DEBUG_OFF = new DebugSettings(false, 0); private static DebugSettings DEBUG_FAILURES = new DebugSettings(true, 0); public DebugSettings(boolean failuresEnabled, long allEnabledUntil) { this.failuresEnabled = failuresEnabled; this.allEnabled = false; this.allEnabledUntil = allEnabledUntil; } @Schema(description = "Debug failures. ", example = "false") private boolean failuresEnabled; @Schema(description = "Debug All. Used as a trigger for updating debugAllUntil.", example = "false") private boolean allEnabled; @Schema(description = "Timestamp of the end time for the processing debug events.") private long allEnabledUntil; public static DebugSettings off() {return DebugSettings.DEBUG_OFF;} public static DebugSettings failures() {return DebugSettings.DEBUG_FAILURES;}
public static DebugSettings until(long ts) {return new DebugSettings(false, ts);} public static DebugSettings failuresOrUntil(long ts) {return new DebugSettings(true, ts);} public static DebugSettings all() { var ds = new DebugSettings(); ds.setAllEnabled(true); return ds; } public DebugSettings copy(long maxDebugAllUntil) { return new DebugSettings(failuresEnabled, allEnabled ? maxDebugAllUntil : Math.min(allEnabledUntil, maxDebugAllUntil)); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\debug\DebugSettings.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setIsArchived (final boolean IsArchived) { set_Value (COLUMNNAME_IsArchived, IsArchived); } @Override public boolean isArchived() { return get_ValueAsBoolean(COLUMNNAME_IsArchived); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @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); } @Override public void setTitleShort (final @Nullable java.lang.String TitleShort) { set_Value (COLUMNNAME_TitleShort, TitleShort); } @Override public java.lang.String getTitleShort() { return get_ValueAsString(COLUMNNAME_TitleShort); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_Alberta.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Point.class, DC_ELEMENT_POINT) .namespaceUri(DC_NS) .instanceProvider(new ModelTypeInstanceProvider<Point>() { public Point newInstance(ModelTypeInstanceContext instanceContext) { return new PointImpl(instanceContext); } }); xAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_X) .required() .build(); yAttribute = typeBuilder.doubleAttribute(DC_ATTRIBUTE_Y) .required() .build(); typeBuilder.build(); } public PointImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext);
} public Double getX() { return xAttribute.getValue(this); } public void setX(double x) { xAttribute.setValue(this, x); } public Double getY() { return yAttribute.getValue(this); } public void setY(double y) { yAttribute.setValue(this, y); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\dc\PointImpl.java
1
请完成以下Java代码
public class AddPrivilegeMappingCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected IdmEngineConfiguration idmEngineConfiguration; protected String privilegeId; protected String userId; protected String groupId; public AddPrivilegeMappingCmd(String privilegeId, String userId, String groupId, IdmEngineConfiguration idmEngineConfiguration) { this.privilegeId = privilegeId; this.userId = userId; this.groupId = groupId; this.idmEngineConfiguration = idmEngineConfiguration; }
@Override public Void execute(CommandContext commandContext) { PrivilegeMappingEntityManager privilegeMappingEntityManager = idmEngineConfiguration.getPrivilegeMappingEntityManager(); PrivilegeMappingEntity entity = privilegeMappingEntityManager.create(); entity.setPrivilegeId(privilegeId); if (userId != null) { entity.setUserId(userId); } else if (groupId != null) { entity.setGroupId(groupId); } privilegeMappingEntityManager.insert(entity); return null; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\cmd\AddPrivilegeMappingCmd.java
1
请完成以下Java代码
private void recomputeCosts( @NonNull final CostElement costElement, @NonNull final PInstanceId productsSelectionId, @NonNull final Instant startDate) { DB.executeFunctionCallEx(getTrxName() , "select \"de_metas_acct\".product_costs_recreate_from_date( p_C_AcctSchema_ID :=" + getAccountingSchemaId().getRepoId() + ", p_M_CostElement_ID:=" + costElement.getId().getRepoId() + ", p_m_product_selection_id:=" + productsSelectionId.getRepoId() + " , p_ReorderDocs_DateAcct_Trunc:='MM'" + ", p_StartDateAcct:=" + DB.TO_SQL(startDate) + "::date)" // , null // ); } private Instant getStartDate() { return inventoryDAO.getMinInventoryDate(getSelectedInventoryIds())
.orElseThrow(() -> new AdempiereException("Cannot determine Start Date")); } private List<CostElement> getCostElements() { if (p_costingMethod != null) { return costElementRepository.getMaterialCostingElementsForCostingMethod(p_costingMethod); } return costElementRepository.getActiveMaterialCostingElements(getClientID()); } private AcctSchemaId getAccountingSchemaId() {return p_C_AcctSchema_ID;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\process\M_Inventory_RecomputeCosts.java
1
请完成以下Java代码
public void setWorkingTime (final int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } @Override public int getWorkingTime() { return get_ValueAsInt(COLUMNNAME_WorkingTime); } @Override public void setXPosition (final int XPosition) { set_Value (COLUMNNAME_XPosition, XPosition); } @Override public int getXPosition() { return get_ValueAsInt(COLUMNNAME_XPosition); } @Override public void setYield (final int Yield)
{ set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setYPosition (final int YPosition) { set_Value (COLUMNNAME_YPosition, YPosition); } @Override public int getYPosition() { return get_ValueAsInt(COLUMNNAME_YPosition); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
1
请完成以下Java代码
class TUPackingInfo implements IHUPackingInfo { private final I_M_HU tuHU; private final Supplier<IHUProductStorage> huProductStorageSupplier; TUPackingInfo(@NonNull final I_M_HU tuHU) { this.tuHU = tuHU; huProductStorageSupplier = Suppliers.memoize(() -> { final List<IHUProductStorage> productStorages = Services.get(IHandlingUnitsBL.class) .getStorageFactory() .getStorage(tuHU) .getProductStorages(); if (productStorages.size() == 1) { return productStorages.get(0); } else { return null; } }); } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(tuHU).toString(); } private IHUProductStorage getHUProductStorage() { return huProductStorageSupplier.get(); } @Override public I_M_HU_PI getM_LU_HU_PI() { return null; } @Override public I_M_HU_PI getM_TU_HU_PI() { return Services.get(IHandlingUnitsBL.class).getPI(tuHU); } @Override public boolean isInfiniteQtyTUsPerLU()
{ return true; } @Override public BigDecimal getQtyTUsPerLU() { return null; } @Override public boolean isInfiniteQtyCUsPerTU() { return false; } @Override public BigDecimal getQtyCUsPerTU() { final IHUProductStorage huProductStorage = getHUProductStorage(); return huProductStorage == null ? null : huProductStorage.getQty().toBigDecimal(); } @Override public I_C_UOM getQtyCUsPerTU_UOM() { final IHUProductStorage huProductStorage = getHUProductStorage(); return huProductStorage == null ? null : huProductStorage.getC_UOM(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\TUPackingInfo.java
1
请完成以下Java代码
public JmsOperations getJmsOperations() { return jmsOperations; } public void setJmsOperations(JmsOperations jmsOperations) { this.jmsOperations = jmsOperations; } public JmsListenerEndpointRegistry getEndpointRegistry() { return endpointRegistry; } public void setEndpointRegistry(JmsListenerEndpointRegistry endpointRegistry) { this.endpointRegistry = endpointRegistry; } public String getContainerFactoryBeanName() {
return containerFactoryBeanName; } public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } public JmsListenerContainerFactory<?> getContainerFactory() { return containerFactory; } public void setContainerFactory(JmsListenerContainerFactory<?> containerFactory) { this.containerFactory = containerFactory; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsChannelModelProcessor.java
1
请完成以下Java代码
public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo ()
{ return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<String> postToClient(@RequestBody String message, @PathVariable("registrationToken") String registrationToken) throws FirebaseMessagingException { Message msg = Message.builder() .setToken(registrationToken) .putData("body", message) .build(); String id = fcm.send(msg); return ResponseEntity .status(HttpStatus.ACCEPTED) .body(id); } @PostMapping("/clients") public ResponseEntity<List<String>> postToClients(@RequestBody MulticastMessageRepresentation message) throws FirebaseMessagingException { MulticastMessage msg = MulticastMessage.builder() .addAllTokens(message.getRegistrationTokens()) .putData("body", message.getData()) .build(); BatchResponse response = fcm.sendMulticast(msg); List<String> ids = response.getResponses() .stream() .map(r->r.getMessageId()) .collect(Collectors.toList()); return ResponseEntity
.status(HttpStatus.ACCEPTED) .body(ids); } @PostMapping("/subscriptions/{topic}") public ResponseEntity<Void> createSubscription(@PathVariable("topic") String topic,@RequestBody List<String> registrationTokens) throws FirebaseMessagingException { fcm.subscribeToTopic(registrationTokens, topic); return ResponseEntity.ok().build(); } @DeleteMapping("/subscriptions/{topic}/{registrationToken}") public ResponseEntity<Void> deleteSubscription(@PathVariable String topic, @PathVariable String registrationToken) throws FirebaseMessagingException { fcm.subscribeToTopic(Arrays.asList(registrationToken), topic); return ResponseEntity.ok().build(); } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\publisher\controller\FirebasePublisherController.java
2
请完成以下Java代码
public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(msgBL.getMsg(jsonOpts.getAdLanguage(), ARE_YOU_SURE)) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity) { final HUConsolidationJob job = getHUConsolidationJob(wfProcess);
return computeActivityState(job); } public static WFActivityStatus computeActivityState(final HUConsolidationJob job) { // TODO return WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return HUConsolidationApplication.mapJob(request.getWfProcess(), jobService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\CompleteWFActivityHandler.java
1
请完成以下Java代码
public void removeByTenantId(TenantId tenantId) { notificationTemplateRepository.deleteByTenantId(tenantId.getId()); } @Override public NotificationTemplate findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public NotificationTemplate findByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndName(tenantId, name)); } @Override public PageData<NotificationTemplate> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(notificationTemplateRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override
public NotificationTemplateId getExternalIdByInternal(NotificationTemplateId internalId) { return DaoUtil.toEntityId(notificationTemplateRepository.getExternalIdByInternal(internalId.getId()), NotificationTemplateId::new); } @Override public PageData<NotificationTemplate> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override protected JpaRepository<NotificationTemplateEntity, UUID> getRepository() { return notificationTemplateRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_TEMPLATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationTemplateDao.java
1
请完成以下Java代码
public List<? extends Event> findLatestEvents(UUID tenantId, UUID entityId, EventType eventType, int limit) { return DaoUtil.convertDataList(getEventRepository(eventType).findLatestEvents(tenantId, entityId, limit)); } @Override public Event findLatestDebugRuleNodeInEvent(UUID tenantId, UUID entityId) { return DaoUtil.getData(ruleNodeDebugEventRepository.findLatestDebugRuleNodeInEvent(tenantId, entityId)); } @Override public void cleanupEvents(long regularEventExpTs, long debugEventExpTs, boolean cleanupDb) { if (regularEventExpTs > 0) { log.info("Going to cleanup regular events with exp time: {}", regularEventExpTs); if (cleanupDb) { cleanupEvents(regularEventExpTs, false); } else { cleanupPartitionsCache(regularEventExpTs, false); } } if (debugEventExpTs > 0) { log.info("Going to cleanup debug events with exp time: {}", debugEventExpTs); if (cleanupDb) { cleanupEvents(debugEventExpTs, true); } else { cleanupPartitionsCache(debugEventExpTs, true); } } } private void cleanupEvents(long eventExpTime, boolean debug) { for (EventType eventType : EventType.values()) { if (eventType.isDebug() == debug) { cleanupPartitions(eventType, eventExpTime); } } } private void cleanupPartitions(EventType eventType, long eventExpTime) { partitioningRepository.dropPartitionsBefore(eventType.getTable(), eventExpTime, partitionConfiguration.getPartitionSizeInMs(eventType));
} private void cleanupPartitionsCache(long expTime, boolean isDebug) { for (EventType eventType : EventType.values()) { if (eventType.isDebug() == isDebug) { partitioningRepository.cleanupPartitionsCache(eventType.getTable(), expTime, partitionConfiguration.getPartitionSizeInMs(eventType)); } } } private void parseUUID(String src, String paramName) { if (!StringUtils.isEmpty(src)) { try { UUID.fromString(src); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Failed to convert " + paramName + " to UUID!"); } } } private EventRepository<? extends EventEntity<?>, ?> getEventRepository(EventType eventType) { var repository = repositories.get(eventType); if (repository == null) { throw new RuntimeException("Event type: " + eventType + " is not supported!"); } return repository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\JpaBaseEventDao.java
1
请完成以下Java代码
public final IUserRolePermissions getUserRolePermissions() { if (_userRolePermissions == null) { return Env.getUserRolePermissions(getCtx()); } return _userRolePermissions; } // // // // // public static final class Builder { private Properties ctx; private int AD_Tree_ID; private boolean editable; private boolean clientTree; private boolean allNodes = false; @Nullable private String trxName = ITrx.TRXNAME_None; private String adLanguage = null; private IUserRolePermissions userRolePermissions; private Builder() { super(); } /** * Construct & Load Tree */ public MTree build() { return new MTree(this); } public Builder setCtx(final Properties ctx) { this.ctx = ctx; return this; } public Properties getCtx() { Check.assumeNotNull(ctx, "Parameter ctx is not null"); return ctx; } public Builder setUserRolePermissions(final IUserRolePermissions userRolePermissions) { this.userRolePermissions = userRolePermissions; return this; } public IUserRolePermissions getUserRolePermissions() { if (userRolePermissions == null) { return Env.getUserRolePermissions(getCtx()); } return userRolePermissions; } public Builder setAD_Tree_ID(final int AD_Tree_ID) { this.AD_Tree_ID = AD_Tree_ID; return this; } public int getAD_Tree_ID() { if (AD_Tree_ID <= 0) { throw new IllegalArgumentException("Param 'AD_Tree_ID' may not be null"); } return AD_Tree_ID; } public Builder setTrxName(@Nullable final String trxName) { this.trxName = trxName; return this; } @Nullable public String getTrxName() { return trxName; }
/** * @param editable True, if tree can be modified * - includes inactive and empty summary nodes */ public Builder setEditable(final boolean editable) { this.editable = editable; return this; } public boolean isEditable() { return editable; } /** * @param clientTree the tree is displayed on the java client (not on web) */ public Builder setClientTree(final boolean clientTree) { this.clientTree = clientTree; return this; } public boolean isClientTree() { return clientTree; } public Builder setAllNodes(final boolean allNodes) { this.allNodes = allNodes; return this; } public boolean isAllNodes() { return allNodes; } public Builder setLanguage(final String adLanguage) { this.adLanguage = adLanguage; return this; } private String getAD_Language() { if (adLanguage == null) { return Env.getADLanguageOrBaseLanguage(getCtx()); } return adLanguage; } } } // MTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree.java
1
请完成以下Java代码
protected @NonNull ConfigurableApplicationContext getApplicationContext() { return this.applicationContext; } /** * Handles the {@link MembershipEvent membership event} when a {@link DistributedMember peer member} * departs from the {@link DistributedSystem cluster} by calling {@link ConfigurableApplicationContext#close()}. * * @param event {@link MemberDepartedEvent} to handle. * @see org.springframework.geode.distributed.event.support.MemberDepartedEvent * @see org.springframework.context.ConfigurableApplicationContext#close() */ @Override public void handleMemberDeparted(MemberDepartedEvent event) { getApplicationContext().close();
} /** * Handles the {@link MembershipEvent membership event} when a {@link DistributedMember peer member} * joins the {@link DistributedSystem cluster} by calling {@link ConfigurableApplicationContext#refresh()}. * * @param event {@link MemberJoinedEvent} to handle. * @see org.springframework.geode.distributed.event.support.MemberJoinedEvent * @see org.springframework.context.ConfigurableApplicationContext#refresh() */ @Override public void handleMemberJoined(MemberJoinedEvent event) { getApplicationContext().refresh(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\distributed\event\ApplicationContextMembershipListener.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Mandatory Parameters. @param IsManadatoryParams Mandatory Parameters */ @Override public void setIsManadatoryParams (boolean IsManadatoryParams) { set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams)); } /** Get Mandatory Parameters. @return Mandatory Parameters */ @Override public boolean isManadatoryParams () { Object oo = get_Value(COLUMNNAME_IsManadatoryParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Display All Parameters. @param IsShowAllParams Display All Parameters */ @Override public void setIsShowAllParams (boolean IsShowAllParams) { set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams)); } /** Get Display All Parameters. @return Display All Parameters */ @Override
public boolean isShowAllParams () { Object oo = get_Value(COLUMNNAME_IsShowAllParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
1
请完成以下Java代码
public void removeConnectionEventListener(ConnectionEventListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.remove(listener); } void closeHandle(JcaExecutorServiceConnection handle) { ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); event.setConnectionHandle(handle); for (ConnectionEventListener cel : listeners) { cel.connectionClosed(event); } } public PrintWriter getLogWriter() throws ResourceException { return logwriter; } public void setLogWriter(PrintWriter out) throws ResourceException { logwriter = out; } public LocalTransaction getLocalTransaction() throws ResourceException { throw new NotSupportedException("LocalTransaction not supported"); } public XAResource getXAResource() throws ResourceException { throw new NotSupportedException("GetXAResource not supported not supported");
} public ManagedConnectionMetaData getMetaData() throws ResourceException { return null; } // delegate methods ///////////////////////////////////////// public boolean schedule(Runnable runnable, boolean isLongRunning) { return delegate.schedule(runnable, isLongRunning); } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return delegate.getExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnection.java
1
请完成以下Java代码
public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } @Override public void setC_Async_Batch_ID (final int C_Async_Batch_ID) { if (C_Async_Batch_ID < 1) set_Value (COLUMNNAME_C_Async_Batch_ID, null); else set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID); } @Override public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public void setChunkUUID (final @Nullable java.lang.String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public java.lang.String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() {
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final boolean quarantineHUs = isQuarantineHUs(streamSelectedHUs(Select.ONLY_TOPLEVEL)); if (quarantineHUs) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_HUs_IN_Quarantine)); } return super.checkPreconditionsApplicable(); } @ProcessParamLookupValuesProvider(parameterName = I_M_Locator.COLUMNNAME_M_Warehouse_ID, numericKey = true, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup) @Override public LookupValuesList getAvailableWarehouses(final LookupDataSourceContext evalCtx) { return super.getAvailableWarehouses(evalCtx); } @ProcessParamLookupValuesProvider(parameterName = I_M_Locator.COLUMNNAME_M_Locator_ID, numericKey = true, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup) @Override protected LookupValuesList getAvailableLocators(final LookupDataSourceContext evalCtx)
{ return super.getAvailableLocators(evalCtx); } @Override public ProcessPreconditionsResolution checkHUsEligible() { return isQuarantineHUs(streamSelectedHUs(Select.ONLY_TOPLEVEL)) ? ProcessPreconditionsResolution.reject(MSG_WEBUI_HUs_IN_Quarantine) : ProcessPreconditionsResolution.accept(); } private boolean isQuarantineHUs(final Stream<I_M_HU> streamSelectedHUs) { return streamSelectedHUs.anyMatch(lotNumberQuarantineService::isQuarantineHU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToAnotherWarehouse_ExclQuarantined.java
1
请完成以下Java代码
private DocumentEntityDescriptor createEntityDescriptor( final DocumentId documentTypeId, final DetailId detailId, @NonNull final Optional<SOTrx> soTrx) { return createDescriptorBuilder(documentTypeId, detailId) .addField(createProductFieldBuilder()) .addFieldIf(QuickInputConstants.isEnablePackingInstructionsField(), this::createPackingInstructionFieldBuilder) .addField(createQuantityFieldBuilder()) .setIsSOTrx(soTrx) .build(); } private Builder createProductFieldBuilder() { return DocumentFieldDescriptor.builder(IForecastLineQuickInput.COLUMNNAME_M_Product_ID) .setCaption(Services.get(IMsgBL.class).translatable(IForecastLineQuickInput.COLUMNNAME_M_Product_ID)) // .setWidgetType(DocumentFieldWidgetType.Lookup) .setLookupDescriptorProvider(ProductLookupDescriptor.builderWithStockInfo() .bpartnerParamName(I_M_Forecast.COLUMNNAME_C_BPartner_ID) .pricingDateParamName(I_M_Forecast.COLUMNNAME_DatePromised) .availableStockDateParamName(I_M_Forecast.COLUMNNAME_DatePromised) .availableToPromiseAdapter(availableToPromiseAdapter) .availableForSaleAdapter(availableForSaleAdapter) .availableForSalesConfigRepo(availableForSalesConfigRepo) .build()) .setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true) .setMandatoryLogic(ConstantLogicExpression.TRUE) .setDisplayLogic(ConstantLogicExpression.TRUE) .addCallout(ForecastLineQuickInputDescriptorFactory::onProductChangedCallout) .addCharacteristic(Characteristic.PublicField); } private static QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor) { return QuickInputLayoutDescriptor.onlyFields(entityDescriptor, new String[][] { { "M_Product_ID", "M_HU_PI_Item_Product_ID" } // , { "Qty" } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\forecastline\ForecastLineQuickInputDescriptorFactory.java
1
请完成以下Java代码
class ShipmentSchedulesCUsToTUsAggregator { @NonNull private final IHUShipmentScheduleBL huShipmentScheduleBL; @NonNull private final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO; @NonNull private final IHandlingUnitsBL handlingUnitsBL; @NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds; @Builder private ShipmentSchedulesCUsToTUsAggregator( @NonNull final IHUShipmentScheduleBL huShipmentScheduleBL, @NonNull final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO, @NonNull final IHandlingUnitsBL handlingUnitsBL, // @NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { this.huShipmentScheduleBL = huShipmentScheduleBL; this.shipmentScheduleAllocDAO = shipmentScheduleAllocDAO; this.handlingUnitsBL = handlingUnitsBL; this.shipmentScheduleIds = ImmutableSet.copyOf(shipmentScheduleIds); } public void execute() { if (shipmentScheduleIds.isEmpty()) { return; } final Map<ShipmentScheduleId, I_M_ShipmentSchedule> shipmentSchedulesById = huShipmentScheduleBL.getByIds(shipmentScheduleIds); final ImmutableListMultimap<ShipmentScheduleId, I_M_ShipmentSchedule_QtyPicked> qtyPickedRecordsByScheduleId = shipmentScheduleAllocDAO.retrieveNotOnShipmentLineRecordsByScheduleIds(shipmentSchedulesById.keySet(), I_M_ShipmentSchedule_QtyPicked.class); for (final ShipmentScheduleId shipmentScheduleId : qtyPickedRecordsByScheduleId.keySet()) { final I_M_ShipmentSchedule shipmentSchedule = shipmentSchedulesById.get(shipmentScheduleId); final ImmutableSet<HuId> cuIdsToAggregate = qtyPickedRecordsByScheduleId.get(shipmentScheduleId) .stream() .filter(ShipmentSchedulesCUsToTUsAggregator::isEligibleForAggregation) .map(record -> HuId.ofRepoId(record.getVHU_ID())) .collect(ImmutableSet.toImmutableSet()); final List<I_M_HU> cusToAggregate = handlingUnitsBL.getByIds(cuIdsToAggregate);
if (cusToAggregate.isEmpty()) { continue; } final TULoader tuLoader = huShipmentScheduleBL.createTULoader(shipmentSchedule).orElse(null); if (tuLoader == null) { continue; } try (final IAutoCloseable ignored = ShipmentScheduleHUTrxListener.temporaryEnableUpdateAllocationLUAndTUForCU()) { tuLoader.addCUs(cusToAggregate); tuLoader.closeCurrentTUs(); } } } private static boolean isEligibleForAggregation(final I_M_ShipmentSchedule_QtyPicked qtyPickedRecord) { return qtyPickedRecord.isActive() && qtyPickedRecord.getVHU_ID() > 0 // we have a CU && qtyPickedRecord.getQtyPicked().signum() != 0 && qtyPickedRecord.getM_TU_HU_ID() <= 0 // not already aggregated to TUs && qtyPickedRecord.getM_LU_HU_ID() <= 0// not already aggregated to LUs && qtyPickedRecord.getM_InOutLine_ID() <= 0 // not already shipped ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentSchedulesCUsToTUsAggregator.java
1
请完成以下Java代码
public MDocType getCounterDocType() { MDocType dt = null; if (getCounter_C_DocType_ID() > 0) { dt = MDocType.get(getCtx(), getCounter_C_DocType_ID()); if (dt.get_ID() == 0) { dt = null; } } return dt; } // getCounterDocType /************************************************************************** * Validate Document Type compatability * * @return Error message or null if valid */ public String validate() { MDocType dt = getDocType(); if (dt == null) { log.error("No DocType=" + getC_DocType_ID()); setIsValid(false); return "No Document Type"; } MDocType c_dt = getCounterDocType(); if (c_dt == null) { log.error("No Counter DocType=" + getCounter_C_DocType_ID()); setIsValid(false); return "No Counter Document Type"; } // DocBaseType dtBT = DocBaseType.ofCode(dt.getDocBaseType()); DocBaseType c_dtBT = DocBaseType.ofCode(c_dt.getDocBaseType()); log.debug(dtBT + " -> " + c_dtBT); boolean valid = true; final DocBaseType docBaseTypeCounter = Services.get(IDocTypeDAO.class).getDocBaseTypeCounter(dtBT).orElse(null); if (c_dtBT == null) { valid = false; } else if (docBaseTypeCounter == null) { valid = false; } else if (!c_dtBT.equals(docBaseTypeCounter)) { valid = false; } setIsValid(valid); if (!valid) { log.warn("NOT - " + dtBT + " -> " + c_dtBT); return "Not valid"; } // Counter should have document numbering if (!c_dt.isDocNoControlled()) { return "Counter Document Type should be automatically Document Number controlled"; } return null; } // validate
/** * String Representation * * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("MDocTypeCounter["); sb.append(get_ID()).append(",").append(getName()) .append(",C_DocType_ID=").append(getC_DocType_ID()) .append(",Counter=").append(getCounter_C_DocType_ID()) .append(",DocAction=").append(getDocAction()) .append("]"); return sb.toString(); } // toString /** * Before Save * * @param newRecord new * @return true */ @Override protected boolean beforeSave(boolean newRecord) { if (getAD_Org_ID() != 0) { setAD_Org_ID(0); } if (!newRecord && (is_ValueChanged("C_DocType_ID") || is_ValueChanged("Counter_C_DocType_ID"))) { setIsValid(false); } // try to validate if (!isValid()) { validate(); } return true; } // beforeSave } // MDocTypeCounter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDocTypeCounter.java
1
请完成以下Java代码
public void onGLJournalLineReactivated(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = Check.assumeNotNull(line.getOpenItemTrxInfo(), "OpenItemTrxInfo shall not be null"); final PaymentId paymentId = openItemTrxInfo.getKey().getPaymentId().orElse(null); if (paymentId == null) { return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_PaymentSelect_Acct, B_UnallocatedCash_Acct)) { paymentBL.scheduleUpdateIsAllocated(paymentId); } else if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { paymentBL.markNotReconciled(paymentId); } } // // // @Component @Interceptor(I_C_Payment.class) public static class C_Payment_Interceptor { private final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class);
@ModelChange( timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_C_Payment.COLUMNNAME_C_BankStatement_ID, I_C_Payment.COLUMNNAME_C_BankStatementLine_ID, I_C_Payment.COLUMNNAME_C_BankStatementLine_Ref_ID }) void copyOpenItemKeyToFactAcct(final I_C_Payment payment) { final FAOpenItemTrxInfo openItemTrxInfo = computeTrxInfoFromPayment_B_InTransit(payment); factAcctDAO.setOpenItemTrxInfo(openItemTrxInfo, FactAcctQuery.builder() .tableName(I_C_Payment.Table_Name) .recordId(payment.getC_Payment_ID()) .accountConceptualName(B_InTransit_Acct) .build()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\handlers\PaymentOIHandler.java
1
请完成以下Java代码
public final void setServiceProperties(ServiceProperties serviceProperties) { this.serviceProperties = serviceProperties; } /** * Sets whether to encode the service url with the session id or not. * @param encodeServiceUrlWithSessionId whether to encode the service url with the * session id or not. */ public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) { this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; } /** * Sets whether to encode the service url with the session id or not. * @return whether to encode the service url with the session id or not. *
*/ protected boolean getEncodeServiceUrlWithSessionId() { return this.encodeServiceUrlWithSessionId; } /** * Sets the {@link RedirectStrategy} to use * @param redirectStrategy the {@link RedirectStrategy} to use * @since 6.3 */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationEntryPoint.java
1
请完成以下Java代码
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU_Item item) { return getDelegate(item).retrieveIncludedHUs(item); } @Override public List<I_M_HU_Item> retrieveItems(final I_M_HU hu) { return getDelegate(hu).retrieveItems(hu); } @Override public Optional<I_M_HU_Item> retrieveItem(final I_M_HU hu, final I_M_HU_PI_Item piItem) { return getDelegate(hu).retrieveItem(hu, piItem); } @Override public I_M_HU_Item createHUItem(final I_M_HU hu, final I_M_HU_PI_Item piItem) { return getDelegate(hu).createHUItem(hu, piItem); } @Override public I_M_HU_Item createAggregateHUItem(@NonNull final I_M_HU hu)
{ return getDelegate(hu).createAggregateHUItem(hu); } @Override public I_M_HU_Item createChildHUItem(@NonNull final I_M_HU hu) { return getDelegate(hu).createChildHUItem(hu); } @Override public I_M_HU_Item retrieveAggregatedItemOrNull(I_M_HU hu) { return getDelegate(hu).retrieveAggregatedItemOrNull(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CachedIfInTransactionHUAndItemsDAO.java
1
请完成以下Java代码
public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setMobileUI_HUManager_Attribute_ID (final int MobileUI_HUManager_Attribute_ID) { if (MobileUI_HUManager_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, MobileUI_HUManager_Attribute_ID); } @Override public int getMobileUI_HUManager_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_Attribute_ID); } @Override public org.compiere.model.I_MobileUI_HUManager getMobileUI_HUManager() { return get_ValueAsPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class); } @Override public void setMobileUI_HUManager(final org.compiere.model.I_MobileUI_HUManager MobileUI_HUManager) { set_ValueFromPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class, MobileUI_HUManager); } @Override public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID) { if (MobileUI_HUManager_ID < 1) set_Value (COLUMNNAME_MobileUI_HUManager_ID, null); else
set_Value (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID); } @Override public int getMobileUI_HUManager_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public List<IdentityLinkEntity> getQueryIdentityLinks() { if (queryIdentityLinks == null) { queryIdentityLinks = new LinkedList<>(); } return queryIdentityLinks; } public void setQueryIdentityLinks(List<IdentityLinkEntity> identityLinks) { queryIdentityLinks = identityLinks; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("Task["); strb.append("id=").append(id); strb.append(", key=").append(taskDefinitionKey); strb.append(", name=").append(name); if (executionId != null) { strb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId) .append(", processDefinitionId=").append(processDefinitionId); } else if (scopeId != null) { strb.append(", scopeInstanceId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeDefinitionId=").append(scopeDefinitionId); } strb.append("]"); return strb.toString(); } @Override public boolean isCountEnabled() { return isCountEnabled; } public boolean getIsCountEnabled() { return isCountEnabled; } @Override public void setCountEnabled(boolean isCountEnabled) {
this.isCountEnabled = isCountEnabled; } public void setIsCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } @Override public void setVariableCount(int variableCount) { this.variableCount = variableCount; } @Override public int getVariableCount() { return variableCount; } @Override public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; } @Override public int getIdentityLinkCount() { return identityLinkCount; } @Override public int getSubTaskCount() { return subTaskCount; } @Override public void setSubTaskCount(int subTaskCount) { this.subTaskCount = subTaskCount; } @Override public boolean isIdentityLinksInitialized() { return isIdentityLinksInitialized; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\TaskEntityImpl.java
2
请完成以下Java代码
public class TbGpsGeofencingFilterNodeConfiguration implements NodeConfiguration<TbGpsGeofencingFilterNodeConfiguration> { private String latitudeKeyName; private String longitudeKeyName; private PerimeterType perimeterType; private boolean fetchPerimeterInfoFromMessageMetadata; // If Perimeter is fetched from metadata private String perimeterKeyName; //For Polygons private String polygonsDefinition; //For Circles private Double centerLatitude;
private Double centerLongitude; private Double range; private RangeUnit rangeUnit; @Override public TbGpsGeofencingFilterNodeConfiguration defaultConfiguration() { TbGpsGeofencingFilterNodeConfiguration configuration = new TbGpsGeofencingFilterNodeConfiguration(); configuration.setLatitudeKeyName("latitude"); configuration.setLongitudeKeyName("longitude"); configuration.setPerimeterType(PerimeterType.POLYGON); configuration.setFetchPerimeterInfoFromMessageMetadata(true); configuration.setPerimeterKeyName("ss_perimeter"); return configuration; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\geo\TbGpsGeofencingFilterNodeConfiguration.java
1
请完成以下Java代码
public static void setReplicationCtx(final Properties ctx, final String name, final Object value, final boolean overwrite) { if (value instanceof Integer) { final Integer valueInt = (Integer)value; final Integer valueOldInt = Env.containsKey(ctx, name) ? Env.getContextAsInt(ctx, name) : null; if (Objects.equals(valueInt, valueOldInt)) { // nothing to do return; } else if (overwrite || valueOldInt == null) { Env.setContext(ctx, name, valueInt); } else { throw new ReplicationException(MSG_XMLInvalidContext) .setParameter("AttributeName", name) .setParameter("Value", valueInt) .setParameter("ValueOld", valueOldInt); } } else if (value instanceof Timestamp) { final Timestamp valueTS = (Timestamp)value; final Timestamp valueOldTS = Env.containsKey(ctx, name) ? Env.getContextAsDate(ctx, name) : null; if (Objects.equals(valueTS, valueOldTS)) { // nothing to do return; } else if (overwrite || valueOldTS == null) { Env.setContext(ctx, name, valueTS); } else { throw new ReplicationException(MSG_XMLInvalidContext) .setParameter("AttributeName", name) .setParameter("Value", valueTS) .setParameter("ValueOld", valueOldTS);
} } else { final String valueStr = value == null ? null : value.toString(); final String valueOldStr = Env.containsKey(ctx, name) ? Env.getContext(ctx, name) : null; if (Objects.equals(valueStr, valueOldStr)) { // nothing to do return; } else if (overwrite || valueOldStr == null) { Env.setContext(ctx, name, valueStr); } else { throw new ReplicationException(MSG_XMLInvalidContext) .setParameter("AttributeName", name) .setParameter("Value", valueStr) .setParameter("ValueOld", valueOldStr); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\ReplicationHelper.java
1
请完成以下Java代码
public List<String> segment(String sentence) { List<String> result = new LinkedList<String>(); segment(sentence, result); return result; } /** * 在线学习 * * @param segmentedSentence 分好词的句子,空格或tab分割,不含词性 * @return 是否学习成功(失败的原因是参数错误) */ public boolean learn(String segmentedSentence) { return learn(segmentedSentence.split("\\s+")); } /** * 在线学习 * * @param words 分好词的句子 * @return 是否学习成功(失败的原因是参数错误) */ public boolean learn(String... words) { // for (int i = 0; i < words.length; i++) // 防止传入带词性的词语 // {
// int index = words[i].indexOf('/'); // if (index > 0) // { // words[i] = words[i].substring(0, index); // } // } return learn(new CWSInstance(words, model.featureMap)); } @Override protected Instance createInstance(Sentence sentence, FeatureMap featureMap) { return CWSInstance.create(sentence, featureMap); } @Override public double[] evaluate(String corpora) throws IOException { // 这里用CWS的F1 double[] prf = Utility.prf(Utility.evaluateCWS(corpora, this)); return prf; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronSegmenter.java
1
请完成以下Java代码
public class CookieUtils { private static final ObjectMapper OBJECT_MAPPER; static { ClassLoader loader = CookieUtils.class.getClassLoader(); OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModules(SecurityJackson2Modules.getModules(loader)); } public static Optional<Cookie> getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return Optional.of(cookie); } } } return Optional.empty(); } public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setHttpOnly(true); cookie.setMaxAge(maxAge); response.addCookie(cookie); } public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } } }
} public static String serialize(Object object) { try { return Base64.getUrlEncoder() .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object)); } catch (JsonProcessingException e) { throw new IllegalArgumentException("The given Json object value: " + object + " cannot be transformed to a String", e); } } public static <T> T deserialize(Cookie cookie, Class<T> cls) { byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue()); try { return OBJECT_MAPPER.readValue(decodedBytes, cls); } catch (IOException e) { throw new IllegalArgumentException("The given string value: " + Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\CookieUtils.java
1
请完成以下Java代码
public void addCUs(@NonNull final Collection<I_M_HU> cuHUs) { cuHUs.forEach(this::addCU); } public void addCU(@NonNull final I_M_HU cuHU) { assertCU(cuHU); final TULoaderInstanceKey tuInstanceKey = extractTULoaderInstanceKeyFromCU(cuHU); final TULoaderInstance tuInstance = tuInstances.computeIfAbsent(tuInstanceKey, this::newTULoaderInstance); tuInstance.addCU(cuHU); } public void closeCurrentTUs() { tuInstances.values().forEach(TULoaderInstance::closeCurrentTU); } private static void assertCU(final @NonNull I_M_HU cuHU) { if (!HuPackingInstructionsVersionId.ofRepoId(cuHU.getM_HU_PI_Version_ID()).isVirtual()) { throw new AdempiereException("Expected to be CU: " + cuHU); } } private TULoaderInstanceKey extractTULoaderInstanceKeyFromCU(final I_M_HU cuHU) { return TULoaderInstanceKey.builder() .bpartnerId(IHandlingUnitsBL.extractBPartnerIdOrNull(cuHU)) .bpartnerLocationRepoId(cuHU.getC_BPartner_Location_ID()) .locatorId(warehouseDAO.getLocatorIdByRepoIdOrNull(cuHU.getM_Locator_ID())) .huStatus(cuHU.getHUStatus()) .clearanceStatusInfo(ClearanceStatusInfo.ofHU(cuHU)) .build(); } private TULoaderInstance newTULoaderInstance(@NonNull final TULoaderInstanceKey key) { return TULoaderInstance.builder() .huContext(huContext) .tuPI(tuPI) .capacity(capacity) .bpartnerId(key.getBpartnerId()) .bpartnerLocationRepoId(key.getBpartnerLocationRepoId()) .locatorId(key.getLocatorId()) .huStatus(key.getHuStatus()) .clearanceStatusInfo(key.getClearanceStatusInfo()) .build(); } // // // @Value
private static class TULoaderInstanceKey { @Nullable BPartnerId bpartnerId; int bpartnerLocationRepoId; @Nullable LocatorId locatorId; @Nullable String huStatus; @Nullable ClearanceStatusInfo clearanceStatusInfo; @Builder private TULoaderInstanceKey( @Nullable final BPartnerId bpartnerId, final int bpartnerLocationRepoId, @Nullable final LocatorId locatorId, @Nullable final String huStatus, @Nullable final ClearanceStatusInfo clearanceStatusInfo) { this.bpartnerId = bpartnerId; this.bpartnerLocationRepoId = bpartnerLocationRepoId > 0 ? bpartnerLocationRepoId : -1; this.locatorId = locatorId; this.huStatus = StringUtils.trimBlankToNull(huStatus); this.clearanceStatusInfo = clearanceStatusInfo; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoader.java
1
请完成以下Java代码
public void skipWhileAndSkipUntilStream() { Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4); Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4); } public void unfoldStream() { Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty()); } public void windowedStream() { Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5); List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); List<List<Integer>> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
} public void groupRunsStreams() { Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList()); } public void aggreagateOnBiElementPredicate() { Stream<String> stream = Stream.of("a1", "b1", "b2", "c1"); Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0)); } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\protonpack\StreamUtilsExample.java
1
请完成以下Java代码
public void setHR_ListType_ID (int HR_ListType_ID) { if (HR_ListType_ID < 1) set_Value (COLUMNNAME_HR_ListType_ID, null); else set_Value (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID)); } /** Get Payroll List Type. @return Payroll List Type */ public int getHR_ListType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID); if (ii == null) return 0; return ii.intValue(); } public org.eevolution.model.I_HR_Payroll getHR_Payroll() throws RuntimeException { return (org.eevolution.model.I_HR_Payroll)MTable.get(getCtx(), org.eevolution.model.I_HR_Payroll.Table_Name) .getPO(getHR_Payroll_ID(), get_TrxName()); } /** Set Payroll. @param HR_Payroll_ID Payroll */ public void setHR_Payroll_ID (int HR_Payroll_ID) { if (HR_Payroll_ID < 1) set_Value (COLUMNNAME_HR_Payroll_ID, null); else set_Value (COLUMNNAME_HR_Payroll_ID, Integer.valueOf(HR_Payroll_ID)); } /** Get Payroll. @return Payroll */ public int getHR_Payroll_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Employee. @param IsEmployee Indicates if this Business Partner is an employee */ public void setIsEmployee (boolean IsEmployee) { set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee)); } /** Get Employee. @return Indicates if this Business Partner is an employee */ public boolean isEmployee () { Object oo = get_Value(COLUMNNAME_IsEmployee); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_List.java
1
请完成以下Java代码
public Builder filterConverterDecorator(@NonNull final SqlDocumentFilterConverterDecorator sqlDocumentFilterConverterDecorator) { this.sqlDocumentFilterConverterDecorator = sqlDocumentFilterConverterDecorator; return this; } public Builder rowCustomizer(final ViewRowCustomizer rowCustomizer) { this.rowCustomizer = rowCustomizer; return this; } private ViewRowCustomizer getRowCustomizer() { return rowCustomizer; } public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor) { this.viewInvalidationAdvisor = viewInvalidationAdvisor; return this; } private IViewInvalidationAdvisor getViewInvalidationAdvisor()
{ return viewInvalidationAdvisor; } public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this.refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this; } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder includedEntitiesDescriptors(final Map<DetailId, SqlDocumentEntityDataBindingDescriptor> includedEntitiesDescriptors) { this.includedEntitiesDescriptors = includedEntitiesDescriptors; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBinding.java
1
请完成以下Java代码
public String toString() { return "TrxRunConfig [trxPropagation=" + trxPropagation + ", onRunnableSuccess=" + onRunnableSuccess + ", onRunnableFail=" + onRunnableFail + "]"; } @Override public TrxPropagation getTrxPropagation() { return trxPropagation; } @Override public OnRunnableSuccess getOnRunnableSuccess() {
return onRunnableSuccess; } @Override public OnRunnableFail getOnRunnableFail() { return onRunnableFail; } @Override public boolean isAutoCommit() { return autocommit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxRunConfig.java
1
请完成以下Java代码
public void onSuccess(String result) { amqpTemplate.convertAndSend(replyTo, result); } @Override public void onFailure(Throwable ex) { logger.error("接受到QUEUE_ASYNC_RPC失败", ex); } }); } @RabbitListener(queues = QUEUE_ASYNC_RPC_WITH_FIXED_REPLY) public void processAsyncRpcFixed(User user, @Header(AmqpHeaders.REPLY_TO) String replyTo, @Header(AmqpHeaders.CORRELATION_ID) byte[] correlationId) { // String body = new String(message.getBody(), Charset.forName("UTF-8")); // User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){}); logger.info("user.name={}", user.getName()); logger.info("use a fixed reply queue={}, correlationId={}", replyTo, new String(correlationId)); ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(user.getName()); asyncResult.addCallback(new ListenableFutureCallback<String>() { @Override
public void onSuccess(String result) { amqpTemplate.convertAndSend(replyTo, (Object) result, m -> { //https://stackoverflow.com/questions/42382307/messageproperties-setcorrelationidstring-is-not-working m.getMessageProperties().setCorrelationId(new String(correlationId)); return m; }); } @Override public void onFailure(Throwable ex) { logger.error("接受到QUEUE_ASYNC_RPC_WITH_FIXED_REPLY失败", ex); } }); } }
repos\SpringBootBucket-master\springboot-rabbitmq-rpc\springboot-rabbitmq-rpc-server\src\main\java\com\xncoding\pos\server\AsyncRPCServer.java
1
请完成以下Java代码
public void addLabel(E label, Integer frequency) { Integer innerFrequency = labelMap.get(label); if (innerFrequency == null) { innerFrequency = frequency; } else { innerFrequency += frequency; } labelMap.put(label, innerFrequency); } public boolean containsLabel(E label) { return labelMap.containsKey(label); } public int getFrequency(E label) { Integer frequency = labelMap.get(label); if (frequency == null) return 0; return frequency; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); ArrayList<Map.Entry<E, Integer>> entries = new ArrayList<Map.Entry<E, Integer>>(labelMap.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<E, Integer>>() { @Override public int compare(Map.Entry<E, Integer> o1, Map.Entry<E, Integer> o2) { return -o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<E, Integer> entry : entries) { sb.append(entry.getKey());
sb.append(' '); sb.append(entry.getValue()); sb.append(' '); } return sb.toString(); } public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param) { if (param == null) return null; String[] array = param.split(" "); return create(array); } @SuppressWarnings("unchecked") public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param[]) { if (param.length % 2 == 0) return null; int natureCount = (param.length - 1) / 2; Map.Entry<String, Integer>[] entries = (Map.Entry<String, Integer>[]) Array.newInstance(Map.Entry.class, natureCount); for (int i = 0; i < natureCount; ++i) { entries[i] = new AbstractMap.SimpleEntry<String, Integer>(param[1 + 2 * i], Integer.parseInt(param[2 + 2 * i])); } return new AbstractMap.SimpleEntry<String, Map.Entry<String, Integer>[]>(param[0], entries); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\EnumItem.java
1
请完成以下Java代码
public class Crud { public static <R extends UpdatableRecord<R>> void save(UpdatableRecord<R> record) { record.store(); } public static Result<Record> getAll(DSLContext context, Table<? extends Record> table) { return context.select() .from(table) .fetch(); } public static Result<Record> getFields(DSLContext context, Table<? extends Record> table, SelectFieldOrAsterisk... fields) { return context.select(fields) .from(table) .fetch(); } public static <R extends Record> R getOne(DSLContext context, Table<R> table, Condition condition) { return context.fetchOne(table, condition); } public static <T> void update(DSLContext context, Table<? extends Record> table, Map<Field<T>, T> values, Condition condition) { context.update(table) .set(values) .where(condition) .execute(); }
public static <R extends UpdatableRecord<R>> void update(UpdatableRecord<R> record) { record.update(); } public static void delete(DSLContext context, Table<? extends Record> table, Condition condition) { context.delete(table) .where(condition) .execute(); } public static <R extends UpdatableRecord<R>> void delete(UpdatableRecord<R> record) { record.delete(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\Crud.java
1
请完成以下Java代码
public class UserSettingsEntity implements ToData<UserSettings> { @Id @Column(name = ModelConstants.USER_SETTINGS_USER_ID_PROPERTY) private UUID userId; @Id @Column(name = ModelConstants.USER_SETTINGS_TYPE_PROPERTY) private String type; @Convert(converter = JsonConverter.class) @JdbcType(PostgreSQLJsonPGObjectJsonbType.class) @Column(name = ModelConstants.USER_SETTINGS_SETTINGS, columnDefinition = "jsonb") private JsonNode settings; public UserSettingsEntity(UserSettings userSettings) { this.userId = userSettings.getUserId().getId(); this.type = userSettings.getType().name(); if (userSettings.getSettings() != null) { this.settings = userSettings.getSettings();
} } @Override public UserSettings toData() { UserSettings userSettings = new UserSettings(); userSettings.setUserId(new UserId(userId)); userSettings.setType(UserSettingsType.valueOf(type)); if (settings != null) { userSettings.setSettings(settings); } return userSettings; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\UserSettingsEntity.java
1
请完成以下Java代码
public boolean isInDispute () { Object oo = get_Value(COLUMNNAME_IsInDispute); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open Amount. @param OpenAmt Open item amount */ public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Times Dunned. @param TimesDunned Number of times dunned previously */ public void setTimesDunned (int TimesDunned) { set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned)); }
/** Get Times Dunned. @return Number of times dunned previously */ public int getTimesDunned () { Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned); if (ii == null) return 0; return ii.intValue(); } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java
1
请完成以下Java代码
public class DelegatingSecurityContextSchedulingTaskExecutor extends DelegatingSecurityContextAsyncTaskExecutor implements SchedulingTaskExecutor { /** * Creates a new {@link DelegatingSecurityContextSchedulingTaskExecutor} that uses the * specified {@link SecurityContext}. * @param delegateSchedulingTaskExecutor the {@link SchedulingTaskExecutor} to * delegate to. Cannot be null. * @param securityContext the {@link SecurityContext} to use for each * {@link DelegatingSecurityContextRunnable} and * {@link DelegatingSecurityContextCallable} */ public DelegatingSecurityContextSchedulingTaskExecutor(SchedulingTaskExecutor delegateSchedulingTaskExecutor, @Nullable SecurityContext securityContext) { super(delegateSchedulingTaskExecutor, securityContext); } /** * Creates a new {@link DelegatingSecurityContextSchedulingTaskExecutor} that uses the * current {@link SecurityContext}. * @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to.
* Cannot be null. */ public DelegatingSecurityContextSchedulingTaskExecutor(SchedulingTaskExecutor delegateAsyncTaskExecutor) { this(delegateAsyncTaskExecutor, null); } @Override public boolean prefersShortLivedTasks() { return getDelegate().prefersShortLivedTasks(); } private SchedulingTaskExecutor getDelegate() { return (SchedulingTaskExecutor) getDelegateExecutor(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\scheduling\DelegatingSecurityContextSchedulingTaskExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public void updatePassword(String telephone, String password, String authCode) { UmsMemberExample example = new UmsMemberExample(); example.createCriteria().andPhoneEqualTo(telephone); List<UmsMember> memberList = memberMapper.selectByExample(example); if(CollectionUtils.isEmpty(memberList)){ Asserts.fail("该账号不存在"); } //验证验证码 if(!verifyAuthCode(authCode,telephone)){ Asserts.fail("验证码错误"); } UmsMember umsMember = memberList.get(0); umsMember.setPassword(passwordEncoder.encode(password)); memberMapper.updateByPrimaryKeySelective(umsMember); memberCacheService.delMember(umsMember.getId()); } @Override public UmsMember getCurrentMember() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); MemberDetails memberDetails = (MemberDetails) auth.getPrincipal(); return memberDetails.getUmsMember(); } @Override public void updateIntegration(Long id, Integer integration) { UmsMember record=new UmsMember(); record.setId(id); record.setIntegration(integration); memberMapper.updateByPrimaryKeySelective(record); memberCacheService.delMember(id); } @Override public UserDetails loadUserByUsername(String username) { UmsMember member = getByUsername(username); if(member!=null){ return new MemberDetails(member); } throw new UsernameNotFoundException("用户名或密码错误"); } @Override public String login(String username, String password) { String token = null;
//密码需要客户端加密后传递 try { UserDetails userDetails = loadUserByUsername(username); if(!passwordEncoder.matches(password,userDetails.getPassword())){ throw new BadCredentialsException("密码不正确"); } UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); token = jwtTokenUtil.generateToken(userDetails); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; } @Override public String refreshToken(String token) { return jwtTokenUtil.refreshHeadToken(token); } //对输入的验证码进行校验 private boolean verifyAuthCode(String authCode, String telephone){ if(StrUtil.isEmpty(authCode)){ return false; } String realAuthCode = memberCacheService.getAuthCode(telephone); return authCode.equals(realAuthCode); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberServiceImpl.java
2
请完成以下Java代码
public void initialize() { someDependency.getReady(); } @PreDestroy public void cleanup() { System.out.println("Cleanup"); } } @Component class SomeDependency { public void getReady() { System.out.println("Some logic using SomeDependency"); }
} @Configuration @ComponentScan public class PrePostAnnotationsContextLauncherApplication { public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext (PrePostAnnotationsContextLauncherApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()) .forEach(System.out::println); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\f1\PrePostAnnotationsContextLauncherApplication.java
1
请完成以下Java代码
public void setC_Year_ID (int C_Year_ID) { if (C_Year_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Year_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID)); } /** Get Year. @return Calendar Year */ public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Demand. @param M_Demand_ID Material Demand */ public void setM_Demand_ID (int M_Demand_ID) { if (M_Demand_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Demand_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Demand_ID, Integer.valueOf(M_Demand_ID)); } /** Get Demand. @return Material Demand */ public int getM_Demand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Demand.java
1
请完成以下Java代码
private IQueryBuilder<Object> toQueryBuilder(final SqlDocumentEntityDataBindingDescriptor dataBinding, final DocumentId documentId) { final String tableName = dataBinding.getTableName(); final List<SqlDocumentFieldDataBindingDescriptor> keyFields = dataBinding.getKeyFields(); final int keyFieldsCount = keyFields.size(); if (keyFieldsCount == 0) { throw new AdempiereException("No primary key defined for " + tableName); } final List<Object> keyParts = documentId.toComposedKeyParts(); if (keyFieldsCount != keyParts.size()) { throw new AdempiereException("Invalid documentId '" + documentId + "'. It shall have " + keyFieldsCount + " parts but it has " + keyParts.size()); } final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(tableName, PlainContextAware.newWithThreadInheritedTrx()); for (int i = 0; i < keyFieldsCount; i++) { final SqlDocumentFieldDataBindingDescriptor keyField = keyFields.get(i); final String keyColumnName = keyField.getColumnName(); final Object keyValue = convertToPOValue(keyParts.get(i), keyColumnName, keyField.getWidgetType(), keyField.getSqlValueClass()); queryBuilder.addEqualsFilter(keyColumnName, keyValue); } return queryBuilder; } private static TableRecordReference extractRootRecordReference(final Document includedDocument) { if (includedDocument.isRootDocument()) { return null; } final Document rootDocument = includedDocument.getRootDocument(); final String rootTableName = rootDocument.getEntityDescriptor().getTableNameOrNull(); if (rootTableName == null) { return null; }
final int rootRecordId = rootDocument.getDocumentId().toIntOr(-1); if (rootRecordId < 0) { return null; } return TableRecordReference.of(rootTableName, rootRecordId); } private static DocumentId extractDocumentId(final PO po, SqlDocumentEntityDataBindingDescriptor dataBinding) { if (dataBinding.isSingleKey()) { return DocumentId.of(InterfaceWrapperHelper.getId(po)); } else { final List<SqlDocumentFieldDataBindingDescriptor> keyFields = dataBinding.getKeyFields(); if (keyFields.isEmpty()) { throw new AdempiereException("No primary key defined for " + dataBinding.getTableName()); } final List<Object> keyParts = keyFields.stream() .map(keyField -> po.get_Value(keyField.getColumnName())) .collect(ImmutableList.toImmutableList()); return DocumentId.ofComposedKeyParts(keyParts); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\save\DefaultSaveHandler.java
1
请完成以下Java代码
public class Round { private static final double PI = 3.1415d; public static void main (String args[]) { System.out.println("PI: " + PI); System.out.printf("Value with 3 digits after decimal point %.3f %n", PI); // OUTPUTS: Value with 3 digits after decimal point 3.142 DecimalFormat df = new DecimalFormat("###.###"); System.out.println(df.format(PI)); System.out.println(round(PI, 3)); System.out.println(roundNotPrecise(PI, 3)); System.out.println(roundAvoid(PI, 3)); System.out.println(Precision.round(PI, 3)); System.out.println(DoubleRounder.round(PI, 3)); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(Double.toString(value)); bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue(); } public static double roundNotPrecise(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public static double roundAvoid(double value, int places) { double scale = Math.pow(10, places); double rounded = Math.round(value * scale) / scale; return rounded; } }
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\maths\Round.java
1
请完成以下Java代码
public void setBackground(Color bg) { if (bg.equals(getBackground())) return; super.setBackground( bg); } // setBackground /** * Set Background - NOP * @param error */ @Override public void setBackground (boolean error) { } // setBackground /** * Set Standard Background */ public void setBackgroundColor () { setBackgroundColor (null); } // setBackground /** * Set Background * @param bg AdempiereColor for Background, if null set standard background */ public void setBackgroundColor (MFColor bg) { if (bg == null) bg = MFColor.ofFlatColor(AdempierePLAF.getFormBackground()); setOpaque(true); putClientProperty(AdempiereLookAndFeel.BACKGROUND, bg); super.setBackground (bg.getFlatColor()); } // setBackground /** * Get Background * @return Color for Background */ public MFColor getBackgroundColor () { try { return (MFColor)getClientProperty(AdempiereLookAndFeel.BACKGROUND); } catch (Exception e) { System.err.println("CButton - ClientProperty: " + e.getMessage()); } return null; } // getBackgroundColor /** Mandatory (default false) */ private boolean m_mandatory = false; /** * Set Editor Mandatory * @param mandatory true, if you have to enter data */ @Override public void setMandatory (boolean mandatory) { m_mandatory = mandatory; setBackground(false); } // setMandatory /** * Is Field mandatory * @return true, if mandatory */ @Override public boolean isMandatory() { return m_mandatory; } // isMandatory /** * Enable Editor * @param rw true, if you can enter/select data */ @Override public void setReadWrite (boolean rw) { if (super.isEnabled() != rw)
super.setEnabled(rw); } // setReadWrite /** * Is it possible to edit * @return true, if editable */ @Override public boolean isReadWrite() { return super.isEnabled(); } // isReadWrite /** * Set Editor to value * @param value value of the editor */ @Override public void setValue (Object value) { if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */ @Override public Object getValue() { return getText(); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return getText(); } // getDisplay } // CToggleButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CToggleButton.java
1
请完成以下Java代码
public boolean isSameLine() { return sameLine; } public void setSameLine(final boolean sameLine) { this.sameLine = sameLine; } /** * Is this a long (string/text) field (over 60/2=30 characters) * * @return true if long field */ public boolean isLongField() { // if (m_vo.displayType == DisplayType.String // || m_vo.displayType == DisplayType.Text // || m_vo.displayType == DisplayType.Memo // || m_vo.displayType == DisplayType.TextLong // || m_vo.displayType == DisplayType.Image) return displayLength >= MAXDISPLAY_LENGTH / 2; // return false; } // isLongField public int getSpanX() { return spanX; } public int getSpanY() { return spanY; } public static final class Builder { private int displayLength = 0; private int columnDisplayLength = 0; private boolean sameLine = false; private int spanX = 1; private int spanY = 1; private Builder() { super(); } public GridFieldLayoutConstraints build()
{ return new GridFieldLayoutConstraints(this); } public Builder setDisplayLength(final int displayLength) { this.displayLength = displayLength; return this; } public Builder setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; return this; } public Builder setSameLine(final boolean sameLine) { this.sameLine = sameLine; return this; } public Builder setSpanX(final int spanX) { this.spanX = spanX; return this; } public Builder setSpanY(final int spanY) { this.spanY = spanY; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldLayoutConstraints.java
1
请完成以下Java代码
public List<MoveExecutionEntityContainer> getMoveExecutionEntityContainers() { return moveExecutionEntityContainers; } public ProcessInstanceChangeState setMoveExecutionEntityContainers(List<MoveExecutionEntityContainer> moveExecutionEntityContainers) { this.moveExecutionEntityContainers = moveExecutionEntityContainers; return this; } public HashMap<String, ExecutionEntity> getCreatedEmbeddedSubProcesses() { return createdEmbeddedSubProcess; } public Optional<ExecutionEntity> getCreatedEmbeddedSubProcessByKey(String key) { return Optional.ofNullable(createdEmbeddedSubProcess.get(key)); } public void addCreatedEmbeddedSubProcess(String key, ExecutionEntity executionEntity) { this.createdEmbeddedSubProcess.put(key, executionEntity); } public HashMap<String, ExecutionEntity> getCreatedMultiInstanceRootExecution() { return createdMultiInstanceRootExecution; } public void setCreatedMultiInstanceRootExecution(HashMap<String, ExecutionEntity> createdMultiInstanceRootExecution) { this.createdMultiInstanceRootExecution = createdMultiInstanceRootExecution; } public void addCreatedMultiInstanceRootExecution(String key, ExecutionEntity executionEntity) { this.createdMultiInstanceRootExecution.put(key, executionEntity); }
public Map<String, List<ExecutionEntity>> getProcessInstanceActiveEmbeddedExecutions() { return processInstanceActiveEmbeddedExecutions; } public ProcessInstanceChangeState setProcessInstanceActiveEmbeddedExecutions(Map<String, List<ExecutionEntity>> processInstanceActiveEmbeddedExecutions) { this.processInstanceActiveEmbeddedExecutions = processInstanceActiveEmbeddedExecutions; return this; } public HashMap<StartEvent, ExecutionEntity> getPendingEventSubProcessesStartEvents() { return pendingEventSubProcessesStartEvents; } public void addPendingEventSubProcessStartEvent(StartEvent startEvent, ExecutionEntity eventSubProcessParent) { this.pendingEventSubProcessesStartEvents.put(startEvent, eventSubProcessParent); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\ProcessInstanceChangeState.java
1
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Position Assignment. @param C_JobAssignment_ID Assignemt of Employee (User) to Job Position */ public void setC_JobAssignment_ID (int C_JobAssignment_ID) { if (C_JobAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_C_JobAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_C_JobAssignment_ID, Integer.valueOf(C_JobAssignment_ID)); } /** Get Position Assignment. @return Assignemt of Employee (User) to Job Position */ public int getC_JobAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_JobAssignment_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Job getC_Job() throws RuntimeException { return (I_C_Job)MTable.get(getCtx(), I_C_Job.Table_Name) .getPO(getC_Job_ID(), get_TrxName()); } /** Set Position. @param C_Job_ID Job Position */ public void setC_Job_ID (int C_Job_ID) { if (C_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Job_ID, Integer.valueOf(C_Job_ID)); } /** Get Position. @return Job Position */ public int getC_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_Job_ID())); } /** Set Description. @param Description Optional short description of the record */
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<RequestInfo> getRequestParameters(HttpServletRequest request) throws IOException { LOG.info("getRequestParameters: {}?{}", request.getRequestURL(), request.getQueryString()); String body = request.getReader().lines().collect(Collectors.joining()); RequestInfo requestInfo = new RequestInfo(applicationConfig.getId(), request.getRequestURL().toString(), request.getQueryString(), body, request.getCharacterEncoding(), request.getMethod(), createCookiesMap(request.getCookies()), request.getContentType(), createHeaderMap(request), request.getProtocol(), createRemoteInfo(request)); return ResponseEntity.ok(requestInfo); } @GetMapping(path="/very-long-number") public ResponseEntity<NumberWrapper> getVeryLongNumber() { return ResponseEntity.ok(new NumberWrapper(4855910445484272258L)); } private Map<String, String> createCookiesMap(Cookie[] cookies) { Map<String, String> cookiesMap = new HashMap<>(); if (cookies != null) { for (Cookie cookie : cookies) { String id = cookie.getDomain() + ":" + cookie.getName(); cookiesMap.put(id, cookie.toString()); } } return cookiesMap; }
private Map<String, List<String>> createHeaderMap(HttpServletRequest request) { Map<String, List<String>> headers = new HashMap<>(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { List<String> headerValues = new ArrayList<>(); String headerName = headerNames.nextElement(); Enumeration<String> values = request.getHeaders(headerName); while (values.hasMoreElements()) { headerValues.add(values.nextElement()); } headers.put(headerName, headerValues); } } return headers; } private String createRemoteInfo(HttpServletRequest request) { return request.getRemoteHost() + ":" + request.getRemotePort(); } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\controller\DataServiceController.java
2
请完成以下Java代码
public static String concatenateUsingStringJoiner(String[] values) { StringJoiner result = new StringJoiner(""); for (String value : values) { result = result.add(getNonNullString(value)); } return result.toString(); } public static String concatenateUsingJoin(String[] values) { String result = String.join("", values); return result; } public static String concatenateUsingStringBuilder(String[] values) { StringBuilder result = new StringBuilder(); for (String value : values) { result = result.append(getNonNullString(value)); } return result.toString(); } public static String concatenateUsingHelperMethod(String[] values) { String result = ""; for (String value : values) { result = result + getNonNullString(value); }
return result; } public static String concatenateUsingPlusOperator(String[] values) { String result = ""; for (String value : values) { result = result + (value == null ? "" : value); } return result; } private static String getNonNullString(String value) { return value == null ? "" : value; } }
repos\tutorials-master\core-java-modules\core-java-string-operations-4\src\main\java\com\baeldung\concatenation\ConcatenatingNull.java
1