instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static Stream<Map.Entry<PickingSlotRowId, PickingSlotRowId>> streamChild2RootRowIdsRecursivelly(final PickingSlotRow row) { final PickingSlotRowId rootRowId = row.getPickingSlotRowId(); return row.streamThisRowAndIncludedRowsRecursivelly() .map(PickingSlotRow::getPickingSlotRowId) .map(includedRowId -> GuavaCollectors.entry(includedRowId, rootRowId)); } public PickingSlotRow getRow(final PickingSlotRowId rowId) { return rowsById.get(rowId); } @Nullable public PickingSlotRow getRootRow(final PickingSlotRowId rowId) { final PickingSlotRowId rootRowId = getRootRowId(rowId); if (rootRowId == null) { return null; }
return getRow(rootRowId); } public PickingSlotRowId getRootRowId(final PickingSlotRowId rowId) { return rowId2rootRowId.get(rowId); } public long size() { return rowsById.size(); } public Stream<PickingSlotRow> stream() { return rowsById.values().stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowsCollection.java
1
请完成以下Java代码
public static ILoggable withLogger(@NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(get(), logger, level); } @NonNull public static ILoggable withFallbackToLogger(@NonNull final Logger logger, @NonNull final Level level) { final ILoggable threadLocalLoggable = get(); if (NullLoggable.isNull(threadLocalLoggable)) { return new LoggableWithLogger(NullLoggable.instance, logger, level); } else { return threadLocalLoggable; } } public static ILoggable withLogger(@NonNull final ILoggable loggable, @NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(loggable, logger, level); }
public static ILoggable withWarnLoggerToo(@NonNull final Logger logger) { return withLogger(logger, Level.WARN); } public static PlainStringLoggable newPlainStringLoggable() { return new PlainStringLoggable(); } public static ILoggable addLog(final String msg, final Object... msgParameters) { return get().addLog(msg, msgParameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Loggables.java
1
请完成以下Java代码
protected void applyFilters(HistoricIdentityLinkLogQuery query) { if (dateBefore != null) { query.dateBefore(dateBefore); } if (dateAfter != null) { query.dateAfter(dateAfter); } if (type != null) { query.type(type); } if (userId != null) { query.userId(userId); } if (groupId != null) { query.groupId(groupId); } if (taskId != null) { query.taskId(taskId); } if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionKey != null) { query.processDefinitionKey(processDefinitionKey); } if (operationType != null) { query.operationType(operationType); } if (assignerId != null) { query.assignerId(assignerId); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); }
} @Override protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_TIME)) { query.orderByTime(); } else if (sortBy.equals(SORT_BY_TYPE)) { query.orderByType(); } else if (sortBy.equals(SORT_BY_USER_ID)) { query.orderByUserId(); } else if (sortBy.equals(SORT_BY_GROUP_ID)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_TASK_ID)) { query.orderByTaskId(); } else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) { query.orderByOperationType(); } else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) { query.orderByAssignerId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogQueryDto.java
1
请完成以下Java代码
public class LocationTag { private String name; private int xPos; private int yPos; public LocationTag() { } public LocationTag(String name, int xPos, int yPos) { super(); this.name = name; this.xPos = xPos; this.yPos = yPos; } public String getName() { return name; }
public int getxPos() { return xPos; } public void setxPos(int xPos) { this.xPos = xPos; } public int getyPos() { return yPos; } public void setyPos(int yPos) { this.yPos = yPos; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-filtering\src\main\java\com\baeldung\inmemory\persistence\model\LocationTag.java
1
请完成以下Java代码
public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setPP_Order_IssueSchedule_ID (final int PP_Order_IssueSchedule_ID) { if (PP_Order_IssueSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_IssueSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_IssueSchedule_ID, PP_Order_IssueSchedule_ID); } @Override public int getPP_Order_IssueSchedule_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_IssueSchedule_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyIssued (final BigDecimal QtyIssued) { set_Value (COLUMNNAME_QtyIssued, QtyIssued); } @Override public BigDecimal getQtyIssued() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyIssued); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReject (final @Nullable BigDecimal QtyReject) { set_Value (COLUMNNAME_QtyReject, QtyReject); } @Override public BigDecimal getQtyReject() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToIssue (final BigDecimal QtyToIssue) { set_ValueNoCheck (COLUMNNAME_QtyToIssue, QtyToIssue); } @Override public BigDecimal getQtyToIssue() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue); return bd != null ? bd : BigDecimal.ZERO; }
/** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_ValueNoCheck (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_IssueSchedule.java
1
请完成以下Java代码
public void setM_Product_Certificate_ID (int M_Product_Certificate_ID) { if (M_Product_Certificate_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, Integer.valueOf(M_Product_Certificate_ID)); } /** Get Label_ID. @return Label_ID */ @Override public int getM_Product_Certificate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Certificate_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Certificate.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityRestController { private final UserAccessService userAccessService; private final HttpServletRequest request; @Autowired public SecurityRestController(UserAccessService userAccessService, HttpServletRequest request) { this.userAccessService = userAccessService; this.request = request; } @PostMapping("/login") public ResponseEntity<UserData> login(@RequestBody LoginUserNamePasswordRequest loginRequest) { Optional<UserData> userData = userAccessService.login(new LoginRequest(UserId.from(loginRequest.getUserName()), loginRequest.getPassword())); if (userData.isPresent()) { return ResponseEntity.ok().body(userData.get()); } else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } } @GetMapping("/logout") public ResponseEntity<Void> logout() { String authorization = request.getHeader("Authorization"); JWToken jwToken = JWToken.from(JWTUtils.extractJwtToken(authorization)); if (userAccessService.logout(jwToken)) { return ResponseEntity.ok().build(); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } } }
repos\spring-examples-java-17\spring-security-jwt\src\main\java\itx\examples\springboot\security\springsecurity\jwt\rest\SecurityRestController.java
2
请在Spring Boot框架中完成以下Java代码
public class Employee { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "employee_number", unique = true) private String empNumber; @Column(name = "employee_name") private String name; @Column(name = "employee_age") private int age; public Employee() { super(); } public Employee(Long id, String empNumber) { super(); this.id = id; this.empNumber = empNumber; } public Long getId() { return id; } public void setId(Long id) {
this.id = id; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } public String getEmpNumber() { return empNumber; } public void setEmpNumber(String empNumber) { this.empNumber = empNumber; } public static long getSerialversionuid() { return serialVersionUID; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\queryparams\Employee.java
2
请完成以下Spring Boot application配置
server: port: 8080 spring: application: name: Eureka-Server eureka: instance: hostname: peer1 client: serviceUrl: defaultZone: http://mrbird
:123456@peer2:8081/eureka/ server: enable-self-preservation: false
repos\SpringAll-master\28.Spring-Cloud-Eureka-Server-Discovery\Eureka-Service\src\main\resources\application-peer1.yml
2
请在Spring Boot框架中完成以下Java代码
public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public ContentNegotiatingViewResolver viewResolver(ContentNegotiationManager cnManager) { ContentNegotiatingViewResolver cnvResolver = new ContentNegotiatingViewResolver(); cnvResolver.setContentNegotiationManager(cnManager); List<ViewResolver> resolvers = new ArrayList<>(); InternalResourceViewResolver bean = new InternalResourceViewResolver("/WEB-INF/views/",".jsp"); ArticleRssFeedViewResolver articleRssFeedViewResolver = new ArticleRssFeedViewResolver(); resolvers.add(bean); resolvers.add(articleRssFeedViewResolver); cnvResolver.setViewResolvers(resolvers); return cnvResolver; } @Bean public MultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
return multipartResolver; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new StringHttpMessageConverter()); converters.add(new RssChannelHttpMessageConverter()); converters.add(new JsonChannelHttpMessageConverter()); } @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToEnumConverter()); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\configuration\ApplicationConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class Car implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @Column(name = "id") private Long id; @Column(name = "price") private Double price; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return this.id; } public Car id(Long id) { this.setId(id); return this; } public void setId(Long id) { this.id = id; } public Double getPrice() { return this.price; } public Car price(Double price) { this.setPrice(price); return this; } public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Car)) { return false; } return getId() != null && getId().equals(((Car) o).getId()); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Car{" + "id=" + getId() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\domain\Car.java
2
请完成以下Java代码
public int size() { return cookieMap.size(); } @Override public boolean isEmpty() { return cookieMap.isEmpty(); } @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } @Override public Iterator<Cookie> iterator() { return cookieMap.values().iterator(); } public Cookie[] toArray() { Cookie[] cookies = new Cookie[cookieMap.size()]; return toArray(cookies); } @Override public <T> T[] toArray(T[] ts) { return cookieMap.values().toArray(ts); } @Override public boolean add(Cookie cookie) { if (cookie == null) { return false; } cookieMap.put(cookie.getName(), cookie); return true; } @Override public boolean remove(Object o) { if (o instanceof String) { return cookieMap.remove((String)o) != null; } if (o instanceof Cookie) { Cookie c = (Cookie)o; return cookieMap.remove(c.getName()) != null; } return false; } public Cookie get(String name) { return cookieMap.get(name); } @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends Cookie> collection) {
boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } @Override public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } @Override public void clear() { cookieMap.clear(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\CookieCollection.java
1
请在Spring Boot框架中完成以下Java代码
public void fetchBooksOfAuthorById() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); System.out.println(books); } public void fetchPageBooksOfAuthorById() { Page<Book> books = bookRepository.fetchPageBooksOfAuthorById(4L, PageRequest.of(0, 2, Sort.by(Sort.Direction.ASC, "title"))); books.get().forEach(System.out::println); } @Transactional public void fetchBooksOfAuthorByIdAndAddNewBook() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); Book book = new Book(); book.setIsbn("004-JN");
book.setTitle("History Facts"); book.setAuthor(books.get(0).getAuthor()); books.add(bookRepository.save(book)); System.out.println(books); } @Transactional public void fetchBooksOfAuthorByIdAndDeleteFirstBook() { List<Book> books = bookRepository.fetchBooksOfAuthorById(4L); bookRepository.delete(books.remove(0)); System.out.println(books); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJustManyToOne\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public String getSourceRef() { return sourceRef; } public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; } public String getMessageRef() { return messageRef; } public void setMessageRef(String messageRef) { this.messageRef = messageRef; } @Override public String toString() { return sourceRef + " --> " + targetRef; }
@Override public MessageFlow clone() { MessageFlow clone = new MessageFlow(); clone.setValues(this); return clone; } public void setValues(MessageFlow otherFlow) { super.setValues(otherFlow); setName(otherFlow.getName()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setMessageRef(otherFlow.getMessageRef()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MessageFlow.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonPickingStepEvent { // // Picking Line/Step Identifier @NonNull String wfProcessId; @NonNull String wfActivityId; @NonNull String pickingLineId; @Nullable String pickingStepId; // // Event Type public enum EventType {PICK, UNPICK} @NonNull EventType type; // // Common @NonNull String huQRCode; //
// Event Type: PICK @Nullable BigDecimal qtyPicked; @Nullable BigDecimal qtyRejected; @Nullable String qtyRejectedReasonCode; @Nullable BigDecimal catchWeight; boolean pickWholeTU; @Nullable Boolean checkIfAlreadyPacked; boolean setBestBeforeDate; @Nullable @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") LocalDate bestBeforeDate; boolean setLotNo; @Nullable String lotNo; boolean isCloseTarget; // Event Type: UNPICK @Nullable String unpickToTargetQRCode; }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\json\JsonPickingStepEvent.java
2
请完成以下Java代码
public class DeleteIdentityLinkCmd extends NeedsActiveTaskCmd<Void> { private static final long serialVersionUID = 1L; public static int IDENTITY_USER = 1; public static int IDENTITY_GROUP = 2; protected String userId; protected String groupId; protected String type; public DeleteIdentityLinkCmd(String taskId, String userId, String groupId, String type) { super(taskId); validateParams(userId, groupId, type, taskId); this.taskId = taskId; this.userId = userId; this.groupId = groupId; this.type = type; } protected void validateParams(String userId, String groupId, String type, String taskId) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } if (type == null) { throw new ActivitiIllegalArgumentException("type is required when adding a new task identity link"); } // Special treatment for assignee and owner: group cannot be used and // userId may be null
if (IdentityLinkType.ASSIGNEE.equals(type) || IdentityLinkType.OWNER.equals(type)) { if (groupId != null) { throw new ActivitiIllegalArgumentException( "Incompatible usage: cannot use type '" + type + "' together with a groupId" ); } } else { if (userId == null && groupId == null) { throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null"); } } } protected Void execute(CommandContext commandContext, TaskEntity task) { if (IdentityLinkType.ASSIGNEE.equals(type)) { commandContext.getTaskEntityManager().changeTaskAssignee(task, null); } else if (IdentityLinkType.OWNER.equals(type)) { commandContext.getTaskEntityManager().changeTaskOwner(task, null); } else { commandContext.getIdentityLinkEntityManager().deleteIdentityLink(task, userId, groupId, type); } commandContext.getHistoryManager().createIdentityLinkComment(taskId, userId, groupId, type, false); return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteIdentityLinkCmd.java
1
请完成以下Java代码
public abstract class ServerWebExchangeMatchers { private ServerWebExchangeMatchers() { } /** * Creates a matcher that matches on the specific method and any of the provided * patterns. * @param method the method to match on. If null, any method will be matched * @param patterns the patterns to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(@Nullable HttpMethod method, String... patterns) { List<ServerWebExchangeMatcher> matchers = new ArrayList<>(patterns.length); for (String pattern : patterns) { matchers.add(new PathPatternParserServerWebExchangeMatcher(pattern, method)); } return new OrServerWebExchangeMatcher(matchers); } /** * Creates a matcher that matches on any of the provided patterns. * @param patterns the patterns to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(String... patterns) { return pathMatchers(null, patterns); } /** * Creates a matcher that matches on any of the provided {@link PathPattern}s. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(PathPattern... pathPatterns) { return pathMatchers(null, pathPatterns); } /** * Creates a matcher that matches on the specific method and any of the provided * {@link PathPattern}s. * @param method the method to match on. If null, any method will be matched. * @param pathPatterns the {@link PathPattern}s to match on * @return the matcher to use */ public static ServerWebExchangeMatcher pathMatchers(@Nullable HttpMethod method, PathPattern... pathPatterns) { List<ServerWebExchangeMatcher> matchers = new ArrayList<>(pathPatterns.length); for (PathPattern pathPattern : pathPatterns) { matchers.add(new PathPatternParserServerWebExchangeMatcher(pathPattern, method)); } return new OrServerWebExchangeMatcher(matchers); } /** * Creates a matcher that will match on any of the provided matchers
* @param matchers the matchers to match on * @return the matcher to use */ public static ServerWebExchangeMatcher matchers(ServerWebExchangeMatcher... matchers) { return new OrServerWebExchangeMatcher(matchers); } /** * Matches any exchange * @return the matcher to use */ @SuppressWarnings("Convert2Lambda") public static ServerWebExchangeMatcher anyExchange() { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered // LinkedHashMap return new ServerWebExchangeMatcher() { @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return ServerWebExchangeMatcher.MatchResult.match(); } }; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\ServerWebExchangeMatchers.java
1
请完成以下Java代码
protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) { ResourceEntity resource = new ResourceEntity(); resource.setName(name); resource.setBytes(bytes); resource.setDeploymentId(deploymentEntity.getId()); // Mark the resource as 'generated' resource.setGenerated(true); Context .getCommandContext() .getDbSqlSession() .insert(resource); } protected boolean isBpmnResource(String resourceName) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (resourceName.endsWith(suffix)) { return true; } } return false; } public ExpressionManager getExpressionManager() {
return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请在Spring Boot框架中完成以下Java代码
public Object getCreatedAt() { return createdAt; } public void setCreatedAt(Object createdAt) { this.createdAt = createdAt; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\configuration\AdvancedArticle.java
2
请完成以下Java代码
public void onHalfClose() { try { super.onHalfClose(); } catch (Exception ex) { logger.error("Exception caught in a RPC endpoint", ex.getMessage()); handleEndpointException(ex, serverCall); } } }; } private static <ReqT, RespT> void handleEndpointException(Exception ex, ServerCall<ReqT, RespT> serverCall) { logger.error("The ex.getMessage() = {}", ex.getMessage()); String ticket = new TicketService().createTicket(ex.getMessage()); //send the response back serverCall.close(Status.INTERNAL
.withCause(ex) .withDescription(ex.getMessage() + ", Ticket raised:" + ticket), new Metadata()); } private <ReqT, RespT> ServerCall.Listener<ReqT> handleInterceptorException(Throwable t, ServerCall<ReqT, RespT> serverCall) { String ticket = new TicketService().createTicket(t.getMessage()); serverCall.close(Status.INTERNAL .withCause(t) .withDescription("An exception occurred in a **subsequent** interceptor:" + ", Ticket raised:" + ticket), new Metadata()); return new ServerCall.Listener<ReqT>() { // no-op }; } }
repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\orderprocessing\orderprocessing\GlobalExceptionInterceptor.java
1
请完成以下Java代码
public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Exclude Lot. @param M_LotCtlExclude_ID Exclude the ability to create Lots in Attribute Sets */ public void setM_LotCtlExclude_ID (int M_LotCtlExclude_ID) { if (M_LotCtlExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, Integer.valueOf(M_LotCtlExclude_ID)); } /** Get Exclude Lot. @return Exclude the ability to create Lots in Attribute Sets */ public int getM_LotCtlExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtlExclude_ID); if (ii == null) return 0; return ii.intValue();
} public I_M_LotCtl getM_LotCtl() throws RuntimeException { return (I_M_LotCtl)MTable.get(getCtx(), I_M_LotCtl.Table_Name) .getPO(getM_LotCtl_ID(), get_TrxName()); } /** Set Lot Control. @param M_LotCtl_ID Product Lot Control */ public void setM_LotCtl_ID (int M_LotCtl_ID) { if (M_LotCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID)); } /** Get Lot Control. @return Product Lot Control */ public int getM_LotCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtlExclude.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsPermission extends PermissionBaseEntity { private static final long serialVersionUID = -2175597348886393330L; private String permissionName; // 权限名称 private String permission; // 权限标识 /** * 权限名称 * * @return */ public String getPermissionName() { return permissionName; } /** * 权限名称 * * @return */ public void setPermissionName(String permissionName) { this.permissionName = permissionName; } /**
* 权限标识 * * @return */ public String getPermission() { return permission; } /** * 权限标识 * * @return */ public void setPermission(String permission) { this.permission = permission; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsPermission.java
2
请完成以下Java代码
private boolean isAllowChangingDiscount(@NonNull final SOTrx soTrx) { final I_C_OrderLine orderLine = request.getOrderLine(); if (orderLine.isManualDiscount()) { return false; } if (soTrx.isPurchase()) { return true; } if (request.isUpdatePriceEnteredAndDiscountOnlyIfNotAlreadySet() && orderLine.getDiscount().signum() != 0) // task 06727 { return false; } return true; } private void updateProfitPriceActual(final I_C_OrderLine orderLineRecord) { final OrderLineRepository orderLineRepository = SpringContextHolder.instance.getBean(OrderLineRepository.class); final ProfitPriceActualFactory profitPriceActualFactory = SpringContextHolder.instance.getBean(ProfitPriceActualFactory.class); final OrderLine orderLine = orderLineRepository.ofRecord(orderLineRecord); final CalculateProfitPriceActualRequest request = CalculateProfitPriceActualRequest.builder() .bPartnerId(orderLine.getBPartnerId()) .productId(orderLine.getProductId()) .date(orderLine.getDatePromised().toLocalDate()) .baseAmount(orderLine.getPriceActual().toMoney()) .paymentTermId(orderLine.getPaymentTermId()) .quantity(orderLine.getOrderedQty()) .build(); final Money profitBasePrice = profitPriceActualFactory.calculateProfitPriceActual(request); orderLineRecord.setProfitPriceActual(profitBasePrice.toBigDecimal()); } @Nullable private UomId extractPriceUomId(@NonNull final IPricingResult pricingResult) { final I_C_OrderLine orderLine = request.getOrderLine(); return UomId.optionalOfRepoId(orderLine.getPrice_UOM_ID()) .orElse(pricingResult.getPriceUomId());
} public TaxCategoryId computeTaxCategoryId() { final IPricingContext pricingCtx = createPricingContext() .setDisallowDiscount(true); // don't bother computing discounts; we know that the tax category is not related to them. final IPricingResult pricingResult = pricingBL.calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { final I_C_OrderLine orderLine = request.getOrderLine(); throw new ProductNotOnPriceListException(pricingCtx, orderLine.getLine()) .setParameter("log", pricingResult.getLoggableMessages()); } return pricingResult.getTaxCategoryId(); } public IPricingResult computePrices() { final IEditablePricingContext pricingCtx = createPricingContext(); return pricingBL.calculatePrice(pricingCtx); } public PriceLimitRuleResult computePriceLimit() { final I_C_OrderLine orderLine = request.getOrderLine(); return pricingBL.computePriceLimit(PriceLimitRuleContext.builder() .pricingContext(createPricingContext()) .priceLimit(orderLine.getPriceLimit()) .priceActual(orderLine.getPriceActual()) .paymentTermId(orderLineBL.getPaymentTermId(orderLine)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePriceCalculator.java
1
请完成以下Java代码
public String index(Model model) { getDomain().ifPresent(d -> { model.addAttribute("domain", d); }); return "index"; } @RequestMapping("/user/index") public String userIndex(Model model) { getDomain().ifPresent(d -> { model.addAttribute("domain", d); }); return "user/index"; }
@RequestMapping("/login") public String login() { return "login"; } private Optional<String> getDomain() { Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); String domain = null; if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) { User user = (User) auth.getPrincipal(); domain = user.getDomain(); } return Optional.ofNullable(domain); } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\WebController.java
1
请完成以下Java代码
public class GlobalClientInterceptorRegistry { private final ApplicationContext applicationContext; private ImmutableList<ClientInterceptor> sortedClientInterceptors; /** * Creates a new GlobalClientInterceptorRegistry. * * @param applicationContext The application context to fetch the {@link GlobalClientInterceptorConfigurer} beans * from. */ public GlobalClientInterceptorRegistry(final ApplicationContext applicationContext) { this.applicationContext = requireNonNull(applicationContext, "applicationContext"); } /** * Gets the immutable list of global server interceptors. * * @return The list of globally registered server interceptors. */ public ImmutableList<ClientInterceptor> getClientInterceptors() { if (this.sortedClientInterceptors == null) { this.sortedClientInterceptors = ImmutableList.copyOf(initClientInterceptors()); } return this.sortedClientInterceptors; } /** * Initializes the list of client interceptors. *
* @return The list of global client interceptors. */ protected List<ClientInterceptor> initClientInterceptors() { final List<ClientInterceptor> interceptors = new ArrayList<>(); for (final GlobalClientInterceptorConfigurer configurer : this.applicationContext .getBeansOfType(GlobalClientInterceptorConfigurer.class).values()) { configurer.configureClientInterceptors(interceptors); } sortInterceptors(interceptors); return interceptors; } /** * Sorts the given list of interceptors. Use this method if you want to sort custom interceptors. The default * implementation will sort them by using then {@link AnnotationAwareOrderComparator}. * * @param interceptors The interceptors to sort. */ public void sortInterceptors(final List<? extends ClientInterceptor> interceptors) { interceptors.sort(beanFactoryAwareOrderComparator(this.applicationContext, ClientInterceptor.class)); } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\interceptor\GlobalClientInterceptorRegistry.java
1
请在Spring Boot框架中完成以下Java代码
public class LoginController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") @ResponseBody public ResponseBo login(String username, String password) { password = MD5Utils.encrypt(username, password); UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); return ResponseBo.ok(); } catch (UnknownAccountException e) { return ResponseBo.error(e.getMessage()); } catch (IncorrectCredentialsException e) { return ResponseBo.error(e.getMessage()); } catch (LockedAccountException e) { return ResponseBo.error(e.getMessage()); } catch (AuthenticationException e) { return ResponseBo.error("认证失败!");
} } @RequestMapping("/") public String redirectIndex() { return "redirect:/index"; } @RequestMapping("/index") public String index(Model model) { User user = (User) SecurityUtils.getSubject().getPrincipal(); model.addAttribute("user", user); return "index"; } }
repos\SpringAll-master\11.Spring-Boot-Shiro-Authentication\src\main\java\com\springboot\controller\LoginController.java
2
请完成以下Java代码
private static void normalizeArgsBeforeFormat(final Object[] args, final String adLanguage) { if (args == null || args.length == 0) { return; } for (int i = 0; i < args.length; i++) { final Object arg = args[i]; final Object argNorm = normalizeSingleArgumentBeforeFormat(arg, adLanguage); args[i] = argNorm; } } private static Object normalizeSingleArgumentBeforeFormat(@Nullable final Object arg, final String adLanguage) { if (arg == null) { return null; } else if (arg instanceof ITranslatableString) { return ((ITranslatableString)arg).translate(adLanguage); } else if (arg instanceof Amount) { return TranslatableStrings.amount((Amount)arg).translate(adLanguage); } else if (arg instanceof ReferenceListAwareEnum) { return normalizeSingleArgumentBeforeFormat_ReferenceListAwareEnum((ReferenceListAwareEnum)arg, adLanguage); } else if (arg instanceof Iterable) { @SuppressWarnings("unchecked") final Iterable<Object> iterable = (Iterable<Object>)arg; return normalizeSingleArgumentBeforeFormat_Iterable(iterable, adLanguage); } else { return arg; } } private static Object normalizeSingleArgumentBeforeFormat_ReferenceListAwareEnum( @NonNull final ReferenceListAwareEnum referenceListAwareEnum, final String adLanguage) { final int adReferenceId = ReferenceListAwareEnums.getAD_Reference_ID(referenceListAwareEnum); if (adReferenceId > 0) { final ADReferenceService adReferenceService = ADReferenceService.get(); final ADRefListItem adRefListItem = adReferenceService.retrieveListItemOrNull(adReferenceId, referenceListAwareEnum.getCode()); if (adRefListItem != null) { return adRefListItem.getName().translate(adLanguage); }
} // Fallback return referenceListAwareEnum.toString(); } private static String normalizeSingleArgumentBeforeFormat_Iterable( @NonNull final Iterable<Object> iterable, final String adLanguage) { final StringBuilder result = new StringBuilder(); for (final Object item : iterable) { String itemNormStr; try { final Object itemNormObj = normalizeSingleArgumentBeforeFormat(item, adLanguage); itemNormStr = itemNormObj != null ? itemNormObj.toString() : "-"; } catch (Exception ex) { s_log.warn("Failed normalizing argument `{}`. Using toString().", item, ex); itemNormStr = item.toString(); } if (!(result.length() == 0)) { result.append(", "); } result.append(itemNormStr); } return result.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessageFormatter.java
1
请在Spring Boot框架中完成以下Java代码
public List<Error> getWarnings() { return warnings; } public void setWarnings(List<Error> warnings) { this.warnings = warnings; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingFulfillmentPagedCollection shippingFulfillmentPagedCollection = (ShippingFulfillmentPagedCollection)o; return Objects.equals(this.fulfillments, shippingFulfillmentPagedCollection.fulfillments) && Objects.equals(this.total, shippingFulfillmentPagedCollection.total) && Objects.equals(this.warnings, shippingFulfillmentPagedCollection.warnings); } @Override public int hashCode() { return Objects.hash(fulfillments, total, warnings); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class ShippingFulfillmentPagedCollection {\n"); sb.append(" fulfillments: ").append(toIndentedString(fulfillments)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append(" warnings: ").append(toIndentedString(warnings)).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(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingFulfillmentPagedCollection.java
2
请完成以下Java代码
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception { xtw.writeStartDocument(encoding, "1.0"); // start definitions root element xtw.writeStartElement(ELEMENT_DEFINITIONS); xtw.setDefaultNamespace(BPMN2_NAMESPACE); xtw.writeDefaultNamespace(BPMN2_NAMESPACE); xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE); xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE); xtw.writeNamespace(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE); xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE); xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE); xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE); for (String prefix : model.getNamespaces().keySet()) { if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix)) { xtw.writeNamespace(prefix, model.getNamespaces().get(prefix)); } } xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE); xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
if (StringUtils.isNotEmpty(model.getTargetNamespace())) { xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace()); } else { xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE); } if (StringUtils.isNotEmpty(model.getExporter())) { xtw.writeAttribute(BpmnXMLConstants.ATTRIBUTE_EXPORTER, model.getExporter()); } if (StringUtils.isNotEmpty(model.getExporterVersion())) { xtw.writeAttribute(BpmnXMLConstants.ATTRIBUTE_EXPORTER_VERSION, model.getExporterVersion()); } BpmnXMLUtil.writeCustomAttributes(model.getDefinitionsAttributes().values(), xtw, model.getNamespaces(), defaultAttributes); } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\export\DefinitionsRootExport.java
1
请完成以下Java代码
public PayPalHttpClient createPayPalHttpClient(@NonNull final PayPalConfig config) { final PayPalEnvironment environment = createPayPalEnvironment(config); return new PayPalHttpClient(environment); } private static PayPalEnvironment createPayPalEnvironment(@NonNull final PayPalConfig config) { if (!config.isSandbox()) { return new PayPalEnvironment( config.getClientId(), config.getClientSecret(), config.getBaseUrl(), config.getWebUrl()); } else { return new PayPalEnvironment.Sandbox( config.getClientId(), config.getClientSecret()); } } public PayPalConfig getConfig() { return payPalConfigProvider.getConfig(); } private <T> PayPalClientResponse<T, PayPalErrorResponse> executeRequest( @NonNull final HttpRequest<T> request, @NonNull final PayPalClientExecutionContext context) { final PayPalCreateLogRequestBuilder log = PayPalCreateLogRequest.builder() .paymentReservationId(context.getPaymentReservationId()) .paymentReservationCaptureId(context.getPaymentReservationCaptureId()) // .salesOrderId(context.getSalesOrderId()) .salesInvoiceId(context.getSalesInvoiceId()) .paymentId(context.getPaymentId()) // .internalPayPalOrderId(context.getInternalPayPalOrderId()); try { log.request(request); final PayPalHttpClient httpClient = createPayPalHttpClient(getConfig()); final HttpResponse<T> response = httpClient.execute(request); log.response(response); return PayPalClientResponse.ofResult(response.result()); } catch (final HttpException httpException) { log.response(httpException); final String errorAsJson = httpException.getMessage(); try { final PayPalErrorResponse error = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(errorAsJson, PayPalErrorResponse.class); return PayPalClientResponse.ofError(error, httpException);
} catch (final Exception jsonException) { throw AdempiereException.wrapIfNeeded(httpException) .suppressing(jsonException); } } catch (final IOException ex) { log.response(ex); throw AdempiereException.wrapIfNeeded(ex); } finally { logsRepo.log(log.build()); } } public Capture captureOrder( @NonNull final PayPalOrderAuthorizationId authId, @NonNull final Amount amount, @Nullable final Boolean finalCapture, @NonNull final PayPalClientExecutionContext context) { final AuthorizationsCaptureRequest request = new AuthorizationsCaptureRequest(authId.getAsString()) .requestBody(new CaptureRequest() .amount(new com.paypal.payments.Money() .currencyCode(amount.getCurrencyCode().toThreeLetterCode()) .value(amount.getAsBigDecimal().toPlainString())) .finalCapture(finalCapture)); return executeRequest(request, context) .getResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalClientService.java
1
请在Spring Boot框架中完成以下Java代码
class ObservationHandlerGroups { private final List<ObservationHandlerGroup> groups; ObservationHandlerGroups(Collection<? extends ObservationHandlerGroup> groups) { this.groups = Collections.unmodifiableList(sort(groups)); } private static List<ObservationHandlerGroup> sort(Collection<? extends ObservationHandlerGroup> groups) { ArrayList<ObservationHandlerGroup> sortedGroups = new ArrayList<>(groups); Collections.sort(sortedGroups); return sortedGroups; } void register(ObservationConfig config, List<ObservationHandler<?>> handlers) { MultiValueMap<ObservationHandlerGroup, ObservationHandler<?>> grouped = new LinkedMultiValueMap<>(); List<ObservationHandler<?>> unclaimed = new ArrayList<>(); for (ObservationHandler<?> handler : handlers) { ObservationHandlerGroup group = findGroup(handler); if (group == null) { unclaimed.add(handler); } else { grouped.add(group, handler); } } for (ObservationHandlerGroup group : this.groups) { List<ObservationHandler<?>> members = grouped.get(group); if (!CollectionUtils.isEmpty(members)) {
group.registerMembers(config, members); } } if (!CollectionUtils.isEmpty(unclaimed)) { for (ObservationHandler<?> handler : unclaimed) { config.observationHandler(handler); } } } private @Nullable ObservationHandlerGroup findGroup(ObservationHandler<?> handler) { for (ObservationHandlerGroup group : this.groups) { if (group.isMember(handler)) { return group; } } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationHandlerGroups.java
2
请在Spring Boot框架中完成以下Java代码
public static ServiceName forNoViewProcessApplicationStartService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("NO_VIEW"); } /** * @return the {@link ServiceName} of the {@link MscExecutorService}. */ public static ServiceName forMscExecutorService() { return BPM_PLATFORM.append("executor-service"); } /** * @return the {@link ServiceName} of the {@link MscRuntimeContainerJobExecutor} */ public static ServiceName forMscRuntimeContainerJobExecutorService(String jobExecutorName) { return JOB_EXECUTOR.append(jobExecutorName); } /** * @return the {@link ServiceName} of the {@link MscBpmPlatformPlugins} */ public static ServiceName forBpmPlatformPlugins() { return BPM_PLATFORM_PLUGINS; } /** * @return the {@link ServiceName} of the {@link ProcessApplicationStopService} */ public static ServiceName forProcessApplicationStopService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("STOP"); }
/** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.BoundedQueueThreadPoolService} */ public static ServiceName forManagedThreadPool(String threadPoolName) { return JOB_EXECUTOR.append(threadPoolName); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.ThreadFactoryService} */ public static ServiceName forThreadFactoryService(String threadFactoryName) { return ThreadsServices.threadFactoryName(threadFactoryName); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ServiceNames.java
2
请在Spring Boot框架中完成以下Java代码
protected ExternalWorkerJobQuery createExternalWorkerJobQuery() { if (managementService != null) { return managementService.createExternalWorkerJobQuery(); } else if (cmmnManagementService != null) { return cmmnManagementService.createExternalWorkerJobQuery(); } else { throw new FlowableException("Cannot query external jobs. There is no BPMN or CMMN engine available"); } } protected ExternalWorkerJob getExternalWorkerJobById(String jobId) { ExternalWorkerJob job = createExternalWorkerJobQuery().jobId(jobId).singleResult(); if (job == null) { throw new FlowableObjectNotFoundException("Could not find external worker job with id '" + jobId + "'.", ExternalWorkerJob.class); } if (restApiInterceptor != null) { restApiInterceptor.accessExternalWorkerJobById(job); } return job; }
@Autowired(required = false) public void setManagementService(ManagementService managementService) { this.managementService = managementService; } @Autowired(required = false) public void setCmmnManagementService(CmmnManagementService cmmnManagementService) { this.cmmnManagementService = cmmnManagementService; } @Autowired(required = false) public void setRestApiInterceptor(ExternalWorkerJobRestApiInterceptor restApiInterceptor) { this.restApiInterceptor = restApiInterceptor; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\ExternalWorkerJobBaseResource.java
2
请完成以下Java代码
public String getExecutionId() { Execution execution = getExecution(); if (execution != null) { return execution.getId(); } else { return null; } } @Override public Execution getExecution() { ExecutionEntity execution = getExecutionFromContext(); if(execution != null) { return execution; } else { return getScopedAssociation().getExecution(); } } @Override public TypedValue getVariable(String variableName) { ExecutionEntity execution = getExecutionFromContext(); if (execution != null) { return execution.getVariableTyped(variableName); } else { return getScopedAssociation().getVariable(variableName); } } @Override public void setVariable(String variableName, Object value) { ExecutionEntity execution = getExecutionFromContext(); if(execution != null) { execution.setVariable(variableName, value); execution.getVariable(variableName); } else { getScopedAssociation().setVariable(variableName, value); } } @Override public TypedValue getVariableLocal(String variableName) { ExecutionEntity execution = getExecutionFromContext(); if (execution != null) { return execution.getVariableLocalTyped(variableName); } else { return getScopedAssociation().getVariableLocal(variableName); } } @Override public void setVariableLocal(String variableName, Object value) { ExecutionEntity execution = getExecutionFromContext(); if(execution != null) { execution.setVariableLocal(variableName, value); execution.getVariableLocal(variableName); } else { getScopedAssociation().setVariableLocal(variableName, value); } }
protected ExecutionEntity getExecutionFromContext() { if(Context.getCommandContext() != null) { BpmnExecutionContext executionContext = Context.getBpmnExecutionContext(); if(executionContext != null) { return executionContext.getExecution(); } } return null; } public Task getTask() { ensureCommandContextNotActive(); return getScopedAssociation().getTask(); } public void setTask(Task task) { ensureCommandContextNotActive(); getScopedAssociation().setTask(task); } public VariableMap getCachedVariables() { ensureCommandContextNotActive(); return getScopedAssociation().getCachedVariables(); } public VariableMap getCachedLocalVariables() { ensureCommandContextNotActive(); return getScopedAssociation().getCachedVariablesLocal(); } public void flushVariableCache() { ensureCommandContextNotActive(); getScopedAssociation().flushVariableCache(); } protected void ensureCommandContextNotActive() { if(Context.getCommandContext() != null) { throw new ProcessEngineCdiException("Cannot work with scoped associations inside command context."); } } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\DefaultContextAssociationManager.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceRecipientExtensionType { @XmlElement(name = "Department") protected String department; @XmlElement(name = "CustomerReferenceNumber") protected String customerReferenceNumber; @XmlElement(name = "FiscalNumber") protected String fiscalNumber; /** * Department at the invoice recipient's side. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the customerReferenceNumber property. * * @return * possible object is * {@link String } * */ public String getCustomerReferenceNumber() { return customerReferenceNumber; } /** * Sets the value of the customerReferenceNumber property. * * @param value * allowed object is
* {@link String } * */ public void setCustomerReferenceNumber(String value) { this.customerReferenceNumber = value; } /** * Fiscal number of the invoice recipient. * * @return * possible object is * {@link String } * */ public String getFiscalNumber() { return fiscalNumber; } /** * Sets the value of the fiscalNumber property. * * @param value * allowed object is * {@link String } * */ public void setFiscalNumber(String value) { this.fiscalNumber = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\InvoiceRecipientExtensionType.java
2
请完成以下Java代码
public List<QualityInvoiceLineGroupType> getQualityInvoiceLineGroupTypes() { return QualityInvoiceLineGroupType_ForInvoicing; } @Override public int getC_DocTypeInvoice_DownPayment_ID() { if (_invoiceDocTypeDownPaymentId == null) { final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment; _invoiceDocTypeDownPaymentId = loadDocType(DocSubType.ofCode(docSubType)); } return _invoiceDocTypeDownPaymentId.getRepoId(); } @Override public int getC_DocTypeInvoice_FinalSettlement_ID() { if (_invoiceDocTypeFinalSettlementId == null) { final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement; _invoiceDocTypeFinalSettlementId = loadDocType(DocSubType.ofCode(docSubType)); } return _invoiceDocTypeFinalSettlementId.getRepoId(); } /** * Returns true if the scrap percentage treshold is less than 100. */ @Override public boolean isFeeForScrap()
{ return getScrapPercentageTreshold().compareTo(new BigDecimal("100")) < 0; } private DocTypeId loadDocType(final DocSubType docSubType) { final IContextAware context = getContext(); final Properties ctx = context.getCtx(); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); // FIXME: not sure if it's ok return Services.get(IDocTypeDAO.class).getDocTypeId( DocTypeQuery.builder() .docBaseType(X_C_DocType.DOCBASETYPE_APInvoice) .docSubType(docSubType) .adClientId(adClientId) .adOrgId(adOrgId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\AbstractQualityBasedConfig.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxMessagesPerPoll() { return this.maxMessagesPerPoll; } public void setMaxMessagesPerPoll(int maxMessagesPerPoll) { this.maxMessagesPerPoll = maxMessagesPerPoll; } public Duration getReceiveTimeout() { return this.receiveTimeout; } public void setReceiveTimeout(Duration receiveTimeout) { this.receiveTimeout = receiveTimeout; } public @Nullable Duration getFixedDelay() { return this.fixedDelay; } public void setFixedDelay(@Nullable Duration fixedDelay) { this.fixedDelay = fixedDelay; } public @Nullable Duration getFixedRate() { return this.fixedRate; } public void setFixedRate(@Nullable Duration fixedRate) { this.fixedRate = fixedRate; } public @Nullable Duration getInitialDelay() { return this.initialDelay; } public void setInitialDelay(@Nullable Duration initialDelay) { this.initialDelay = initialDelay; } public @Nullable String getCron() { return this.cron; } public void setCron(@Nullable String cron) { this.cron = cron; } } public static class Management { /** * Whether Spring Integration components should perform logging in the main * message flow. When disabled, such logging will be skipped without checking the * logging level. When enabled, such logging is controlled as normal by the * logging system's log level configuration. */ private boolean defaultLoggingEnabled = true;
/** * List of simple patterns to match against the names of Spring Integration * components. When matched, observation instrumentation will be performed for the * component. Please refer to the javadoc of the smartMatch method of Spring * Integration's PatternMatchUtils for details of the pattern syntax. */ private List<String> observationPatterns = new ArrayList<>(); public boolean isDefaultLoggingEnabled() { return this.defaultLoggingEnabled; } public void setDefaultLoggingEnabled(boolean defaultLoggingEnabled) { this.defaultLoggingEnabled = defaultLoggingEnabled; } public List<String> getObservationPatterns() { return this.observationPatterns; } public void setObservationPatterns(List<String> observationPatterns) { this.observationPatterns = observationPatterns; } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationProperties.java
2
请完成以下Java代码
public boolean contains(DbEntity dbEntity) { return dbEntityCache.contains(dbEntity); } // getters / setters ///////////////////////////////// public DbOperationManager getDbOperationManager() { return dbOperationManager; } public void setDbOperationManager(DbOperationManager operationManager) { this.dbOperationManager = operationManager; } public DbEntityCache getDbEntityCache() { return dbEntityCache; } public void setDbEntityCache(DbEntityCache dbEntityCache) { this.dbEntityCache = dbEntityCache; } // query factory methods //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public CaseDefinitionQueryImpl createCaseDefinitionQuery() { return new CaseDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); } public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); }
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } public HistoricJobLogQueryImpl createHistoricJobLogQuery() { return new HistoricJobLogQueryImpl(); } public UserQueryImpl createUserQuery() { return new DbUserQueryImpl(); } public GroupQueryImpl createGroupQuery() { return new DbGroupQueryImpl(); } public void registerOptimisticLockingListener(OptimisticLockingListener optimisticLockingListener) { if(optimisticLockingListeners == null) { optimisticLockingListeners = new ArrayList<>(); } optimisticLockingListeners.add(optimisticLockingListener); } public List<String> getTableNamesPresentInDatabase() { return persistenceSession.getTableNamesPresent(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\DbEntityManager.java
1
请完成以下Java代码
public static QtyAvailableStatus computeOfQtyRequiredAndQtyAvailable(@NonNull final Quantity qtyRequired, @NonNull final Quantity qtyAvailable) { final Quantity qtyNotAvailable = qtyRequired.subtract(qtyAvailable); if (qtyNotAvailable.signum() <= 0) { return QtyAvailableStatus.FULLY_AVAILABLE; } else if (qtyAvailable.signum() > 0) { return QtyAvailableStatus.PARTIALLY_AVAILABLE; } else { return QtyAvailableStatus.NOT_AVAILABLE; } } public static <T> Optional<QtyAvailableStatus> computeOfLines( @NonNull final Collection<T> lines, @NonNull final Function<T, QtyAvailableStatus> getStatusFunc) { if (lines.isEmpty()) { return Optional.empty(); } boolean hasNotAvailableProducts = false; boolean hasFullyAvailableProducts = false; for (final T line : lines) { @Nullable final QtyAvailableStatus lineStatus = getStatusFunc.apply(line); if (lineStatus == null) {
return Optional.empty(); } switch (lineStatus) { case NOT_AVAILABLE: hasNotAvailableProducts = true; break; case PARTIALLY_AVAILABLE: return Optional.of(QtyAvailableStatus.PARTIALLY_AVAILABLE); case FULLY_AVAILABLE: hasFullyAvailableProducts = true; break; default: throw new AdempiereException("Unknown QtyAvailableStatus: " + lineStatus); } } if (hasFullyAvailableProducts) { return hasNotAvailableProducts ? Optional.of(QtyAvailableStatus.PARTIALLY_AVAILABLE) : Optional.of(QtyAvailableStatus.FULLY_AVAILABLE); } else { return Optional.of(QtyAvailableStatus.NOT_AVAILABLE); } } public boolean isPartialOrFullyAvailable() {return this == PARTIALLY_AVAILABLE || this == FULLY_AVAILABLE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\QtyAvailableStatus.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<String> chunk(Chunk chunk) { chunkService.chunk(chunk); return ResponseEntity.ok("File Chunk Upload Success"); } /** * merge * * @param filename * @return */ @GetMapping(value = "merge") public ResponseEntity<Void> merge(@RequestParam("filename") String filename) { chunkService.merge(filename); return ResponseEntity.ok().build(); } /** * get fileName * * @return files */
@GetMapping("/files") public ResponseEntity<List<FileInfo>> list() { return ResponseEntity.ok(chunkService.list()); } /** * get single file * * @param filename * @return file */ @GetMapping("/files/{filename:.+}") public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename) { return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").body(chunkService.getFile(filename)); } }
repos\springboot-demo-master\file\src\main\java\com\et\controller\ChunkController.java
2
请完成以下Java代码
public static byte[] readInputStream(InputStream inputStream, String inputStreamName) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[16*1024]; try { int bytesRead = inputStream.read(buffer); while (bytesRead!=-1) { outputStream.write(buffer, 0, bytesRead); bytesRead = inputStream.read(buffer); } } catch (Exception e) { throw LOG.exceptionWhileReadingStream(inputStreamName, e); } return outputStream.toByteArray(); } public static String readClasspathResourceAsString(String resourceName) { InputStream resourceAsStream = IoUtil.class.getClassLoader().getResourceAsStream(resourceName); if (resourceAsStream == null) { throw new ProcessEngineException("resource " + resourceName + " not found"); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int next; byte[] result; byte[] buffer = new byte[1024]; BufferedInputStream inputStream = null; try { inputStream = new BufferedInputStream(resourceAsStream); while ((next = inputStream.read(buffer)) >= 0) { outStream.write(buffer, 0, next); } result = outStream.toByteArray(); } catch(Exception e) { throw LOG.exceptionWhileReadingFile(resourceName, e); } finally { IoUtil.closeSilently(inputStream); IoUtil.closeSilently(outStream); } return new String(result, Charset.forName("UTF-8")); } public static File getFile(String filePath) { URL url = IoUtil.class.getClassLoader().getResource(filePath); try { return new File(url.toURI()); } catch (Exception e) { throw LOG.exceptionWhileGettingFile(filePath, e); } } public static void writeStringToFile(String content, String filePath) { BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); outputStream.write(content.getBytes()); outputStream.flush(); } catch(Exception e) { throw LOG.exceptionWhileWritingToFile(filePath, e); }
finally { IoUtil.closeSilently(outputStream); } } /** * Closes the given stream. The same as calling {@link Closeable#close()}, but * errors while closing are silently ignored. */ public static void closeSilently(Closeable closeable) { try { if(closeable != null) { closeable.close(); } } catch(IOException ignore) { LOG.debugCloseException(ignore); } } /** * Flushes the given object. The same as calling {@link Flushable#flush()}, but * errors while flushing are silently ignored. */ public static void flushSilently(Flushable flushable) { try { if(flushable != null) { flushable.flush(); } } catch(IOException ignore) { LOG.debugCloseException(ignore); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\IoUtil.java
1
请在Spring Boot框架中完成以下Java代码
public static java.util.Date parseTime(final String lexicalXSDTime) { final Calendar calendar = jakarta.xml.bind.DatatypeConverter.parseTime(lexicalXSDTime); return calendar.getTime(); } /** * <p> * Converts a time ({@link Date}) value into a string. * * @param val * A time ({@link Date}) value * @return A string containing a lexical representation of xsd:time * @throws IllegalArgumentException * if <tt>val</tt> is null. */ public static String printTime(final java.util.Date val) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(val); return jakarta.xml.bind.DatatypeConverter.printTime(calendar); } /** * <p> * Converts the string argument into a date/time ({@link Date}) value. * * @param lexicalXSDDateTime * A string containing lexical representation of xsd:dateTime. * @return A date/time ({@link Date}) value represented by the string argument. * @throws IllegalArgumentException * if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:date/Time. */ public static java.util.Date parseDateTime(final String lexicalXSDDateTime) { final Calendar calendar = jakarta.xml.bind.DatatypeConverter.parseDateTime(lexicalXSDDateTime); return calendar.getTime(); } /**
* <p> * Converts a date/time ({@link Date}) value into a string. * * @param val * A date/time ({@link Date}) value * @return A string containing a lexical representation of xsd:dateTime * @throws IllegalArgumentException * if <tt>val</tt> is null. */ public static String printDateTime(final java.util.Date val) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(val); return jakarta.xml.bind.DatatypeConverter.printDateTime(calendar); } }
repos\flowable-engine-main\modules\flowable-cxf\src\main\java\org\flowable\engine\impl\webservice\DatatypeConverter.java
2
请完成以下Java代码
public void setP_Date (java.sql.Timestamp P_Date) { set_Value (COLUMNNAME_P_Date, P_Date); } /** Get Process Date. @return Prozess-Parameter */ @Override public java.sql.Timestamp getP_Date () { return (java.sql.Timestamp)get_Value(COLUMNNAME_P_Date); } /** Set Process Number. @param P_Number Prozess-Parameter */ @Override public void setP_Number (java.math.BigDecimal P_Number) { set_Value (COLUMNNAME_P_Number, P_Number); } /** Get Process Number. @return Prozess-Parameter */ @Override public java.math.BigDecimal getP_Number () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number); if (bd == null) return BigDecimal.ZERO; return bd; }
/** Set Process String. @param P_String Prozess-Parameter */ @Override public void setP_String (java.lang.String P_String) { set_Value (COLUMNNAME_P_String, P_String); } /** Get Process String. @return Prozess-Parameter */ @Override public java.lang.String getP_String () { return (java.lang.String)get_Value(COLUMNNAME_P_String); } /** Set Parameter Name. @param ParameterName Parameter Name */ @Override public void setParameterName (java.lang.String ParameterName) { set_ValueNoCheck (COLUMNNAME_ParameterName, ParameterName); } /** Get Parameter Name. @return Parameter Name */ @Override public java.lang.String getParameterName () { return (java.lang.String)get_Value(COLUMNNAME_ParameterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Param.java
1
请完成以下Java代码
public class SimpleStructureDefinition implements FieldBaseStructureDefinition { protected String id; protected List<String> fieldNames; protected List<Class<?>> fieldTypes; public SimpleStructureDefinition(String id) { this.id = id; this.fieldNames = new ArrayList<String>(); this.fieldTypes = new ArrayList<Class<?>>(); } public int getFieldSize() { return this.fieldNames.size(); } public String getId() { return this.id; } public void setFieldName(int index, String fieldName, Class<?> type) { this.growListToContain(index, this.fieldNames); this.growListToContain(index, this.fieldTypes); this.fieldNames.set(index, fieldName); this.fieldTypes.set(index, type);
} private void growListToContain(int index, List<?> list) { if (!(list.size() - 1 >= index)) { for (int i = list.size(); i <= index; i++) { list.add(null); } } } public String getFieldNameAt(int index) { return this.fieldNames.get(index); } public Class<?> getFieldTypeAt(int index) { return this.fieldTypes.get(index); } public StructureInstance createInstance() { return new FieldBaseStructureInstance(this); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\SimpleStructureDefinition.java
1
请完成以下Java代码
public static String convertToDelimitedString(List<String> stringList) { StringBuilder resultString = new StringBuilder(); if (stringList != null) { for (String result : stringList) { if (resultString.length() > 0) { resultString.append(","); } resultString.append(result); } } return resultString.toString(); } public static boolean isBlacklisted(ExtensionAttribute attribute, List<ExtensionAttribute>... blackLists) { if (blackLists != null) { for (List<ExtensionAttribute> blackList : blackLists) { for (ExtensionAttribute blackAttribute : blackList) { if (blackAttribute.getName().equals(attribute.getName())) { if (attribute.getNamespace() != null && FLOWABLE_EXTENSIONS_NAMESPACE.equals(attribute.getNamespace())) { return true; } if (blackAttribute.getNamespace() == null && attribute.getNamespace() == null) { return true; } } } } } return false; } public static boolean containsNewLine(String str) { return str != null && str.contains("\n"); }
public static boolean writeIOParameters(String elementName, List<IOParameter> parameterList, boolean didWriteParameterStartElement, XMLStreamWriter xtw) throws Exception { if (parameterList == null || parameterList.isEmpty()) { return didWriteParameterStartElement; } for (IOParameter ioParameter : parameterList) { if (!didWriteParameterStartElement) { xtw.writeStartElement(ELEMENT_EXTENSION_ELEMENTS); didWriteParameterStartElement = true; } xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, elementName, FLOWABLE_EXTENSIONS_NAMESPACE); if (StringUtils.isNotEmpty(ioParameter.getSource())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE, ioParameter.getSource()); } if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION, ioParameter.getSourceExpression()); } if (StringUtils.isNotEmpty(ioParameter.getTarget())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET, ioParameter.getTarget()); } if (StringUtils.isNotEmpty(ioParameter.getTargetExpression())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET_EXPRESSION, ioParameter.getTargetExpression()); } xtw.writeEndElement(); } return didWriteParameterStartElement; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\CmmnXmlUtil.java
1
请完成以下Java代码
public void setCheckingPath(TreePath path) { getCheckingModel().setCheckingPath(path); } /** * Set paths that are in the checking. */ public void setCheckingPaths(TreePath[] paths) { getCheckingModel().setCheckingPaths(paths); } /** * @return Returns the paths that are in the greying. */ public TreePath[] getGreyingPaths() { return getCheckingModel().getGreyingPaths(); } /** * Adds a listener for <code>TreeChecking</code> events. * * @param tsl the <code>TreeCheckingListener</code> that will be * notified when a node is checked */ public void addTreeCheckingListener(TreeCheckingListener tsl) { this.checkingModel.addTreeCheckingListener(tsl); } /** * Removes a <code>TreeChecking</code> listener. * * @param tsl the <code>TreeChckingListener</code> to remove */ public void removeTreeCheckingListener(TreeCheckingListener tsl) { this.checkingModel.removeTreeCheckingListener(tsl); }
/** * Expand completely a tree */ public void expandAll() { expandSubTree(getPathForRow(0)); } private void expandSubTree(TreePath path) { expandPath(path); Object node = path.getLastPathComponent(); int childrenNumber = getModel().getChildCount(node); TreePath[] childrenPath = new TreePath[childrenNumber]; for (int childIndex = 0; childIndex < childrenNumber; childIndex++) { childrenPath[childIndex] = path.pathByAddingChild(getModel().getChild(node, childIndex)); expandSubTree(childrenPath[childIndex]); } } /** * @return a string representation of the tree, including the checking, * enabling and greying sets. */ @Override public String toString() { String retVal = super.toString(); TreeCheckingModel tcm = getCheckingModel(); if (tcm != null) { return retVal + "\n" + tcm.toString(); } return retVal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\CheckboxTree.java
1
请在Spring Boot框架中完成以下Java代码
public RouterFunction<ServerResponse> andRoute(RequestPredicate predicate, HandlerFunction<ServerResponse> handlerFunction) { return this.provider.getRouterFunction().andRoute(predicate, handlerFunction); } @Override public RouterFunction<ServerResponse> andNest(RequestPredicate predicate, RouterFunction<ServerResponse> routerFunction) { return this.provider.getRouterFunction().andNest(predicate, routerFunction); } @Override public <S extends ServerResponse> RouterFunction<S> filter( HandlerFilterFunction<ServerResponse, S> filterFunction) { return this.provider.getRouterFunction().filter(filterFunction); } @Override public void accept(RouterFunctions.Visitor visitor) { this.provider.getRouterFunction().accept(visitor); } @Override public RouterFunction<ServerResponse> withAttribute(String name, Object value) { return this.provider.getRouterFunction().withAttribute(name, value); }
@Override public RouterFunction<ServerResponse> withAttributes(Consumer<Map<String, Object>> attributesConsumer) { return this.provider.getRouterFunction().withAttributes(attributesConsumer); } @Override public Optional<HandlerFunction<ServerResponse>> route(ServerRequest request) { return this.provider.getRouterFunction().route(request); } @Override public String toString() { return this.provider.getRouterFunction().toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcPropertiesBeanDefinitionRegistrar.java
2
请完成以下Java代码
public Set<HuPackingInstructionsIdAndCaption> getLUPIs( @NonNull final ImmutableSet<HuPackingInstructionsItemId> tuPIItemIds, @Nullable final BPartnerId bpartnerId) { return handlingUnitsRepo.retrieveParentLUPIs(tuPIItemIds, bpartnerId); } @Override @NonNull public ImmutableSet<HuPackingInstructionsIdAndCaption> retrievePIInfo(@NonNull final Collection<HuPackingInstructionsItemId> piItemIds) { return handlingUnitsRepo.retrievePIInfo(piItemIds); } @Override @Nullable public I_M_HU_PI retrievePIDefaultForPicking() { return handlingUnitsRepo.retrievePIDefaultForPicking(); } @Override public boolean isTUIncludedInLU(@NonNull final I_M_HU tu, @NonNull final I_M_HU expectedLU) { final I_M_HU actualLU = getLoadingUnitHU(tu); return actualLU != null && actualLU.getM_HU_ID() == expectedLU.getM_HU_ID(); } @Override public List<I_M_HU> retrieveIncludedHUs(final I_M_HU huId) { return handlingUnitsRepo.retrieveIncludedHUs(huId); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIds(@NonNull final Collection<HuId> huIds) { final List<I_M_HU> hus = handlingUnitsRepo.getByIds(huIds); final ImmutableSet<Integer> locatorIds = hus .stream() .map(I_M_HU::getM_Locator_ID)
.filter(locatorId -> locatorId > 0) .collect(ImmutableSet.toImmutableSet()); return warehouseBL.getLocatorIdsByRepoId(locatorIds); } @Override public Optional<HuId> getHUIdByValueOrExternalBarcode(@NonNull final ScannedCode scannedCode) { return Optionals.firstPresentOfSuppliers( () -> getHUIdByValue(scannedCode.getAsString()), () -> getByExternalBarcode(scannedCode) ); } private Optional<HuId> getHUIdByValue(final String value) { final HuId huId = HuId.ofHUValueOrNull(value); return huId != null && existsById(huId) ? Optional.of(huId) : Optional.empty(); } private Optional<HuId> getByExternalBarcode(@NonNull final ScannedCode scannedCode) { return handlingUnitsRepo.createHUQueryBuilder() .setOnlyActiveHUs(true) .setOnlyTopLevelHUs() .addOnlyWithAttribute(AttributeConstants.ATTR_ExternalBarcode, scannedCode.getAsString()) .firstIdOnly(); } @Override public Set<HuPackingMaterialId> getHUPackingMaterialIds(@NonNull final HuId huId) { return handlingUnitsRepo.retrieveAllItemsNoCache(Collections.singleton(huId)) .stream() .map(item -> HuPackingMaterialId.ofRepoIdOrNull(item.getM_HU_PackingMaterial_ID())) .filter(Objects::nonNull) .collect(Collectors.toSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsBL.java
1
请完成以下Java代码
public int getM_AttributeSearch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getLockOwner() { return lockOwner;
} public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
private String getConfiguredAuthToken() { final I_AD_User configuredESUser = getConfiguredESUser(); final UserId configuredUserId = UserId.ofRepoId(configuredESUser.getAD_User_ID()); final Role role = getAndValidateRole(configuredUserId); final UserAuthToken userAuthToken = authTokenRepository.retrieveOptionalByUserAndRoleId(configuredUserId, role.getId()) .orElseGet(() -> createNewUserAuthToken(configuredESUser, role)); return userAuthToken.getAuthToken(); } @NonNull private UserAuthToken createNewUserAuthToken(@NonNull final I_AD_User user, @NonNull final Role configuredRole) { Loggables.withLogger(log, Level.DEBUG).addLog("Creating AuthToken for userId: {} && role: {}", user.getAD_User_ID(), configuredRole.getId().getRepoId()); final CreateUserAuthTokenRequest request = CreateUserAuthTokenRequest.builder() .userId(UserId.ofRepoId(user.getAD_User_ID())) .roleId(configuredRole.getId()) .orgId(configuredRole.getOrgId()) .clientId(configuredRole.getClientId()) .build(); return authTokenRepository.createNew(request); } @NonNull private Role getAndValidateRole(@NonNull final UserId userId) { final RoleId configuredRoleId = RoleId.ofRepoId(resolveAuthRelatedSysConfig(SYS_CONFIG_EXTERNAL_SYSTEM_AD_ROLE_ID)); final Role role = roleDAO.getById(configuredRoleId); final List<Role> userRoles = roleDAO.getUserRoles(userId); final boolean hasNecessaryRole = userRoles.stream() .map(Role::getId) .anyMatch(roleId -> roleId.getRepoId() == configuredRoleId.getRepoId()); if (!hasNecessaryRole) { throw ESMissingConfigurationException.builder() .adMessageKey(EXTERNAL_SYSTEM_AUTH_NOTIFICATION_ROLE_NOT_FOUND) .params(ImmutableList.of(role.getName(), userId.getRepoId())) .build(); } return role; }
@NonNull private I_AD_User getConfiguredESUser() { final UserId configuredUserId = UserId.ofRepoId(resolveAuthRelatedSysConfig(SYS_CONFIG_EXTERNAL_SYSTEM_AD_USER_ID)); return userDAO.getById(configuredUserId); } @NonNull private Integer resolveAuthRelatedSysConfig(@NonNull final String sysConfig) { final String sysConfigValueAsString = sysConfigBL.getValue(sysConfig); if (Check.isNotBlank(sysConfigValueAsString)) { return Integer.parseInt(sysConfigValueAsString); } throw ESMissingConfigurationException.builder() .adMessageKey(EXTERNAL_SYSTEM_AUTH_NOTIFICATION_CONTENT_SYSCONFIG_NOT_FOUND) .params(ImmutableList.of(sysConfig)) .build(); } @NonNull private static JsonExternalSystemMessage buildJsonExternalSystemMessage(@NonNull final String authToken) throws JsonProcessingException { final JsonExternalSystemMessagePayload payload = JsonExternalSystemMessagePayload.builder() .authToken(authToken) .build(); return JsonExternalSystemMessage.builder() .type(JsonExternalSystemMessageType.AUTHORIZATION_REPLY) .payload(JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(payload)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\authorization\ExternalSystemAuthorizationService.java
2
请完成以下Java代码
public Builder setDocumentType(@NonNull final DocumentType documentType, @NonNull final DocumentId documentTypeId) { this.documentType = documentType; this.documentTypeId = documentTypeId; return this; } public Builder setDocumentId(final String documentIdStr) { setDocumentId(DocumentId.ofStringOrEmpty(documentIdStr)); return this; } public Builder setDocumentId(final DocumentId documentId) { this.documentId = documentId; return this; } public Builder allowNewDocumentId() { documentId_allowNew = true; return this; } public Builder setDetailId(final String detailIdStr) { setDetailId(DetailId.fromJson(detailIdStr)); return this; } public Builder setDetailId(final DetailId detailId) { this.detailId = detailId; return this; } public Builder setRowId(final String rowIdStr) { final DocumentId rowId = DocumentId.ofStringOrEmpty(rowIdStr); setRowId(rowId); return this; }
public Builder setRowId(@Nullable final DocumentId rowId) { rowIds.clear(); if (rowId != null) { rowIds.add(rowId); } return this; } public Builder setRowIdsList(final String rowIdsListStr) { return setRowIds(DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr)); } public Builder setRowIds(final DocumentIdsSelection rowIds) { this.rowIds.clear(); this.rowIds.addAll(rowIds.toSet()); return this; } public Builder allowNullRowId() { rowId_allowNull = true; return this; } public Builder allowNewRowId() { rowId_allowNew = true; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentPath.java
1
请完成以下Java代码
/* package */class InvoiceHeaderAndLineAggregators { private final AggregationKey headerAggregationKey; @Getter private final InvoiceHeaderImplBuilder invoiceHeader; /** Map: C_Invoice_Candidate_Agg_ID to invoice line aggregator ({@link IAggregator}) */ private final HashMap<Object, IAggregator> lineAggregators = new HashMap<>(); public InvoiceHeaderAndLineAggregators(@NonNull final AggregationKey headerAggregationKey) { this.headerAggregationKey = headerAggregationKey; this.invoiceHeader = InvoiceHeaderImpl.builder(); } public IAggregator getLineAggregator(final int invoiceCandidateAggId) { final Object key = mkLineAggregatorKey(invoiceCandidateAggId); return lineAggregators.get(key);
} public void setLineAggregator(final int invoiceCandidateAggId, final IAggregator lineAggregator) { Check.assumeNotNull(lineAggregator, "lineAggregator not null"); final Object key = mkLineAggregatorKey(invoiceCandidateAggId); lineAggregators.put(key, lineAggregator); } private final Object mkLineAggregatorKey(final int invoiceCandidateAggId) { return invoiceCandidateAggId > 0 ? invoiceCandidateAggId : 0; } public Collection<IAggregator> getLineAggregators() { return lineAggregators.values(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderAndLineAggregators.java
1
请完成以下Java代码
public boolean isLatest() { return latest; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getAuthorizationUserId() {
return authorizationUserId; } public String getProcDefId() { return procDefId; } public String getEventSubscriptionName() { return eventSubscriptionName; } public String getEventSubscriptionType() { return eventSubscriptionType; } public ProcessDefinitionQueryImpl startableByUser(String userId) { if (userId == null) { throw new ActivitiIllegalArgumentException("userId is null"); } this.authorizationUserId = userId; return this; } public ProcessDefinitionQuery startableByGroups(List<String> groupIds) { authorizationGroups = groupIds; return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryImpl.java
1
请完成以下Java代码
private List<I_GL_DistributionLine> getGLDistributionLines() { final I_GL_Distribution glDistribution = getGLDistribution(); return glDistributionDAO.retrieveLines(glDistribution); } public GLDistributionBuilder setCurrencyId(final CurrencyId currencyId) { _currencyId = currencyId; _precision = null; return this; } private CurrencyId getCurrencyId() { Check.assumeNotNull(_currencyId, "currencyId not null"); return _currencyId; } private CurrencyPrecision getPrecision() { if (_precision == null) { _precision = currencyDAO.getStdPrecision(getCurrencyId()); } return _precision; } public GLDistributionBuilder setAmountToDistribute(final BigDecimal amountToDistribute) { _amountToDistribute = amountToDistribute; return this; } private BigDecimal getAmountToDistribute() { Check.assumeNotNull(_amountToDistribute, "amountToDistribute not null"); return _amountToDistribute; } public GLDistributionBuilder setAmountSign(@NonNull final Sign amountSign) { _amountSign = amountSign; return this; } private Sign getAmountSign() { Check.assumeNotNull(_amountSign, "amountSign not null");
return _amountSign; } public GLDistributionBuilder setQtyToDistribute(final BigDecimal qtyToDistribute) { _qtyToDistribute = qtyToDistribute; return this; } private BigDecimal getQtyToDistribute() { Check.assumeNotNull(_qtyToDistribute, "qtyToDistribute not null"); return _qtyToDistribute; } public GLDistributionBuilder setAccountDimension(final AccountDimension accountDimension) { _accountDimension = accountDimension; return this; } private AccountDimension getAccountDimension() { Check.assumeNotNull(_accountDimension, "_accountDimension not null"); return _accountDimension; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\GLDistributionBuilder.java
1
请完成以下Java代码
public static void extractTarArchive(File file, String folder) throws IOException { logger.info("Extracting archive {} into folder {}", file.getName(), folder); // @formatter:off try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis); TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) { // @formatter:on TarArchiveEntry entry; while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) { extractEntry(entry, tar, folder); } } logger.info("Archive extracted"); } /** * Extract an entry of the input stream into a given folder * @param entry * @param tar * @param folder * @throws IOException */ public static void extractEntry(ArchiveEntry entry, InputStream tar, String folder) throws IOException {
final int bufferSize = 4096; final String path = folder + entry.getName(); if (entry.isDirectory()) { new File(path).mkdirs(); } else { int count; byte[] data = new byte[bufferSize]; // @formatter:off try (FileOutputStream os = new FileOutputStream(path); BufferedOutputStream dest = new BufferedOutputStream(os, bufferSize)) { // @formatter:off while ((count = tar.read(data, 0, bufferSize)) != -1) { dest.write(data, 0, count); } } } } }
repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\logreg\Utils.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<GithubIssueLink> getFirstMatch(@NonNull final String textToParse) { final Matcher matcher = linkPattern.matcher(textToParse); if (matcher.find()) { return Optional.of(buildIssueLink(matcher)); } return Optional.empty(); } @NonNull private GithubIssueLink buildIssueLink(@NonNull final Matcher matcher) { return GithubIssueLink.builder() .githubIdSearchKey(
GithubIdSearchKey .builder() .repositoryOwner(matcher.group(OWNER_GROUP)) .repository(matcher.group(PROJECT_GROUP)) .issueNo(matcher.group(ISSUE_NO_GROUP)) .build()) .url(matcher.group().trim()) .build(); } private GithubIssueLinkMatcher(@NonNull final Pattern pattern) { this.linkPattern = pattern; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\link\GithubIssueLinkMatcher.java
2
请完成以下Java代码
public class StreamToIterable { public String streamToIterableLambda(List<String> listOfStrings) { Stream<String> stringStream = listOfStrings.stream(); StringBuilder sentence = new StringBuilder(); for (String eachString : (Iterable<String>) () -> stringStream.iterator()) { doSomethingOnString(eachString, sentence); } return sentence.toString(); } public String streamToIterableMethodReference(List<String> listOfStrings) { Stream<String> stringStream = listOfStrings.stream(); StringBuilder sentence = new StringBuilder(); for (String eachString : (Iterable<String>) stringStream::iterator) { doSomethingOnString(eachString, sentence); } return sentence.toString(); }
public String streamToList(List<String> listOfStrings) { Stream<String> stringStream = listOfStrings.stream(); StringBuilder sentence = new StringBuilder(); for (String eachString : stringStream.collect(Collectors.toList())) { doSomethingOnString(eachString, sentence); } return sentence.toString(); } private void doSomethingOnString(String s, StringBuilder sentence) { if (!Strings.isNullOrEmpty(s)) { sentence.append(s); } } }
repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\streamtoiterable\StreamToIterable.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EbayFulfillmentProgram ebayFulfillmentProgram = (EbayFulfillmentProgram)o; return Objects.equals(this.fulfilledBy, ebayFulfillmentProgram.fulfilledBy); } @Override public int hashCode() { return Objects.hash(fulfilledBy); } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append("class EbayFulfillmentProgram {\n"); sb.append(" fulfilledBy: ").append(toIndentedString(fulfilledBy)).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(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\EbayFulfillmentProgram.java
2
请完成以下Java代码
private IntegrationFlow createIntegrationFlow(final InboundEMailConfig config) { return IntegrationFlows .from(Mail.imapIdleAdapter(config.getUrl()) .javaMailProperties(p -> p.put("mail.debug", Boolean.toString(config.isDebugProtocol()))) .userFlag(IMAP_USER_FLAG) .shouldMarkMessagesAsRead(false) .shouldDeleteMessages(false) .shouldReconnectAutomatically(true) .embeddedPartsAsBytes(false) .headerMapper(InboundEMailHeaderAndContentMapper.newInstance())) .handle(InboundEMailMessageHandler.builder() .config(config) .emailService(emailService) .build()) .get();
} @Override public void onInboundEMailConfigChanged(final Set<InboundEMailConfigId> changedConfigIds) { final List<InboundEMailConfig> newOrChangedConfigs = configsRepo.getByIds(changedConfigIds); final Set<InboundEMailConfigId> newOrChangedConfigIds = newOrChangedConfigs.stream() .map(InboundEMailConfig::getId) .collect(ImmutableSet.toImmutableSet()); final Set<InboundEMailConfigId> deletedConfigIds = Sets.difference(changedConfigIds, newOrChangedConfigIds); deletedConfigIds.forEach(this::unloadById); reload(newOrChangedConfigs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailServer.java
1
请完成以下Java代码
public String showAll(Model model) { model.addAttribute("books", bookService.findAll()); return "allBooks"; } @GetMapping(value = "/create") public String showCreateForm(Model model) { BooksCreationDto booksForm = new BooksCreationDto(); for (int i = 1; i <= 3; i++) { booksForm.addBook(new Book()); } model.addAttribute("form", booksForm); return "createBooksForm"; } @GetMapping(value = "/edit") public String showEditForm(Model model) {
List<Book> books = new ArrayList<>(); bookService.findAll() .iterator() .forEachRemaining(books::add); model.addAttribute("form", new BooksCreationDto(books)); return "editBooksForm"; } @PostMapping(value = "/save") public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { bookService.saveAll(form.getBooks()); model.addAttribute("books", bookService.findAll()); return "redirect:/books/all"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\listbindingexample\MultipleBooksController.java
1
请完成以下Java代码
public void contextInitialized(ServletContextEvent sce) { servletContext = sce.getServletContext(); servletContextPath = servletContext.getContextPath(); servletContextName = sce.getServletContext().getServletContextName(); processApplicationClassloader = initProcessApplicationClassloader(sce); // perform lifecycle start deploy(); } protected ClassLoader initProcessApplicationClassloader(ServletContextEvent sce) { if (getClass().equals(JakartaServletProcessApplication.class)) { return JakartaClassLoaderUtil.getServletContextClassloader(sce); } else { return JakartaClassLoaderUtil.getClassloader(getClass()); } }
@Override public void contextDestroyed(ServletContextEvent sce) { // perform lifecycle stop undeploy(); // clear the reference if (reference != null) { reference.clear(); } reference = null; } public ServletContext getServletContext() { return servletContext; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\JakartaServletProcessApplication.java
1
请完成以下Java代码
public class ShipOrderCommand { @TargetAggregateIdentifier private final String orderId; public ShipOrderCommand(String orderId) { this.orderId = orderId; } public String getOrderId() { return orderId; } @Override public int hashCode() { return Objects.hash(orderId); } @Override public boolean equals(Object obj) {
if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final ShipOrderCommand other = (ShipOrderCommand) obj; return Objects.equals(this.orderId, other.orderId); } @Override public String toString() { return "ShipOrderCommand{" + "orderId='" + orderId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\commands\ShipOrderCommand.java
1
请完成以下Java代码
public Article afterUserFavoritesArticle(User user) { userFavorited.add(user); return updateFavoriteByUser(user); } public Article afterUserUnFavoritesArticle(User user) { userFavorited.remove(user); return updateFavoriteByUser(user); } public Comment addComment(User author, String body) { final var commentToAdd = new Comment(this, author, body); comments.add(commentToAdd); return commentToAdd; } public void removeCommentByUser(User user, long commentId) { final var commentsToDelete = comments.stream() .filter(comment -> comment.getId().equals(commentId)) .findFirst() .orElseThrow(NoSuchElementException::new); if (!user.equals(author) || !user.equals(commentsToDelete.getAuthor())) { throw new IllegalAccessError("Not authorized to delete comment"); } comments.remove(commentsToDelete); } public void updateArticle(ArticleUpdateRequest updateRequest) { contents.updateArticleContentsIfPresent(updateRequest); } public Article updateFavoriteByUser(User user) { favorited = userFavorited.contains(user); return this; } public User getAuthor() { return author; } public ArticleContents getContents() { return contents; } public Instant getCreatedAt() { return createdAt; } public Instant getUpdatedAt() {
return updatedAt; } public int getFavoritedCount() { return userFavorited.size(); } public boolean isFavorited() { return favorited; } public Set<Comment> getComments() { return comments; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; var article = (Article) o; return author.equals(article.author) && contents.getTitle().equals(article.contents.getTitle()); } @Override public int hashCode() { return Objects.hash(author, contents.getTitle()); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\Article.java
1
请完成以下Java代码
protected void restoreModelValuesFromSnapshot(final ModelType model, final SnapshotModelType modelSnapshot) { InterfaceWrapperHelper.copy() .setFrom(modelSnapshot) .setTo(model) .setSkipCalculatedColumns(false) // copy everything .copy(); } /** * Restore model when it snapshot is missing because the model was created after the snapshot was taken. * * Suggestion for implementors: maybe in this case you want to delete the model or you want to set it's relevant values to ZERO/<code>null</code>. * * @param model */ protected abstract void restoreModelWhenSnapshotIsMissing(final ModelType model); /** * Completelly restore the model from snapshot because the model is missing at all. * * @param modelSnapshot */ protected void restoreModelAsNew(final SnapshotModelType modelSnapshot) { throw new HUException("Restoring model from ashes is not supported for " + modelSnapshot); } protected abstract SnapshotModelType retrieveModelSnapshot(final ModelType model); protected final void restoreModelsFromSnapshotsByParent(final ParentModelType parentModel) { final Map<Integer, SnapshotModelType> modelSnapshots = retrieveModelSnapshotsByParent(parentModel); final Map<Integer, ModelType> models = new HashMap<>(retrieveModelsByParent(parentModel)); // // Iterate model snapshots and try to restore the models from them for (final SnapshotModelType modelSnapshot : modelSnapshots.values()) { final int modelId = getModelId(modelSnapshot); ModelType model = models.remove(modelId); // // Handle the case when the model's parent was changed // In this case we retrieve the model directly from snapshot's link. if (model == null) { model = getModel(modelSnapshot); } restoreModelFromSnapshot(model, modelSnapshot); }
// Iterate remaining models and delete/inactivate them. // NOTE: those are the models which were created after our snapshot. for (final ModelType model : models.values()) { final SnapshotModelType modelSnapshot = null; // no snapshot restoreModelFromSnapshot(model, modelSnapshot); } } /** * @param modelSnapshot * @return Model's ID from given snapshot */ protected abstract int getModelId(final SnapshotModelType modelSnapshot); /** * @param modelSnapshot * @return model retrieved using {@link #getModelId(Object)}. */ protected abstract ModelType getModel(final SnapshotModelType modelSnapshot); /** * * @param parentModel * @param snapshotId * @return "Model ID" to ModelSnapshot map */ protected abstract Map<Integer, SnapshotModelType> retrieveModelSnapshotsByParent(final ParentModelType parentModel); /** * * @param model * @return "Model ID" to Model map */ protected abstract Map<Integer, ModelType> retrieveModelsByParent(final ParentModelType parentModel); protected final <T> IQueryBuilder<T> query(final Class<T> modelClass) { return queryBL.createQueryBuilder(modelClass, getContext()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\AbstractSnapshotHandler.java
1
请完成以下Java代码
public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public int getType() { return type; } public void setType(int type) { this.type = type; } public Date getLaunchDate() { return launchDate; } public void setLaunchDateDate(Date launchDate) { this.launchDate = launchDate; } public Date getCreated() { return created; } public void setCreated(Date created) {
this.created = created; } public Date getModified() { return modified; } public void setModified(Date modified) { this.modified = modified; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\worker\entity\WorkerNodeEntity.java
1
请完成以下Java代码
public class DIM_Dimension_Spec_Attribute { @Init public void registerCallout() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void validate(final I_DIM_Dimension_Spec_Attribute specAttr) { Services.get(IDimensionspecDAO.class).deleteAllSpecAttributeValues(specAttr); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_DIM_Dimension_Spec_Attribute.COLUMNNAME_M_Attribute_ID) @CalloutMethod(columnNames = I_DIM_Dimension_Spec_Attribute.COLUMNNAME_M_Attribute_ID) public void setAttributerValueType(final I_DIM_Dimension_Spec_Attribute specAttr) {
final AttributeId attributeId = AttributeId.ofRepoIdOrNull(specAttr.getM_Attribute_ID()); if (attributeId == null) { specAttr.setAttributeValueType(null); } else { final I_M_Attribute attribute = Services.get(IAttributeDAO.class).getAttributeRecordById(attributeId); final String attributeValueType = attribute.getAttributeValueType(); specAttr.setAttributeValueType(attributeValueType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\model\validator\DIM_Dimension_Spec_Attribute.java
1
请完成以下Java代码
public int hashCode() { return _hashKey.hashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final FactAcctSummaryKey other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(_hashKey, other._hashKey) .isEqual(); } @Override public int getC_ElementValue_ID() { return C_ElementValue_ID; } @Override public int getC_AcctSchema_ID() { return C_AcctSchema_ID; } @Override public String getPostingType() { return postingType; } @Override public int getC_Period_ID() { return C_Period_ID; } @Override
public Date getDateAcct() { return new Date(dateAcctMs); } @Override public int getAD_Client_ID() { return AD_Client_ID; } @Override public int getAD_Org_ID() { return AD_Org_ID; } @Override public int getPA_ReportCube_ID() { return PA_ReportCube_ID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\FactAcctSummaryKey.java
1
请完成以下Java代码
public class QtyDemand_QtySupply_V_to_ReceiptSchedule extends JavaProcess implements IProcessPrecondition { private final QtyDemandSupplyRepository demandSupplyRepository = SpringContextHolder.instance.getBean(QtyDemandSupplyRepository.class); private final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID()));
final ReceiptScheduleQuery receiptScheduleQuery = ReceiptScheduleQuery.builder() .warehouseId(currentRow.getWarehouseId()) .orgId(currentRow.getOrgId()) .productId(currentRow.getProductId()) .attributesKey(currentRow.getAttributesKey()) .onlyNonZeroQty(true) .build(); final List<TableRecordReference> recordReferences = receiptScheduleDAO.listIdsByQuery(receiptScheduleQuery) .stream() .map(id -> TableRecordReference.of(I_M_ReceiptSchedule.Table_Name, id)) .collect(Collectors.toList()); getResult().setRecordsToOpen(recordReferences); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_ReceiptSchedule.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.record.topic().hashCode() + this.record.partition() + (int) this.record.offset(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") RecordHolder other = (RecordHolder) obj; if (this.record == null) { if (other.record != null) {
return false; } } else { return this.record.topic().equals(other.record.topic()) && this.record.partition() == other.record.partition() && this.record.offset() == other.record.offset(); } return false; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\AggregatingReplyingKafkaTemplate.java
1
请完成以下Java代码
public boolean isEmpty() { return options.isEmpty(); } private boolean isNone() { return this.equals(NONE); } public ImmutableSet<String> getOptionNames() { if (fallback != null && !fallback.isEmpty()) { return ImmutableSet.<String>builder() .addAll(options.keySet()) .addAll(fallback.getOptionNames()) .build(); } else { return options.keySet(); } } public DocumentPrintOptionValue getOption(@NonNull final String name) { final Boolean value = options.get(name); if (value != null) { return DocumentPrintOptionValue.builder() .value(OptionalBoolean.ofBoolean(value)) .sourceName(sourceName) .build(); } else if (fallback != null) { return fallback.getOption(name); } else { return DocumentPrintOptionValue.MISSING; } }
public DocumentPrintOptions mergeWithFallback(@NonNull final DocumentPrintOptions fallback) { if (fallback.isNone()) { return this; } else if (isNone()) { return fallback; } else { if (this == fallback) { throw new IllegalArgumentException("Merging with itself is not allowed"); } final DocumentPrintOptions newFallback; if (this.fallback != null) { newFallback = this.fallback.mergeWithFallback(fallback); } else { newFallback = fallback; } return !Objects.equals(this.fallback, newFallback) ? toBuilder().fallback(newFallback).build() : this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptions.java
1
请完成以下Java代码
public static String getTemplatePathByConfig(String code) { return getCgformEnumByConfig(code).templatePath; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getTemplatePath() { return templatePath; } public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } public String getStylePath() { return stylePath; } public void setStylePath(String stylePath) { this.stylePath = stylePath; } public String[] getVueStyle() { return vueStyle; } public void setVueStyle(String[] vueStyle) { this.vueStyle = vueStyle; } /** * 根据code找枚举 * * @param code * @return */ public static CgformEnum getCgformEnumByConfig(String code) { for (CgformEnum e : CgformEnum.values()) { if (e.code.equals(code)) { return e; } } return null;
} /** * 根据类型找所有 * * @param type * @return */ public static List<Map<String, Object>> getJspModelList(int type) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); for (CgformEnum e : CgformEnum.values()) { if (e.type == type) { Map<String, Object> map = new HashMap<String, Object>(); map.put("code", e.code); map.put("note", e.note); ls.add(map); } } return ls; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\CgformEnum.java
1
请完成以下Java代码
private void activeHUAfterReceipt(final IHUContext huContext, final I_M_HU hu, final I_M_InOutLine receiptLine) { // // Activate HU (i.e. it's not a Planning HU anymore) final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); huStatusBL.setHUStatus(huContext, hu, X_M_HU.HUSTATUS_Active); // // Update HU's Locator final int receiptLocatorId = receiptLine.getM_Locator_ID(); // the locator where this HU was received hu.setM_Locator_ID(receiptLocatorId); // // Update BPartner resetVendor(huContext, hu); // // Set PurchaseOrderLine_ID and ReceiptInOutLine_ID attributes (task 09741) { final IAttributeStorage huAttributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final org.compiere.model.I_M_Attribute attr_PurchaseOrderLine = huAttributeStorage.getAttributeByValueKeyOrNull(HUAttributeConstants.ATTR_PurchaseOrderLine_ID); if (attr_PurchaseOrderLine != null) { huAttributeStorage.setValue(attr_PurchaseOrderLine, receiptLine.getC_OrderLine_ID()); } final org.compiere.model.I_M_Attribute attr_ReceiptInOutLine = huAttributeStorage.getAttributeByValueKeyOrNull(HUAttributeConstants.ATTR_ReceiptInOutLine_ID); if (attr_ReceiptInOutLine != null) { huAttributeStorage.setValue(attr_ReceiptInOutLine, receiptLine.getM_InOutLine_ID()); } } // Save changed HU InterfaceWrapperHelper.save(hu, huContext.getTrxName()); } /** * Set's HU's BPartner to <code>null</code>. * * If there is any SubProducer attribute and is not yet set, we copy the old HU's BPartner to it. * * @param huContext
* @param hu * @task http://dewiki908/mediawiki/index.php/08027_Lieferdispo_Freigabe_nach_BPartner_%28100002853810%29 */ private void resetVendor(final IHUContext huContext, final I_M_HU hu) { // // Get the HU's BPartner. // We will need it to set the SubProducer. final int bpartnerId = hu.getC_BPartner_ID(); // // Reset HU's BPartner & BP Location hu.setC_BPartner_ID(-1); hu.setC_BPartner_Location_ID(-1); // // If there was no partner, we have nothing to set if (bpartnerId <= 0) { return; } // // If HU does not support the SubProducer attribute, we have nothing to do final IAttributeStorage huAttributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); final org.compiere.model.I_M_Attribute attribute_subProducer = huAttributeStorage.getAttributeByValueKeyOrNull(HUAttributeConstants.ATTR_SubProducerBPartner_Value); if (attribute_subProducer == null) { return; } // // Don't override existing value final int subproducerBPartnerId = huAttributeStorage.getValueAsInt(attribute_subProducer); if (subproducerBPartnerId > 0) { return; } // // Sets the ex-Vendor BPartner ID as SubProducer. huAttributeStorage.setValue(attribute_subProducer, bpartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\ReceiptInOutLineHUAssignmentListener.java
1
请完成以下Java代码
public void addCockpitRecord(@NonNull final I_MD_Cockpit cockpitRecord) { final ProductId productId = ProductId.ofRepoId(cockpitRecord.getM_Product_ID()); final I_C_UOM uom = cache.getUomByProductId(productId); qtyStockEstimateCountAtDate = addToNullable(qtyStockEstimateCountAtDate, cockpitRecord.getQtyStockEstimateCount_AtDate(), uom); qtyStockEstimateTimeAtDate = TimeUtil.max(qtyStockEstimateTimeAtDate, TimeUtil.asInstant(cockpitRecord.getQtyStockEstimateTime_AtDate())); qtyInventoryCountAtDate = addToNullable(qtyInventoryCountAtDate, cockpitRecord.getQtyInventoryCount_AtDate(), uom); qtyInventoryTimeAtDate = TimeUtil.max(qtyInventoryTimeAtDate, TimeUtil.asInstant(cockpitRecord.getQtyInventoryTime_AtDate())); qtyStockCurrentAtDate = addToNullable(qtyStockCurrentAtDate, cockpitRecord.getQtyStockCurrent_AtDate(), uom); cockpitRecordIds.add(cockpitRecord.getMD_Cockpit_ID()); } public void addStockRecord(@NonNull final I_MD_Stock stockRecord) { final ProductId productId = ProductId.ofRepoId(stockRecord.getM_Product_ID()); final I_C_UOM uom = cache.getUomByProductId(productId); qtyOnHandStock = addToNullable(qtyOnHandStock, stockRecord.getQtyOnHand(), uom); stockRecordIds.add(stockRecord.getMD_Stock_ID()); } public void addQuantitiesRecord(@NonNull final ProductWithDemandSupply quantitiesRecord) { final I_C_UOM uom = uomDAO.getById(quantitiesRecord.getUomId());
qtyDemandSalesOrder = addToNullable(qtyDemandSalesOrder, quantitiesRecord.getQtyReserved(), uom); qtySupplyPurchaseOrder = addToNullable(qtySupplyPurchaseOrder, quantitiesRecord.getQtyToMove(), uom); } @NonNull public MaterialCockpitRow createIncludedRow(@NonNull final MainRowWithSubRows mainRowBucket) { final MainRowBucketId productIdAndDate = assumeNotNull( mainRowBucket.getProductIdAndDate(), "productIdAndDate may not be null; mainRowBucket={}", mainRowBucket); return MaterialCockpitRow.countingSubRowBuilder() .lookups(rowLookups) .cache(cache) .date(productIdAndDate.getDate()) .productId(productIdAndDate.getProductId().getRepoId()) .detailsRowAggregationIdentifier(detailsRowAggregationIdentifier) .qtyDemandSalesOrder(qtyDemandSalesOrder) .qtySupplyPurchaseOrder(qtySupplyPurchaseOrder) .qtyStockEstimateCountAtDate(qtyStockEstimateCountAtDate) .qtyStockEstimateTimeAtDate(qtyStockEstimateTimeAtDate) .qtyInventoryCountAtDate(qtyInventoryCountAtDate) .qtyInventoryTimeAtDate(qtyInventoryTimeAtDate) .qtyStockCurrentAtDate(qtyStockCurrentAtDate) .qtyOnHandStock(qtyOnHandStock) .allIncludedCockpitRecordIds(cockpitRecordIds) .allIncludedStockRecordIds(stockRecordIds) .qtyConvertor(qtyConvertorService.getQtyConvertorIfConfigured(productIdAndDate)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\CountingSubRowBucket.java
1
请在Spring Boot框架中完成以下Java代码
public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return Instant.class.isAssignableFrom(value.getClass()); } @Override public Object getValue(ValueFields valueFields) {
Long longValue = valueFields.getLongValue(); if (longValue != null) { return Instant.ofEpochMilli(longValue); } return null; } @Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { Instant instant = (Instant) value; valueFields.setLongValue(instant.toEpochMilli()); } else { valueFields.setLongValue(null); } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\InstantType.java
2
请完成以下Java代码
private UserNotificationRequest createNotification(final RequestSalesRepChanged event, final UserId recipientId) { final UserNotificationsConfig notificationsConfig = notificationsService.getUserNotificationsConfig(recipientId); return UserNotificationRequest.builder() .notificationsConfig(notificationsConfig) .topic(TOPIC_Requests) // // RequestActionTransfer - Request {} was transfered by {} from {} to {} .subjectADMessage(MSG_RequestActionTransfer) .subjectADMessageParam(event.getRequestDocumentNo()) .subjectADMessageParam(getUserFullname(event.getChangedById())) .subjectADMessageParam(getUserFullname(event.getFromSalesRepId())) .subjectADMessageParam(getUserFullname(event.getToSalesRepId())) // .contentADMessage(MSG_RequestActionTransfer) .contentADMessageParam(event.getRequestDocumentNo()) .contentADMessageParam(getUserFullname(event.getChangedById())) .contentADMessageParam(getUserFullname(event.getFromSalesRepId())) .contentADMessageParam(getUserFullname(event.getToSalesRepId())) // .targetAction(TargetRecordAction.of(I_R_Request.Table_Name, event.getRequestId().getRepoId())) .build();
} private static Set<UserId> extractUserIdsToNotify(@NonNull final RequestSalesRepChanged event) { return event.getToSalesRepId() != null ? ImmutableSet.of(event.getToSalesRepId()) : ImmutableSet.of(); } private String getUserFullname(@Nullable final UserId userId) { return userId != null ? usersRepo.retrieveUserFullName(userId) : "-"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\notifications\RequestNotificationsSender.java
1
请完成以下Java代码
public String getExpressionLanguage() { return expressionLanguageAttribute.getValue(this); } public void setExpressionLanguage(String expressionLanguage) { expressionLanguageAttribute.setValue(this, expressionLanguage); } public Text getText() { return textChild.getChild(this); } public void setText(Text text) { textChild.setChild(this, text); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(UnaryTests.class, DMN_ELEMENT_UNARY_TESTS) .namespaceUri(LATEST_DMN_NS) .extendsType(DmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<UnaryTests>() { public UnaryTests newInstance(ModelTypeInstanceContext instanceContext) { return new UnaryTestsImpl(instanceContext); } }); expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); textChild = sequenceBuilder.element(Text.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\UnaryTestsImpl.java
1
请完成以下Java代码
public void sendShipperTransportationAsEmail(@NonNull final ShipperTransportationId shipperTransportationId) { final I_M_ShipperTransportation shipperTransportationRecord = loadOutOfTrx(shipperTransportationId, I_M_ShipperTransportation.class); final int shipperId = shipperTransportationRecord.getM_Shipper_ID(); final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository .retrieveConfigForShipperId(shipperId); final EMailAddress emailAddress = shipperConfig.getDeliveryOrderRecipientEmailOrNull(); if (emailAddress == null) { return; } final AttachmentEntry attachmentEntry = attachmentEntryService.getByFilenameOrNull( TableRecordReference.of(shipperTransportationRecord), DerKurierDeliveryOrderService.SHIPPER_TRANSPORTATION_ATTACHMENT_FILENAME); sendAttachmentAsEmail(shipperId, attachmentEntry); } public void sendAttachmentAsEmail(final int shipperId, @NonNull final AttachmentEntry attachmentEntry) { Check.assumeGreaterThanZero(shipperId, "shipperId"); final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository .retrieveConfigForShipperId(shipperId); final EMailAddress emailAddress = shipperConfig.getDeliveryOrderRecipientEmailOrNull(); if (emailAddress == null) { return; } final Mailbox deliveryOrderMailBox = shipperConfig.getDeliveryOrderMailBoxId() .map(mailService::getMailboxById) .orElseThrow(() -> new AdempiereException("No mailbox defined: " + shipperConfig));
sendAttachmentAsEmail(deliveryOrderMailBox, emailAddress, attachmentEntry); } @VisibleForTesting void sendAttachmentAsEmail( @NonNull final Mailbox mailBox, @NonNull final EMailAddress mailTo, @NonNull final AttachmentEntry attachmentEntry) { final byte[] data = attachmentEntryService.retrieveData(attachmentEntry.getId()); final String csvDataString = new String(data, DerKurierConstants.CSV_DATA_CHARSET); final String subject = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailSubject); final String message = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailMessage, new Object[] { csvDataString }); mailService.sendEMail(EMailRequest.builder() .mailbox(mailBox) .to(mailTo) .subject(subject) .message(message) .html(false) .build()); // we don't have an AD_Archive.. // final I_AD_User user = loadOutOfTrx(Env.getAD_User_ID(), I_AD_User.class); // final IArchiveEventManager archiveEventManager = Services.get(IArchiveEventManager.class); // archiveEventManager.fireEmailSent( // null, // X_C_Doc_Outbound_Log_Line.ACTION_EMail, // user, // null/* from */, // mailTo, // null /* cc */, // null /* bcc */, // IArchiveEventManager.STATUS_MESSAGE_SENT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\DerKurierDeliveryOrderEmailer.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private UserMapper userMapper; @Resource private RedisTemplate<String, User> redisTemplate; /** * 创建用户 * 不会对缓存做任何操作 */ public void createUser(User user) { logger.info("创建用户start..."); userMapper.insert(user); } /** * 获取用户信息 * 如果缓存存在,从缓存中获取城市信息 * 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存 * * @param id 用户ID * @return 用户 */ public User getById(int id) { logger.info("获取用户start..."); // 从缓存中获取用户信息 String key = "user_" + id; ValueOperations<String, User> operations = redisTemplate.opsForValue(); // 缓存存在 boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { User user = operations.get(key); logger.info("从缓存中获取了用户 id = " + id); return user; } // 缓存不存在,从 DB 中获取 User user = userMapper.selectById(id); // 插入缓存
operations.set(key, user, 10, TimeUnit.SECONDS); return user; } /** * 更新用户 * 如果缓存存在,删除 * 如果缓存不存在,不操作 * * @param user 用户 */ public void updateUser(User user) { logger.info("更新用户start..."); userMapper.updateById(user); int userId = user.getId(); // 缓存存在,删除缓存 String key = "user_" + userId; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("更新用户时候,从缓存中删除用户 >> " + userId); } } /** * 删除用户 * 如果缓存中存在,删除 */ public void deleteById(int id) { logger.info("删除用户start..."); userMapper.deleteById(id); // 缓存存在,删除缓存 String key = "user_" + id; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); logger.info("更新用户时候,从缓存中删除用户 >> " + id); } } }
repos\SpringBootBucket-master\springboot-redis\src\main\java\com\xncoding\pos\service\UserService.java
2
请完成以下Java代码
public static String toStringWithCustomDecimalSeparator(@NonNull final BigDecimal value, final char separator) { final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(separator); final int scale = value.scale(); final String format; if (scale > 0) { final StringBuilder formatBuilder = new StringBuilder("0."); IntStream.range(0, scale) .forEach(ignored -> formatBuilder.append("0")); format = formatBuilder.toString(); } else { format = "0"; } final DecimalFormat formatter = new DecimalFormat(format, symbols); return formatter.format(value); } @Nullable public static BigDecimal zeroToNull(@Nullable final BigDecimal value) { return value != null && value.signum() != 0 ? value : null; } public static boolean equalsByCompareTo(@Nullable final BigDecimal value1, @Nullable final BigDecimal value2) { //noinspection NumberEquality return (value1 == value2) || (value1 != null && value1.compareTo(value2) == 0); } @SafeVarargs public static int firstNonZero(final Supplier<Integer>... suppliers) { if (suppliers == null || suppliers.length == 0) { return 0; }
for (final Supplier<Integer> supplier : suppliers) { if (supplier == null) { continue; } final Integer value = supplier.get(); if (value != null && value != 0) { return value; } } return 0; } @NonNull public static BigDecimal roundTo5Cent(@NonNull final BigDecimal initialValue) { final BigDecimal multiplyBy20 = initialValue.multiply(TWENTY); final BigDecimal intPart = multiplyBy20.setScale(0, RoundingMode.HALF_UP); return intPart.divide(TWENTY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\NumberUtils.java
1
请完成以下Spring Boot application配置
spring: config: name: application-transformers sql: init: mode: never datasource: url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 driverClassName: org.h2.Driver username: sa password: jpa: hibernate:
ddl-auto: create-drop show-sql: true properties: hibernate: format_sql: true
repos\tutorials-master\persistence-modules\hibernate6\src\main\resources\application-transformers.yaml
2
请在Spring Boot框架中完成以下Java代码
public Foo postFoo(@RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.HEAD, value = "/foos") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo headFoo() { return new Foo(1, randomAlphabetic(4)); } @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" }) @ResponseBody public FooProtos.Foo findProtoById(@PathVariable final long id) { return FooProtos.Foo.newBuilder() .setId(1) .setName("Foo Name") .build(); } @RequestMapping(method = RequestMethod.POST, value = "/foos/new") @ResponseStatus(HttpStatus.CREATED)
@ResponseBody public Foo createFoo(@RequestBody final Foo foo) { return foo; } @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public long deleteFoo(@PathVariable final long id) { return id; } @RequestMapping(method = RequestMethod.POST, value = "/foos/form") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public String submitFoo(@RequestParam("id") String id) { return id; } }
repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\web\controller\FooController.java
2
请完成以下Java代码
default void setRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation from) { setDeliveryToAddress(from.getRenderedAddress()); } default DocumentLocation toDocumentLocation() { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(getDropShip_BPartner_ID()); return DocumentLocation.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, getDropShip_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, getDropShip_User_ID())) .locationId(LocationId.ofRepoIdOrNull(getDropShip_Location_Value_ID())) .bpartnerAddress(getDeliveryToAddress()) .build(); } default void setFrom(@NonNull final DocumentLocation from) {
setDropShip_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setDropShip_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setDropShip_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setDropShip_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setDeliveryToAddress(from.getBpartnerAddress()); } default void setFrom(@NonNull final BPartnerInfo from) { setDropShip_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setDropShip_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setDropShip_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setDropShip_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setDeliveryToAddress(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\adapter\IDocumentDeliveryLocationAdapter.java
1
请完成以下Java代码
private boolean isSQLStartLogicMatches(final Workflow workflow, final PO document) { String logic = workflow.getDocValueWorkflowTriggerLogic(); logic = logic.substring(4); // "SQL=" // final String tableName = document.get_TableName(); final String[] keyColumns = document.get_KeyColumns(); if (keyColumns.length != 1) { log.error("Tables with more then one key column not supported - " + tableName + " = " + keyColumns.length); return false; } final String keyColumn = keyColumns[0]; final StringBuilder sql = new StringBuilder("SELECT ") .append(keyColumn).append(" FROM ").append(tableName) .append(" WHERE AD_Client_ID=? AND ") // #1 .append(keyColumn).append("=? AND ") // #2 .append(logic) // Duplicate Open Workflow test .append(" AND NOT EXISTS (SELECT 1 FROM AD_WF_Process wfp ") .append("WHERE wfp.AD_Table_ID=? AND wfp.Record_ID=") // #3 .append(tableName).append(".").append(keyColumn) .append(" AND wfp.AD_Workflow_ID=?") // #4 .append(" AND SUBSTR(wfp.WFState,1,1)='O')"); final Object[] sqlParams = new Object[] { workflow.getClientId(), document.get_ID(), document.get_Table_ID(), workflow.getId()
}; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql.toString(), document.get_TrxName()); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); return rs.next(); } catch (final Exception ex) { throw new DBException(ex, sql, sqlParams); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\DocWorkflowManager.java
1
请在Spring Boot框架中完成以下Java代码
public boolean hasPermission(SecurityUser user, Operation operation, UserId userId, User userEntity) { if (!Authority.CUSTOMER_USER.equals(userEntity.getAuthority())) { return false; } if (!user.getCustomerId().equals(userEntity.getCustomerId())) { return false; } if (Operation.READ.equals(operation)) { return true; } return user.getId().equals(userId); } }; private static final PermissionChecker widgetsPermissionChecker = new PermissionChecker.GenericPermissionChecker(Operation.READ) { @Override @SuppressWarnings("unchecked") public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) { if (!super.hasPermission(user, operation, entityId, entity)) { return false; } if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) { return true; } return user.getTenantId().equals(entity.getTenantId()); } }; private static final PermissionChecker rpcPermissionChecker = new PermissionChecker.GenericPermissionChecker(Operation.READ) { @Override @SuppressWarnings("unchecked") public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) { if (!super.hasPermission(user, operation, entityId, entity)) { return false; } if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) { return true; } return user.getTenantId().equals(entity.getTenantId()); } }; private static final PermissionChecker profilePermissionChecker = new PermissionChecker.GenericPermissionChecker(Operation.READ) { @Override @SuppressWarnings("unchecked") public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) {
if (!super.hasPermission(user, operation, entityId, entity)) { return false; } if (entity.getTenantId() == null || entity.getTenantId().isNullUid()) { return true; } return user.getTenantId().equals(entity.getTenantId()); } }; private static final PermissionChecker apiKeysPermissionChecker = new PermissionChecker<ApiKeyId, ApiKeyInfo>() { @Override public boolean hasPermission(SecurityUser user, Operation operation) { return true; } @Override @SuppressWarnings("unchecked") public boolean hasPermission(SecurityUser user, Operation operation, ApiKeyId entityId, ApiKeyInfo entity) { return user.getTenantId().equals(entity.getTenantId()); } }; }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\permission\CustomerUserPermissions.java
2
请完成以下Java代码
protected TableOrgPermission noPermission() {return null;} public Optional<Set<OrgId>> getOrgsWithAccess(@Nullable final String tableName, @NonNull final Access access) { // Does not apply if table name is not provided if (tableName == null || Check.isBlank(tableName)) { return Optional.empty(); } final ImmutableList<TableOrgPermission> tablePermissions = permissionsByTableName.get(tableName); if (tablePermissions.isEmpty()) { return Optional.empty(); } final ImmutableSet<OrgId> orgIds = tablePermissions.stream() .filter(permission -> permission.hasAccess(access))
.map(TableOrgPermission::getOrgId) .collect(ImmutableSet.toImmutableSet()); return Optional.of(orgIds); } public static class Builder extends PermissionsBuilder<TableOrgPermission, TableOrgPermissions> { @Override protected TableOrgPermissions createPermissionsInstance() { return new TableOrgPermissions(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableOrgPermissions.java
1
请完成以下Java代码
protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) { List<FieldErrorResource> errorResources = e.getBindingResult().getFieldErrors().stream() .map( fieldError -> new FieldErrorResource( fieldError.getObjectName(), fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage())) .collect(Collectors.toList()); return ResponseEntity.status(UNPROCESSABLE_ENTITY).body(new ErrorResource(errorResources)); } @ExceptionHandler({ConstraintViolationException.class}) @ResponseStatus(UNPROCESSABLE_ENTITY) @ResponseBody public ErrorResource handleConstraintViolation( ConstraintViolationException ex, WebRequest request) { List<FieldErrorResource> errors = new ArrayList<>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { FieldErrorResource fieldErrorResource =
new FieldErrorResource( violation.getRootBeanClass().getName(), getParam(violation.getPropertyPath().toString()), violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), violation.getMessage()); errors.add(fieldErrorResource); } return new ErrorResource(errors); } private String getParam(String s) { String[] splits = s.split("\\."); if (splits.length == 1) { return s; } else { return String.join(".", Arrays.copyOfRange(splits, 2, splits.length)); } } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\exception\CustomizeExceptionHandler.java
1
请完成以下Java代码
protected void setCalendarHour(Calendar cal, int hour) { cal.set(Calendar.HOUR_OF_DAY, hour); if (cal.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) { cal.set(Calendar.HOUR_OF_DAY, hour + 1); } } protected boolean isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); } protected int getLastDayOfMonth(int monthNum, int year) { switch (monthNum) { case 1: return 31; case 2: return (isLeapYear(year)) ? 29 : 28; case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31;
case 9: return 30; case 10: return 31; case 11: return 30; case 12: return 31; default: throw new IllegalArgumentException("Illegal month number: " + monthNum); } } } class ValueSet { public int value; public int pos; }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\CronExpression.java
1
请完成以下Java代码
public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue) { set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue); } /** Set System-Problem. @param AD_Issue_ID Automatically created or manually entered System Issue */ @Override public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } /** Get System-Problem. @return Automatically created or manually entered System Issue */ @Override public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_WorkPackage getC_Queue_WorkPackage() { return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_WorkPackage(de.metas.async.model.I_C_Queue_WorkPackage C_Queue_WorkPackage) { set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, C_Queue_WorkPackage); } /** Set WorkPackage Queue. @param C_Queue_WorkPackage_ID WorkPackage Queue */ @Override public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID) { if (C_Queue_WorkPackage_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID)); } /** Get WorkPackage Queue. @return WorkPackage Queue */ @Override public int getC_Queue_WorkPackage_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Workpackage audit/log table. @param C_Queue_WorkPackage_Log_ID Workpackage audit/log table */ @Override public void setC_Queue_WorkPackage_Log_ID (int C_Queue_WorkPackage_Log_ID) { if (C_Queue_WorkPackage_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, null);
else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, Integer.valueOf(C_Queue_WorkPackage_Log_ID)); } /** Get Workpackage audit/log table. @return Workpackage audit/log table */ @Override public int getC_Queue_WorkPackage_Log_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Log_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Log.java
1
请完成以下Java代码
public int getDatevAcctExport_ID() { return get_ValueAsInt(COLUMNNAME_DatevAcctExport_ID); } @Override public void setDatevAcctExportLine_ID (final int DatevAcctExportLine_ID) { if (DatevAcctExportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_DatevAcctExportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_DatevAcctExportLine_ID, DatevAcctExportLine_ID); } @Override public int getDatevAcctExportLine_ID() { return get_ValueAsInt(COLUMNNAME_DatevAcctExportLine_ID); } @Override public void setDatev_Kost1 (final int Datev_Kost1) { set_Value (COLUMNNAME_Datev_Kost1, Datev_Kost1); } @Override public int getDatev_Kost1() { return get_ValueAsInt(COLUMNNAME_Datev_Kost1); } @Override public void setDatev_Kost2 (final int Datev_Kost2) { set_Value (COLUMNNAME_Datev_Kost2, Datev_Kost2); } @Override public int getDatev_Kost2() { return get_ValueAsInt(COLUMNNAME_Datev_Kost2); } @Override public void setDatum (final @Nullable java.lang.String Datum) { set_Value (COLUMNNAME_Datum, Datum); } @Override public java.lang.String getDatum() { return get_ValueAsString(COLUMNNAME_Datum); } @Override public void setFS (final int FS) { set_Value (COLUMNNAME_FS, FS); } @Override public int getFS() { return get_ValueAsInt(COLUMNNAME_FS); } @Override public void setGegenkonto (final @Nullable java.lang.String Gegenkonto) { set_Value (COLUMNNAME_Gegenkonto, Gegenkonto); } @Override public java.lang.String getGegenkonto() { return get_ValueAsString(COLUMNNAME_Gegenkonto); } @Override public void setKonto (final @Nullable java.lang.String Konto) { set_Value (COLUMNNAME_Konto, Konto); } @Override public java.lang.String getKonto()
{ return get_ValueAsString(COLUMNNAME_Konto); } @Override public void setLeistungsdatum (final @Nullable java.lang.String Leistungsdatum) { set_Value (COLUMNNAME_Leistungsdatum, Leistungsdatum); } @Override public java.lang.String getLeistungsdatum() { return get_ValueAsString(COLUMNNAME_Leistungsdatum); } @Override public void setSkonto (final @Nullable java.lang.String Skonto) { set_Value (COLUMNNAME_Skonto, Skonto); } @Override public java.lang.String getSkonto() { return get_ValueAsString(COLUMNNAME_Skonto); } @Override public void setUmsatz (final @Nullable java.lang.String Umsatz) { set_Value (COLUMNNAME_Umsatz, Umsatz); } @Override public java.lang.String getUmsatz() { return get_ValueAsString(COLUMNNAME_Umsatz); } @Override public void setZI_Art (final @Nullable java.lang.String ZI_Art) { set_Value (COLUMNNAME_ZI_Art, ZI_Art); } @Override public java.lang.String getZI_Art() { return get_ValueAsString(COLUMNNAME_ZI_Art); } @Override public void setZI_Inhalt (final @Nullable java.lang.String ZI_Inhalt) { set_Value (COLUMNNAME_ZI_Inhalt, ZI_Inhalt); } @Override public java.lang.String getZI_Inhalt() { return get_ValueAsString(COLUMNNAME_ZI_Inhalt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExportLine.java
1
请完成以下Java代码
public static NullOperator ofNotNullFlag(@Nullable final Boolean notNullFlag) { if (notNullFlag == null) { return ANY; } else if (notNullFlag) { return IS_NOT_NULL; } else { return IS_NULL; } } public NullOperator negateIf(final boolean value) { return value ? negate() : this; }
public NullOperator negate() { switch (this) { case IS_NULL: return IS_NOT_NULL; case IS_NOT_NULL: return IS_NULL; case ANY: return ANY; default: throw new IllegalStateException("Unhandled: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\NullOperator.java
1
请完成以下Java代码
private String issueProjectLine() { MProjectLine pl = new MProjectLine(getCtx(), m_C_ProjectLine_ID, get_TrxName()); if (pl.getM_Product_ID() == 0) throw new IllegalArgumentException("Projet Line has no Product"); if (pl.getC_ProjectIssue_ID() != 0) throw new IllegalArgumentException("Projet Line already been issued"); if (m_M_Locator_ID == 0) throw new IllegalArgumentException("No Locator"); // Set to Qty 1 if (pl.getPlannedQty() == null || pl.getPlannedQty().signum() == 0) pl.setPlannedQty(Env.ONE); // MProjectIssue pi = new MProjectIssue (m_project); pi.setMandatory (m_M_Locator_ID, pl.getM_Product_ID(), pl.getPlannedQty()); if (m_MovementDate != null) // default today pi.setMovementDate(m_MovementDate); if (m_Description != null && m_Description.length() > 0) pi.setDescription(m_Description); else if (pl.getDescription() != null) pi.setDescription(pl.getDescription()); pi.process(); // Update Line pl.setMProjectIssue(pi); pl.save(); addLog(pi.getLine(), pi.getMovementDate(), pi.getMovementQty(), null); return "@Created@ 1"; } // issueProjectLine /** * Issue from Inventory * @return Message (clear text) */ private String issueInventory() { if (m_M_Locator_ID == 0) throw new IllegalArgumentException("No Locator"); if (m_M_Product_ID == 0) throw new IllegalArgumentException("No Product"); // Set to Qty 1 if (m_MovementQty == null || m_MovementQty.signum() == 0) m_MovementQty = Env.ONE; // MProjectIssue pi = new MProjectIssue (m_project); pi.setMandatory (m_M_Locator_ID, m_M_Product_ID, m_MovementQty); if (m_MovementDate != null) // default today pi.setMovementDate(m_MovementDate); if (m_Description != null && m_Description.length() > 0) pi.setDescription(m_Description); pi.process();
// Create Project Line MProjectLine pl = new MProjectLine(m_project); pl.setMProjectIssue(pi); pl.save(); addLog(pi.getLine(), pi.getMovementDate(), pi.getMovementQty(), null); return "@Created@ 1"; } // issueInventory /** * Check if Project Issue already has Expense * @param S_TimeExpenseLine_ID line * @return true if exists */ private boolean projectIssueHasExpense (int S_TimeExpenseLine_ID) { if (m_projectIssues == null) m_projectIssues = m_project.getIssues(); for (int i = 0; i < m_projectIssues.length; i++) { if (m_projectIssues[i].getS_TimeExpenseLine_ID() == S_TimeExpenseLine_ID) return true; } return false; } // projectIssueHasExpense /** * Check if Project Issue already has Receipt * @param M_InOutLine_ID line * @return true if exists */ private boolean projectIssueHasReceipt (int M_InOutLine_ID) { if (m_projectIssues == null) m_projectIssues = m_project.getIssues(); for (int i = 0; i < m_projectIssues.length; i++) { if (m_projectIssues[i].getM_InOutLine_ID() == M_InOutLine_ID) return true; } return false; } // projectIssueHasReceipt } // ProjectIssue
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectIssue.java
1
请完成以下Java代码
public String getDescription() { if (localizedDescription != null && localizedDescription.length() > 0) { return localizedDescription; } else { return description; } } public void setDescription(String description) { this.description = description; } public String getLocalizedDescription() { return localizedDescription; } public void setLocalizedDescription(String localizedDescription) { this.localizedDescription = localizedDescription; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(Integer processDefinitionVersion) {
this.processDefinitionVersion = processDefinitionVersion; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getBasePath() { return this.basePath; } public void setBasePath(String basePath) { this.basePath = cleanBasePath(basePath); } public @Nullable Ssl getSsl() { return this.ssl; } public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; } @Contract("!null -> !null") private @Nullable String cleanBasePath(@Nullable String basePath) { String candidate = null;
if (StringUtils.hasLength(basePath)) { candidate = basePath.strip(); } if (StringUtils.hasText(candidate)) { if (!candidate.startsWith("/")) { candidate = "/" + candidate; } if (candidate.endsWith("/")) { candidate = candidate.substring(0, candidate.length() - 1); } } return candidate; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\web\server\ManagementServerProperties.java
2
请完成以下Java代码
public void save(final MapSession session) { sessions.put(session.getId(), new MapSession(session)); } @Override public MapSession findById(final String id) { final MapSession saved = sessions.get(id); if (saved == null) { return null; } if (saved.isExpired()) { final boolean expired = true; deleteAndFireEvent(saved.getId(), expired); return null; } return new MapSession(saved); } @Override public void deleteById(final String id) { final boolean expired = false; deleteAndFireEvent(id, expired); } private void deleteAndFireEvent(final String id, boolean expired) { final MapSession deletedSession = sessions.remove(id); // Fire event if (deletedSession != null) { if (expired) { applicationEventPublisher.publishEvent(new SessionExpiredEvent(this, deletedSession)); } else { applicationEventPublisher.publishEvent(new SessionDeletedEvent(this, deletedSession)); } } }
@Override public MapSession createSession() { final MapSession result = new MapSession(); if (defaultMaxInactiveInterval != null) { result.setMaxInactiveInterval(defaultMaxInactiveInterval); } // Fire event applicationEventPublisher.publishEvent(new SessionCreatedEvent(this, result)); return result; } public void purgeExpiredSessionsNoFail() { try { purgeExpiredSessions(); } catch (final Throwable ex) { logger.warn("Failed purging expired sessions. Ignored.", ex); } } public void purgeExpiredSessions() { final Stopwatch stopwatch = Stopwatch.createStarted(); int countExpiredSessions = 0; final List<MapSession> sessionsToCheck = new ArrayList<>(sessions.values()); for (final MapSession session : sessionsToCheck) { if (session.isExpired()) { deleteAndFireEvent(session.getId(), true /* expired */); countExpiredSessions++; } } logger.debug("Purged {}/{} expired sessions in {}", countExpiredSessions, sessionsToCheck.size(), stopwatch); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\FixedMapSessionRepository.java
1
请完成以下Java代码
public void deleteUserInfo(String userId, String key) { commandExecutor.execute(new DeleteUserInfoCmd(userId, key)); } @Override public Privilege createPrivilege(String name) { return commandExecutor.execute(new CreatePrivilegeCmd(name, configuration)); } @Override public void addUserPrivilegeMapping(String privilegeId, String userId) { commandExecutor.execute(new AddPrivilegeMappingCmd(privilegeId, userId, null, configuration)); } @Override public void deleteUserPrivilegeMapping(String privilegeId, String userId) { commandExecutor.execute(new DeletePrivilegeMappingCmd(privilegeId, userId, null)); } @Override public void addGroupPrivilegeMapping(String privilegeId, String groupId) { commandExecutor.execute(new AddPrivilegeMappingCmd(privilegeId, null, groupId, configuration)); } @Override public void deleteGroupPrivilegeMapping(String privilegeId, String groupId) { commandExecutor.execute(new DeletePrivilegeMappingCmd(privilegeId, null, groupId)); } @Override public List<PrivilegeMapping> getPrivilegeMappingsByPrivilegeId(String privilegeId) { return commandExecutor.execute(new GetPrivilegeMappingsByPrivilegeIdCmd(privilegeId)); } @Override
public void deletePrivilege(String id) { commandExecutor.execute(new DeletePrivilegeCmd(id)); } @Override public PrivilegeQuery createPrivilegeQuery() { return commandExecutor.execute(new CreatePrivilegeQueryCmd()); } @Override public List<Group> getGroupsWithPrivilege(String name) { return commandExecutor.execute(new GetGroupsWithPrivilegeCmd(name)); } @Override public List<User> getUsersWithPrivilege(String name) { return commandExecutor.execute(new GetUsersWithPrivilegeCmd(name)); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\IdmIdentityServiceImpl.java
1
请完成以下Java代码
public class TotalProductsShippedQuery { private final String productId; public TotalProductsShippedQuery(String productId) { this.productId = productId; } public String getProductId() { return productId; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} TotalProductsShippedQuery that = (TotalProductsShippedQuery) o; return Objects.equals(productId, that.productId); } @Override public int hashCode() { return Objects.hash(productId); } @Override public String toString() { return "TotalProductsShippedQuery{" + "productId='" + productId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\queries\TotalProductsShippedQuery.java
1
请在Spring Boot框架中完成以下Java代码
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } @Override public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) { // prevent errors on serializing de.metas.ui.web.config.WebuiExceptionHandler#getErrorAttributes final MediaType javascriptMediaType = MediaType.valueOf("application/javascript"); for (final HttpMessageConverter<?> converter : converters) { if (converter instanceof MappingJackson2HttpMessageConverter) { final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter; if (jacksonConverter.getSupportedMediaTypes().contains(javascriptMediaType)) { break; } final List<MediaType> supportedMediaTypes = new ArrayList<>(jacksonConverter.getSupportedMediaTypes()); supportedMediaTypes.add(javascriptMediaType); jacksonConverter.setSupportedMediaTypes(supportedMediaTypes); break; } } } @Bean public Filter corsFilter() { return new CORSFilter(); } @Bean public Filter addMissingHeadersFilter() { return new Filter() { @Override public void init(final FilterConfig filterConfig) { } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { try {
chain.doFilter(request, response); } finally { if (response instanceof HttpServletResponse) { final HttpServletResponse httpResponse = (HttpServletResponse)response; // // If the Cache-Control is not set then set it to no-cache. // In this way we precisely tell to browser that it shall not cache our REST calls. // The Cache-Control is usually defined by features like ETag if (!httpResponse.containsHeader("Cache-Control")) { httpResponse.setHeader("Cache-Control", "no-cache"); } } } } @Override public void destroy() { } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class SolrServiceImpl implements SolrService { @Autowired private SolrClient client; /** * 高亮查询 */ @Override public SolrDocumentList querySolr(String collection, String q, String field) throws IOException, SolrServerException { SolrQuery params = new SolrQuery(); //查询条件, 这里的 q 对应 下面图片标红的地方 params.set("q", q); //过滤条件 // params.set("fq", "product_price:[100 TO 100000]"); //排序 // params.addSort("id", SolrQuery.ORDER.asc); //分页 params.setStart(0); params.setRows(20); //默认域 params.set("df", field); //只查询指定域 // params.set("fl", content + ",content,id,title,author"); //高亮 //打开开关 params.setHighlight(true); //指定高亮域 params.addHighlightField("id"); params.addHighlightField(field); params.addHighlightField("title"); params.addHighlightField("content"); params.addHighlightField("author"); params.addHighlightField("productName"); params.addHighlightField("productDesc"); //设置前缀 params.setHighlightSimplePre("<span style='color:red'>"); //设置后缀 params.setHighlightSimplePost("</span>"); QueryResponse queryResponse = client.query(collection,params); SolrDocumentList results = queryResponse.getResults(); long numFound = results.getNumFound(); // 查询到的结果 //获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的 Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting(); for(SolrDocument result : results){ // 将高亮结果合并到查询结果中 result.remove("keyword"); highlight.forEach((k,v) ->{ if(result.get("id").equals(k)){ v.forEach((k1,v1) -> { if(!k1.equals("keyword")) result.setField(k1,v1); // 高亮列合并如结果
}); } }); } return results; } /** * 根据ID查询 */ @Override public SolrDocument getById(String collection, String id) throws IOException, SolrServerException { return client.getById(id); } /** * 删除全部索引 * @param collection */ @Override public void deleteAll(String collection) throws IOException, SolrServerException { client.deleteByQuery(collection,"*:*"); client.commit(collection); } }
repos\springboot-demo-master\solr\src\main\java\demo\et59\solr\service\impl\SolrServiceImpl.java
2
请完成以下Java代码
public @Nullable String getPermittedCrossDomainPoliciesHeaderValue() { return permittedCrossDomainPoliciesHeaderValue; } public void setPermittedCrossDomainPoliciesHeaderValue( @Nullable String permittedCrossDomainPoliciesHeaderValue) { this.permittedCrossDomainPoliciesHeaderValue = permittedCrossDomainPoliciesHeaderValue; } public @Nullable String getPermissionPolicyHeaderValue() { return permissionPolicyHeaderValue; } public void setPermissionPolicyHeaderValue(@Nullable String permissionPolicyHeaderValue) { this.permissionPolicyHeaderValue = permissionPolicyHeaderValue; } /** * bind the route specific/opt-in header names to enable, in lower case. */ void setEnable(Set<String> enable) { if (enable != null) { this.routeFilterConfigProvided = true; this.routeEnabledHeaders = enable.stream() .map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } } /** * @return the route specific/opt-in header names to enable, in lower case. */ Set<String> getRouteEnabledHeaders() { return routeEnabledHeaders; } /** * bind the route specific/opt-out header names to disable, in lower case. */ void setDisable(Set<String> disable) { if (disable != null) { this.routeFilterConfigProvided = true; this.routeDisabledHeaders = disable.stream()
.map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } } /** * @return the route specific/opt-out header names to disable, in lower case */ Set<String> getRouteDisabledHeaders() { return routeDisabledHeaders; } /** * @return the route specific/opt-out permission policies. */ protected @Nullable String getRoutePermissionsPolicyHeaderValue() { return routePermissionsPolicyHeaderValue; } /** * bind the route specific/opt-out permissions policy. */ void setPermissionsPolicy(@Nullable String permissionsPolicy) { this.routeFilterConfigProvided = true; this.routePermissionsPolicyHeaderValue = permissionsPolicy; } /** * @return flag whether route specific arguments were bound. */ boolean isRouteFilterConfigProvided() { return routeFilterConfigProvided; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java
1