instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public List<String> fieldNames() {
if(jsonNode.isContainerNode()) {
Iterator<String> iterator = jsonNode.fieldNames();
List<String> list = new ArrayList<String>();
while(iterator.hasNext()) {
list.add(iterator.next());
}
return list;
} else {
throw LOG.unableToParseValue("Array/Object", jsonNode.getNodeType());
}
}
public JsonNodeType getNodeType() {
return jsonNode.getNodeType();
}
public SpinJsonPathQuery jsonPath(String expression) {
ensureNotNull("expression", expression);
try {
JsonPath query = JsonPath.compile(expression);
return new JacksonJsonPathQuery(this, query, dataFormat);
} catch(InvalidPathException pex) {
throw LOG.unableToCompileJsonPathExpression(expression, pex);
} catch(IllegalArgumentException aex) {
throw LOG.unableToCompileJsonPathExpression(expression, aex);
}
}
/**
* Maps the json represented by this object to a java object of the given type.<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type | */
public <C> C mapTo(Class<C> type) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
/**
* Maps the json represented by this object to a java object of the given type.
* Argument is to be supplied in Jackson's canonical type string format
* (see {@link JavaType#toCanonical()}).<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type
* @throws SpinJsonDataFormatException if the parameter does not match a valid type
*/
public <C> C mapTo(String type) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
/**
* Maps the json represented by this object to a java object of the given type.<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type
*/
public <C> C mapTo(JavaType type) {
JacksonJsonDataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
} | repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\JacksonJsonNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonFormat(pattern = "dd/MM/yyyy") private LocalDate dateCreated;
private String status;
@OneToMany(mappedBy = "pk.order")
@Valid
private List<OrderProduct> orderProducts = new ArrayList<>();
@Transient
public Double getTotalOrderPrice() {
double sum = 0D;
List<OrderProduct> orderProducts = getOrderProducts();
for (OrderProduct op : orderProducts) {
sum += op.getTotalPrice();
}
return sum;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDate dateCreated) {
this.dateCreated = dateCreated;
}
public String getStatus() { | return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<OrderProduct> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProduct> orderProducts) {
this.orderProducts = orderProducts;
}
@Transient
public int getNumberOfProducts() {
return this.orderProducts.size();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\Order.java | 2 |
请完成以下Java代码 | public void setSourceWarehouse(String sourceWarehouse) {
this.sourceWarehouse = sourceWarehouse;
}
public String getDestinationCountry() {
return destinationCountry;
}
public void setDestinationCountry(String destinationCountry) {
this.destinationCountry = destinationCountry;
}
public String getTenantChannel() {
return tenantChannel;
}
public void setTenantChannel(String tenantChannel) {
this.tenantChannel = tenantChannel;
}
public int getNumberOfIndividuals() {
return numberOfIndividuals;
}
public void setNumberOfIndividuals(int numberOfIndividuals) {
this.numberOfIndividuals = numberOfIndividuals;
}
public int getNumberOfPacks() {
return numberOfPacks;
}
public void setNumberOfPacks(int numberOfPacks) {
this.numberOfPacks = numberOfPacks;
} | public int getItemsPerPack() {
return itemsPerPack;
}
public void setItemsPerPack(int itemsPerPack) {
this.itemsPerPack = itemsPerPack;
}
public String getClientUuid() {
return clientUuid;
}
public void setClientUuid(String clientUuid) {
this.clientUuid = clientUuid;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\customstatefulvalidation\model\PurchaseOrderItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class ProductWithAvailabilityInfo
{
@NonNull
ProductId productId;
@NonNull
ITranslatableString productDisplayName;
Quantity qty;
@NonNull
@Default
Group.Type attributesType = Group.Type.ALL_STORAGE_KEYS;
@NonNull
@Default
ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY;
}
public static ProductId toProductId(@NonNull final LookupValue lookupValue)
{
return lookupValue.getIdAs(ProductId::ofRepoId);
}
public static ProductAndAttributes toProductAndAttributes(@NonNull final LookupValue lookupValue)
{
final ProductId productId = lookupValue.getIdAs(ProductId::ofRepoId);
final Map<Object, Object> valuesByAttributeIdMap = lookupValue.getAttribute(ATTRIBUTE_ASI);
final ImmutableAttributeSet attributes = ImmutableAttributeSet.ofValuesByAttributeIdMap(valuesByAttributeIdMap);
return ProductAndAttributes.builder()
.productId(productId)
.attributes(attributes)
.build();
}
private boolean isFullTextSearchEnabled()
{
final boolean disabled = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DisableFullTextSearch, false);
return !disabled;
}
@Value
@Builder(toBuilder = true)
public static class ProductAndAttributes | {
@NonNull
ProductId productId;
@Default
@NonNull
ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY;
}
private interface I_M_Product_Lookup_V
{
String Table_Name = "M_Product_Lookup_V";
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
String COLUMNNAME_IsActive = "IsActive";
String COLUMNNAME_M_Product_ID = "M_Product_ID";
String COLUMNNAME_Value = "Value";
String COLUMNNAME_Name = "Name";
String COLUMNNAME_UPC = "UPC";
String COLUMNNAME_BPartnerProductNo = "BPartnerProductNo";
String COLUMNNAME_BPartnerProductName = "BPartnerProductName";
String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID";
String COLUMNNAME_Discontinued = "Discontinued";
String COLUMNNAME_DiscontinuedFrom = "DiscontinuedFrom";
String COLUMNNAME_IsBOM = "IsBOM";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\ProductLookupDescriptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public MultipleArticlesResponse getFeedArticles(
User me,
@RequestParam(value = "limit", required = false, defaultValue = "20") int limit,
@RequestParam(value = "offset", required = false, defaultValue = "0") int offset) {
ArticleFacets facets = new ArticleFacets(null, null, null, offset, limit);
List<ArticleVO> articles = articleService.getFeedArticles(me, facets);
return new MultipleArticlesResponse(articles);
}
@PostMapping("/api/articles/{slug}/comments")
public SingleCommentResponse createComment(
User me, @PathVariable String slug, @RequestBody CreateCommentRequest request) {
CommentVO comment = articleService.createComment(me, slug, request);
return new SingleCommentResponse(comment);
}
@GetMapping("/api/articles/{slug}/comments")
public MultipleCommentsResponse getComments(User me, @PathVariable String slug) {
List<CommentVO> comments = articleService.getArticleComments(me, slug);
return new MultipleCommentsResponse(comments);
}
@DeleteMapping("/api/articles/{slug}/comments/{id}") | public void deleteComment(User me, @PathVariable String slug, @PathVariable int id) {
articleService.deleteComment(me, id);
}
@PostMapping("/api/articles/{slug}/favorite")
public SingleArticleResponse favoriteArticle(User me, @PathVariable String slug) {
ArticleVO article = articleService.favoriteArticle(me, slug);
return new SingleArticleResponse(article);
}
@DeleteMapping("/api/articles/{slug}/favorite")
public SingleArticleResponse unfavoriteArticle(User me, @PathVariable String slug) {
ArticleVO article = articleService.unfavoriteArticle(me, slug);
return new SingleArticleResponse(article);
}
} | repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\article\controller\ArticleController.java | 2 |
请完成以下Java代码 | protected static void convertXml2CsvStax(String xmlFilePath, String csvFilePath) throws IOException, TransformerException {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try (InputStream in = Files.newInputStream(Paths.get(xmlFilePath)); BufferedWriter writer = new BufferedWriter(new FileWriter(csvFilePath))) {
writer.write("bookstore_id,book_id,category,title,author_id,author_name,price\n");
XMLStreamReader reader = inputFactory.createXMLStreamReader(in);
String currentElement;
StringBuilder csvRow = new StringBuilder();
StringBuilder bookstoreInfo = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamConstants.START_ELEMENT:
currentElement = reader.getLocalName();
if ("Bookstore".equals(currentElement)) {
bookstoreInfo.setLength(0);
bookstoreInfo.append(reader.getAttributeValue(null, "id"))
.append(",");
}
if ("Book".equals(currentElement)) {
csvRow.append(bookstoreInfo)
.append(reader.getAttributeValue(null, "id"))
.append(",")
.append(reader.getAttributeValue(null, "category"))
.append(",");
}
if ("Author".equals(currentElement)) {
csvRow.append(reader.getAttributeValue(null, "id"))
.append(",");
}
break;
case XMLStreamConstants.CHARACTERS:
if (!reader.isWhiteSpace()) {
csvRow.append(reader.getText()
.trim())
.append(","); | }
break;
case XMLStreamConstants.END_ELEMENT:
if ("Book".equals(reader.getLocalName())) {
csvRow.setLength(csvRow.length() - 1);
csvRow.append("\n");
writer.write(csvRow.toString());
csvRow.setLength(0);
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\xml2csv\Xml2CsvExample.java | 1 |
请完成以下Java代码 | public JsonGetWorkplaceResponse getWorkplace(@RequestParam(name = "includeAvailable", required = false) final boolean includeAvailable)
{
userSession.assertLoggedIn();
final boolean isWorkplacesEnabled = userSession.isWorkplacesEnabled();
if (isWorkplacesEnabled)
{
final JsonGetWorkplaceResponseBuilder builder = JsonGetWorkplaceResponse.builder().workplacesEnabled(true);
userSession.getWorkplace()
.map(UserSessionRestController::toJSONLookupValue)
.ifPresent(builder::currentWorkplace);
if (includeAvailable)
{
builder.available(workplaceService.getAllActive()
.stream()
.map(UserSessionRestController::toJSONLookupValue)
.sorted(Comparator.comparing(JSONLookupValue::getCaption))
.collect(ImmutableList.toImmutableList()));
}
return builder.build();
}
else
{ | return JsonGetWorkplaceResponse.NOT_ENABLED;
}
}
private static JSONLookupValue toJSONLookupValue(@NonNull Workplace workplace)
{
return JSONLookupValue.of(workplace.getId(), workplace.getName());
}
@PutMapping("/workplace")
public void setWorkplace(@RequestBody @NonNull final JsonChangeWorkplaceRequest request)
{
userSession.assertLoggedIn();
if (!userSession.isWorkplacesEnabled())
{
throw new AdempiereException("Workplaces not enabled");
}
workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder()
.workplaceId(request.getWorkplaceId())
.userId(userSession.getLoggedUserId())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSessionRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<User> retrieveAllUsers() {
return userRepository.findAll();
}
//http://localhost:8080/users
//EntityModel
//WebMvcLinkBuilder
@GetMapping("/jpa/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable int id) {
Optional<User> user = userRepository.findById(id);
if(user.isEmpty())
throw new UserNotFoundException("id:"+id);
EntityModel<User> entityModel = EntityModel.of(user.get());
WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers());
entityModel.add(link.withRel("all-users"));
return entityModel;
}
@DeleteMapping("/jpa/users/{id}")
public void deleteUser(@PathVariable int id) {
userRepository.deleteById(id);
}
@GetMapping("/jpa/users/{id}/posts")
public List<Post> retrievePostsForUser(@PathVariable int id) {
Optional<User> user = userRepository.findById(id);
if(user.isEmpty())
throw new UserNotFoundException("id:"+id);
return user.get().getPosts();
} | @PostMapping("/jpa/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User savedUser = userRepository.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@PostMapping("/jpa/users/{id}/posts")
public ResponseEntity<Object> createPostForUser(@PathVariable int id, @Valid @RequestBody Post post) {
Optional<User> user = userRepository.findById(id);
if(user.isEmpty())
throw new UserNotFoundException("id:"+id);
post.setUser(user.get());
Post savedPost = postRepository.save(post);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedPost.getId())
.toUri();
return ResponseEntity.created(location).build();
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserJpaResource.java | 2 |
请完成以下Java代码 | public ImmutableList<DeliveryLineCandidate> getAllLines()
{
return ImmutableList.copyOf(deliveryLineCandidates);
}
@Value
private static class ShipperKey
{
public static ShipperKey of(final Optional<ShipperId> shipperId, final WarehouseId warehouseId, final String bpartnerAddress)
{
return new ShipperKey(bpartnerAddress, warehouseId, shipperId.orElse(null));
}
String bpartnerAddress;
WarehouseId warehouseId;
ShipperId shipperId;
} | @Value
private static class OrderKey
{
public static OrderKey of(
final DeliveryGroupCandidateGroupId groupId,
final WarehouseId warehouseId,
final String bpartnerAddress)
{
return new OrderKey(bpartnerAddress, warehouseId, groupId);
}
String bpartnerAddress;
WarehouseId warehouseId;
DeliveryGroupCandidateGroupId groupId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentSchedulesDuringUpdate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceRejectionDetailRepo
{
private static final String REASON_SEPARATOR = "\n";
private final AttachmentEntryService attachmentEntryService;
public InvoiceRejectionDetailRepo(@NonNull final AttachmentEntryService attachmentEntryService)
{
this.attachmentEntryService = attachmentEntryService;
}
private I_C_Invoice_Rejection_Detail of(@NonNull final ImportedInvoiceResponse response)
{
final I_C_Invoice_Rejection_Detail rejectionDetail = InterfaceWrapperHelper.newInstance(I_C_Invoice_Rejection_Detail.class);
rejectionDetail.setIsDone(false);
rejectionDetail.setInvoiceNumber(response.getDocumentNumber());
if (response.getInvoiceId() != null)
{
rejectionDetail.setC_Invoice_ID(response.getInvoiceId().getRepoId());
}
rejectionDetail.setClient(response.getClient());
rejectionDetail.setInvoiceRecipient(response.getInvoiceRecipient());
rejectionDetail.setReason(Joiner.on(REASON_SEPARATOR).join(response.getReason()));
rejectionDetail.setExplanation(response.getExplanation());
rejectionDetail.setResponsiblePerson(response.getResponsiblePerson());
rejectionDetail.setPhone(response.getPhone());
rejectionDetail.setEMail(response.getEmail());
final Status status = response.getStatus();
if (status == null)
{
throw new AdempiereException("The given response has no status. Probably support for this type of response is not implemented yet")
.appendParametersToMessage()
.setParameter("response", response);
}
rejectionDetail.setStatus(status.name()); | rejectionDetail.setAD_Org_ID(response.getBillerOrg());
return rejectionDetail;
}
public InvoiceRejectionDetailId save(@NonNull final ImportedInvoiceResponse importedInvoiceResponse)
{
final I_C_Invoice_Rejection_Detail invoiceRejectionDetail = of(importedInvoiceResponse);
InterfaceWrapperHelper.saveRecord(invoiceRejectionDetail);
attachFileToInvoiceRejectionDetail(importedInvoiceResponse, invoiceRejectionDetail);
return InvoiceRejectionDetailId.ofRepoId(invoiceRejectionDetail.getC_Invoice_Rejection_Detail_ID());
}
private void attachFileToInvoiceRejectionDetail(
@NonNull final ImportedInvoiceResponse response,
@NonNull final I_C_Invoice_Rejection_Detail invoiceRejectionDetail)
{
final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest
.builderFromByteArray(response.getRequest().getFileName(), response.getRequest().getData())
.tags(AttachmentTags.ofMap(response.getAdditionalTags()))
.build();
attachmentEntryService.createNewAttachment(invoiceRejectionDetail, attachmentEntryCreateRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\InvoiceRejectionDetailRepo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookController {
@Autowired
private BookRepository bookRepository;
/**
* Create book.
*
* @param book the book
* @return the book
*/
@PostMapping("/books")
public ResponseEntity<Book> createBook(@RequestBody Book book) {
bookRepository.add(book);
return ResponseEntity.ok(book);
}
/**
* Get all books.
*
* @return the list
*/
@GetMapping("/books")
public ResponseEntity<List<Book>> getAllBooks() {
return ResponseEntity.ok(bookRepository.getBooks());
}
/**
* Gets book by id.
*
* @param bookId the book id|1
* @return the book by id
*/
@GetMapping("/book/{id}")
public ResponseEntity<Book> getBookById(@PathVariable(value = "id") Long bookId) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
return ResponseEntity.ok(book);
}
/**
* Update book response entity.
* | * @param bookId the book id|1
* @param bookDetails the book details
* @return the response entity
*/
@PutMapping("/books/{id}")
public ResponseEntity<Book> updateBook(@PathVariable(value = "id") Long bookId, @Valid @RequestBody Book bookDetails) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
book.setAuthor(bookDetails.getAuthor());
book.setPrice(bookDetails.getPrice());
book.setTitle(bookDetails.getTitle());
bookRepository.add(book);
return ResponseEntity.ok(book);
}
/**
* Delete book.
*
* @param bookId the book id|1
* @return the true
*/
@DeleteMapping("/book/{id}")
public ResponseEntity<Boolean> deleteBook(@PathVariable(value = "id") Long bookId) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new ResponseStatusException(HttpStatusCode.valueOf(404)));
return ResponseEntity.ok(bookRepository.delete(book));
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\smartdoc\BookController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OpenApiAuthController extends JeecgController<OpenApiAuth, OpenApiAuthService> {
/**
* 分页列表查询
*
* @param openApiAuth
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@GetMapping(value = "/list")
public Result<?> queryPageList(OpenApiAuth openApiAuth, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
QueryWrapper<OpenApiAuth> queryWrapper = QueryGenerator.initQueryWrapper(openApiAuth, req.getParameterMap());
Page<OpenApiAuth> page = new Page<>(pageNo, pageSize);
IPage<OpenApiAuth> pageList = service.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 添加
*
* @param openApiAuth
* @return
*/
@PostMapping(value = "/add")
public Result<?> add(@RequestBody OpenApiAuth openApiAuth) {
service.save(openApiAuth);
return Result.ok("添加成功!");
}
/**
* 编辑
*
* @param openApiAuth
* @return
*/
@PutMapping(value = "/edit")
public Result<?> edit(@RequestBody OpenApiAuth openApiAuth) {
service.updateById(openApiAuth);
return Result.ok("修改成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
service.removeById(id);
return Result.ok("删除成功!"); | }
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.service.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
OpenApiAuth openApiAuth = service.getById(id);
return Result.ok(openApiAuth);
}
/**
* 生成AKSK
* @return
*/
@GetMapping("genAKSK")
public Result<String[]> genAKSK() {
return Result.ok(AKSKGenerator.genAKSKPair());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiAuthController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | default Iterator<SpanProcessor> iterator() {
return list().iterator();
}
@Override
default Spliterator<SpanProcessor> spliterator() {
return list().spliterator();
}
/**
* Constructs a {@link SpanProcessors} instance with the given {@link SpanProcessor
* span processors}.
* @param spanProcessors the span processors
* @return the constructed {@link SpanProcessors} instance
*/
static SpanProcessors of(SpanProcessor... spanProcessors) { | return of(Arrays.asList(spanProcessors));
}
/**
* Constructs a {@link SpanProcessors} instance with the given list of
* {@link SpanProcessor span processors}.
* @param spanProcessors the list of span processors
* @return the constructed {@link SpanProcessors} instance
*/
static SpanProcessors of(Collection<? extends SpanProcessor> spanProcessors) {
Assert.notNull(spanProcessors, "'spanProcessors' must not be null");
List<SpanProcessor> copy = List.copyOf(spanProcessors);
return () -> copy;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\SpanProcessors.java | 2 |
请完成以下Java代码 | private static void initialize(final Path snapshotPath) {
announcementWatcher = new HollowFilesystemAnnouncementWatcher(snapshotPath);
blobRetriever = new HollowFilesystemBlobRetriever(snapshotPath);
logger.info("snapshot data file location: {}", snapshotPath.toString());
consumer = new HollowConsumer.Builder<>()
.withAnnouncementWatcher(announcementWatcher)
.withBlobRetriever(blobRetriever)
.withGeneratedAPIClass(MonitoringEventAPI.class)
.build();
consumer.triggerRefresh();
monitoringEventAPI = consumer.getAPI(MonitoringEventAPI.class);
}
private static void sleep(long milliseconds) {
try { | Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static Path getSnapshotFilePath() {
String moduleDir = System.getProperty("user.dir");
String snapshotPath = moduleDir + "/.hollow/snapshots";
logger.info("snapshot data directory: {}", snapshotPath);
Path path = Paths.get(snapshotPath);
return path;
}
} | repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\consumer\MonitoringEventConsumer.java | 1 |
请完成以下Java代码 | public int getDefaultOrderByPriority()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().getDefaultOrderByPriority();
}
public boolean isDefaultOrderByAscending()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().isDefaultOrderByAscending();
}
public Builder deviceDescriptorsProvider(@NonNull final DeviceDescriptorsProvider deviceDescriptorsProvider)
{
this.deviceDescriptorsProvider = deviceDescriptorsProvider;
return this; | }
private DeviceDescriptorsProvider getDeviceDescriptorsProvider()
{
return deviceDescriptorsProvider;
}
public Builder mainAdFieldId(@Nullable final AdFieldId mainAdFieldId)
{
this.mainAdFieldId = mainAdFieldId;
return this;
}
@Nullable
public AdFieldId getMainAdFieldId() {return mainAdFieldId;}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDescriptor.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: publisher-demo
# RabbitMQ 相关配置项
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
management:
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 |
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 | repos\SpringBoot-Labs-master\labx-18\labx-18-sc-bus-rabbitmq-demo-publisher-actuator\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void setHeaderAggregationKey (final java.lang.String HeaderAggregationKey)
{
set_ValueNoCheck (COLUMNNAME_HeaderAggregationKey, HeaderAggregationKey);
}
@Override
public java.lang.String getHeaderAggregationKey()
{
return get_ValueAsString(COLUMNNAME_HeaderAggregationKey);
}
@Override
public void setHeaderAggregationKeyBuilder_ID (final int HeaderAggregationKeyBuilder_ID)
{
if (HeaderAggregationKeyBuilder_ID < 1)
set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, null);
else
set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, HeaderAggregationKeyBuilder_ID);
}
@Override
public int getHeaderAggregationKeyBuilder_ID()
{
return get_ValueAsInt(COLUMNNAME_HeaderAggregationKeyBuilder_ID);
}
@Override
public void setInvoicingGroupNo (final int InvoicingGroupNo)
{
set_ValueNoCheck (COLUMNNAME_InvoicingGroupNo, InvoicingGroupNo);
}
@Override
public int getInvoicingGroupNo() | {
return get_ValueAsInt(COLUMNNAME_InvoicingGroupNo);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_HeaderAggregation.java | 1 |
请完成以下Java代码 | public boolean isValidateSchema() {
return validateSchema;
}
public void setValidateSchema(boolean validateSchema) {
this.validateSchema = validateSchema;
}
public boolean isValidateProcess() {
return validateProcess;
}
public void setValidateProcess(boolean validateProcess) {
this.validateProcess = validateProcess;
}
public List<ProcessDefinitionEntity> getProcessDefinitions() {
return processDefinitions;
}
public String getTargetNamespace() {
return targetNamespace;
}
public BpmnParseHandlers getBpmnParserHandlers() {
return bpmnParserHandlers;
}
public void setBpmnParserHandlers(BpmnParseHandlers bpmnParserHandlers) {
this.bpmnParserHandlers = bpmnParserHandlers;
}
public DeploymentEntity getDeployment() {
return deployment;
}
public void setDeployment(DeploymentEntity deployment) {
this.deployment = deployment;
}
public BpmnModel getBpmnModel() {
return bpmnModel;
}
public void setBpmnModel(BpmnModel bpmnModel) {
this.bpmnModel = bpmnModel;
}
public ActivityBehaviorFactory getActivityBehaviorFactory() {
return activityBehaviorFactory;
}
public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) {
this.activityBehaviorFactory = activityBehaviorFactory;
}
public ListenerFactory getListenerFactory() {
return listenerFactory;
}
public void setListenerFactory(ListenerFactory listenerFactory) {
this.listenerFactory = listenerFactory;
}
public Map<String, SequenceFlow> getSequenceFlows() { | return sequenceFlows;
}
public ProcessDefinitionEntity getCurrentProcessDefinition() {
return currentProcessDefinition;
}
public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) {
this.currentProcessDefinition = currentProcessDefinition;
}
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
public void setCurrentFlowElement(FlowElement currentFlowElement) {
this.currentFlowElement = currentFlowElement;
}
public Process getCurrentProcess() {
return currentProcess;
}
public void setCurrentProcess(Process currentProcess) {
this.currentProcess = currentProcess;
}
public void setCurrentSubProcess(SubProcess subProcess) {
currentSubprocessStack.push(subProcess);
}
public SubProcess getCurrentSubProcess() {
return currentSubprocessStack.peek();
}
public void removeCurrentSubProcess() {
currentSubprocessStack.pop();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java | 1 |
请完成以下Java代码 | public class AddHoursToDate {
public Date addHoursToJavaUtilDate(Date date, int hours) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();
}
public Date addHoursToDateUsingInstant(Date date, int hours) {
return Date.from(date.toInstant()
.plus(Duration.ofHours(hours)));
}
public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
return localDateTime.plusHours(hours);
}
public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
return localDateTime.minusHours(hours);
}
public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
return zonedDateTime.plusHours(hours);
}
public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { | return zonedDateTime.minusHours(hours);
}
public Instant addHoursToInstant(Instant instant, int hours) {
return instant.plus(hours, ChronoUnit.HOURS);
}
public Instant subtractHoursToInstant(Instant instant, int hours) {
return instant.minus(hours, ChronoUnit.HOURS);
}
public Date addHoursWithApacheCommons(Date date, int hours) {
return DateUtils.addHours(date, hours);
}
} | repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\datetime\AddHoursToDate.java | 1 |
请完成以下Java代码 | public class DeleteTaskCommentCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String commentId;
protected String taskId;
public DeleteTaskCommentCmd(String taskId, String commentId) {
this.taskId = taskId;
this.commentId = commentId;
}
public DeleteTaskCommentCmd(String taskId) {
this.taskId = taskId;
}
@Override
public Object execute(CommandContext commandContext) {
ensureNotNull(BadUserRequestException.class, "taskId", taskId);
TaskEntity task = commandContext.getTaskManager().findTaskById(taskId);
ensureNotNull("No task exists with taskId: " + taskId, "task", task);
checkTaskWork(task, commandContext);
if (commentId != null) {
CommentEntity comment = commandContext.getCommentManager().findCommentByTaskIdAndCommentId(taskId, commentId);
if (comment != null) { | commandContext.getDbEntityManager().delete(comment);
}
} else { // delete all comments
List<Comment> comments = commandContext.getCommentManager().findCommentsByTaskId(taskId);
if (!comments.isEmpty()) {
commandContext.getCommentManager().deleteCommentsByTaskId(taskId);
}
}
commandContext.getOperationLogManager()
.logCommentOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_COMMENT, task,
new PropertyChange("comment", null, null));
task.triggerUpdateEvent();
return null;
}
protected void checkTaskWork(TaskEntity task, CommandContext commandContext) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkTaskWork(task);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteTaskCommentCmd.java | 1 |
请完成以下Java代码 | public Spliterator<List<E>> trySplit()
{
return null;
}
@Override
public long estimateSize()
{
return Long.MAX_VALUE;
}
@Override
public int characteristics()
{
return source.characteristics();
}
private static final class GroupCollector<E>
{
private final Object classifierValue;
private final ImmutableList.Builder<E> items = ImmutableList.builder();
public GroupCollector(final Object classifierValue)
{
this.classifierValue = classifierValue; | }
public boolean isMatchingClassifier(final Object classifierValueToMatch)
{
return Objects.equals(this.classifierValue, classifierValueToMatch);
}
public void collect(final E item)
{
items.add(item);
}
public List<E> finish()
{
return items.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GroupByClassifierSpliterator.java | 1 |
请完成以下Java代码 | 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
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
} | /** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java | 1 |
请完成以下Java代码 | public class Address implements Serializable, Cloneable {
@Override
public Object clone() {
try {
return (Address) super.clone();
} catch (CloneNotSupportedException e) {
return new Address(this.street, this.getCity(), this.getCountry());
}
}
private static final long serialVersionUID = 1740913841244949416L;
private String street;
private String city;
private String country;
public Address(Address that) {
this(that.getStreet(), that.getCity(), that.getCountry());
}
public Address(String street, String city, String country) {
this.street = street;
this.city = city;
this.country = country;
}
public Address() { | }
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public void setStreet(String street) {
this.street = street;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns\src\main\java\com\baeldung\deepcopy\Address.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void initialize() {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
for (Location location : this.locations) {
if (!location.isClassPath()) {
continue;
}
Resource root = resolver.getResource(location.getDescriptor());
if (!root.exists()) {
if (this.failOnMissingLocations) {
throw new FlywayException("Location " + location.getDescriptor() + " doesn't exist");
}
continue;
}
Resource[] resources = getResources(resolver, location, root);
for (Resource resource : resources) {
this.locatedResources.add(new LocatedResource(resource, location));
}
} | }
private Resource[] getResources(PathMatchingResourcePatternResolver resolver, Location location, Resource root) {
try {
return resolver.getResources(root.getURI() + "/*");
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to list resources for " + location.getDescriptor(), ex);
}
}
private record LocatedResource(Resource resource, Location location) {
}
} | repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\NativeImageResourceProvider.java | 2 |
请完成以下Java代码 | private void collect(@NonNull final CacheInvalidateRequest request)
{
logger.trace("Collecting request on `{}`: {}", name, request);
final TableRecordReference rootDocumentRef = request.getRootRecordOrNull();
if (rootDocumentRef == null)
{
return;
}
//
// If we are still collecting document, we will collect this event.
// If not, we will have to fire this event directly.
final DocumentToInvalidateMap documentsToCollect = this.documents;
final DocumentToInvalidateMap documents;
final boolean autoflush;
if (documentsToCollect != null)
{
documents = documentsToCollect;
autoflush = false;
}
else
{
// Basically this shall not happen, but for some reason it's happening.
// So, for that case, instead of just ignoring event, better to fire it directly.
documents = new DocumentToInvalidateMap();
autoflush = true;
}
//
final DocumentToInvalidate documentToInvalidate = documents.getDocumentToInvalidate(rootDocumentRef);
final String childTableName = request.getChildTableName();
if (childTableName == null)
{
documentToInvalidate.invalidateDocument();
}
else if (request.isAllRecords())
{
documentToInvalidate.invalidateAllIncludedDocuments(childTableName);
// NOTE: as a workaround to solve the problem of https://github.com/metasfresh/metasfresh-webui-api/issues/851,
// we are invalidating the whole root document to make sure that in case there were any virtual columns on header,
// those get refreshed too.
documentToInvalidate.invalidateDocument();
}
else
{
final int childRecordId = request.getChildRecordId();
documentToInvalidate.addIncludedDocument(childTableName, childRecordId);
}
// | if (autoflush && !documents.isEmpty())
{
logger.trace("Auto-flushing {} collected requests for on `{}`", documents.size(), name);
DocumentCacheInvalidationDispatcher.this.resetAsync(documents);
}
}
public void resetAsync()
{
final DocumentToInvalidateMap documents = this.documents;
this.documents = null; // just to prevent adding more events
if (documents == null)
{
// it was already executed
return;
}
logger.trace("Flushing {} collected requests for on `{}`", documents.size(), name);
if (documents.isEmpty())
{
return;
}
DocumentCacheInvalidationDispatcher.this.resetAsync(documents);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentCacheInvalidationDispatcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private UserId extractUserId(final MultiValueMap<String, String> queryParams)
{
return StringUtils.trimBlankToOptional(queryParams.getFirst(TOPIC_PARAM_userToken))
.map(userAuthTokenService::getByToken)
.map(UserAuthToken::getUserId)
.orElseThrow(() -> new AdempiereException("Parameter " + TOPIC_PARAM_userToken + " is mandatory"));
}
@NonNull
private static MobileApplicationId extractApplicationId(final MultiValueMap<String, String> queryParams)
{
return StringUtils.trimBlankToOptional(queryParams.getFirst(TOPIC_PARAM_applicationId))
.map(MobileApplicationId::ofString)
.orElseThrow(() -> new AdempiereException("Parameter " + TOPIC_PARAM_applicationId + " is mandatory"));
}
private static ImmutableSet<WorkflowLaunchersFacetId> extractFacetIdsFromQueryParams(final MultiValueMap<String, String> queryParams) throws IOException
{
String facetIdsStr = StringUtils.trimBlankToNull(queryParams.getFirst(TOPIC_PARAM_facetIds)); | if (facetIdsStr == null)
{
return ImmutableSet.of();
}
facetIdsStr = URLDecoder.decode(facetIdsStr, "UTF-8");
return Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(facetIdsStr)
.stream()
.map(WorkflowLaunchersFacetId::fromJson)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\ws\WorkflowLaunchersWebSocketProducerFactory.java | 2 |
请完成以下Java代码 | public List<List<String>> getX_()
{
return x_;
}
public void setX_(List<List<String>> x_)
{
this.x_ = x_;
}
public List<List<Node>> getNode_()
{
return node_;
}
public void setNode_(List<List<Node>> node_)
{
this.node_ = node_;
}
public List<Integer> getAnswer_()
{
return answer_;
}
public void setAnswer_(List<Integer> answer_)
{
this.answer_ = answer_;
}
public List<Integer> getResult_()
{
return result_;
}
public void setResult_(List<Integer> result_)
{
this.result_ = result_;
}
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
return;
}
TaggerImpl tagger = new TaggerImpl(Mode.TEST);
InputStream stream = null;
try
{
stream = IOUtil.newInputStream(args[0]);
}
catch (IOException e)
{
System.err.printf("model not exits for %s", args[0]);
return; | }
if (stream != null && !tagger.open(stream, 2, 0, 1.0))
{
System.err.println("open error");
return;
}
System.out.println("Done reading model");
if (args.length >= 2)
{
InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
while (true)
{
ReadStatus status = tagger.read(br);
if (ReadStatus.ERROR == status)
{
System.err.println("read error");
return;
}
else if (ReadStatus.EOF == status)
{
break;
}
if (tagger.getX_().isEmpty())
{
break;
}
if (!tagger.parse())
{
System.err.println("parse error");
return;
}
System.out.print(tagger.toString());
}
br.close();
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java | 1 |
请完成以下Java代码 | public void setExternalId (final @Nullable java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setM_Forecast_ID (final int M_Forecast_ID)
{
if (M_Forecast_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, M_Forecast_ID);
}
@Override
public int getM_Forecast_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Forecast_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
} | @Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java | 1 |
请完成以下Java代码 | public void setPassWord(String passWord) {
this.passWord = passWord;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getRegTime() {
return regTime;
} | public void setRegTime(Date regTime) {
this.regTime = regTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", age=" + age +
", regTime=" + regTime +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-8 课:Spring Data Jpa 和 Thymeleaf 综合实践\spring-boot-Jpa-thymeleaf\src\main\java\com\neo\model\User.java | 1 |
请完成以下Java代码 | private static ChatMessage.ResponseMessage runToolLoop(
ChatCompletionServices client,
FunctionExecutor functionExecutor,
List<ChatMessage> history
) {
while (true) {
ChatRequest chatRequest = ChatRequest.builder()
.model(Client.CHAT_MODEL)
.messages(history)
.tools(functionExecutor.getToolFunctions())
.build();
CompletableFuture<Chat> chatFuture =
client.chatCompletions().create(chatRequest);
Chat chat = chatFuture.join();
ChatMessage.ResponseMessage message = chat.firstMessage();
List<ToolCall> toolCalls = message.getToolCalls();
if (toolCalls == null || toolCalls.isEmpty()) {
return message;
}
List<ToolCall> sanitizedToolCalls = sanitizeToolCalls(toolCalls);
history.add(AssistantMessage.builder()
.content("")
.toolCalls(sanitizedToolCalls)
.build());
for (ToolCall toolCall : sanitizedToolCalls) {
String id = toolCall.getId();
Client.LOGGER.log(Level.INFO,
"Tool call: {0} with args: {1} (id: {2})",
toolCall.getFunction().getName(),
toolCall.getFunction().getArguments(),
id
);
Object result = functionExecutor.execute(toolCall.getFunction());
String payload = toJson(result);
history.add(ToolMessage.of(payload, id));
}
}
} | private static List<ToolCall> sanitizeToolCalls(List<ToolCall> toolCalls) {
List<ToolCall> sanitized = new ArrayList<>(toolCalls.size());
int counter = 0;
for (ToolCall toolCall : toolCalls) {
counter++;
String id = toolCall.getId();
if (id == null || id.isBlank()) {
id = toolCall.getFunction().getName() + "-" + counter;
}
sanitized.add(new ToolCall(
toolCall.getIndex(),
id,
toolCall.getType(),
toolCall.getFunction()
));
}
return sanitized;
}
private static String toJson(Object value) {
try {
return MAPPER.writeValueAsString(value);
} catch (Exception ex) {
Client.LOGGER.log(Level.INFO,
"Falling back to toString() for tool output: {0}",
ex.getMessage()
);
return String.valueOf(value);
}
}
} | repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HandlingToolCallsInTheChatLoop.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeployHistoryServiceImpl implements DeployHistoryService {
private final DeployHistoryRepository deployhistoryRepository;
private final DeployHistoryMapper deployhistoryMapper;
@Override
public PageResult<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){
Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(deployhistoryMapper::toDto));
}
@Override
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){
return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public DeployHistoryDto findById(String id) {
DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new);
ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id);
return deployhistoryMapper.toDto(deployhistory);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DeployHistory resources) {
resources.setId(IdUtil.simpleUUID());
deployhistoryRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
deployhistoryRepository.deleteById(id);
}
} | @Override
public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DeployHistoryDto deployHistoryDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("部署编号", deployHistoryDto.getDeployId());
map.put("应用名称", deployHistoryDto.getAppName());
map.put("部署IP", deployHistoryDto.getIp());
map.put("部署时间", deployHistoryDto.getDeployDate());
map.put("部署人员", deployHistoryDto.getDeployUser());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DeployHistoryServiceImpl.java | 2 |
请完成以下Java代码 | private int addArchivePartToPDF0(@NonNull final PrintingData data, @NonNull final PrintingSegment segment) throws IOException
{
if (!data.hasData())
{
logger.info("PrintingData {} does not contain any data; -> returning", data);
return 0;
}
logger.debug("Adding data={}; segment={}", data, segment);
int pagesAdded = 0;
for (int i = 0; i < segment.getCopies(); i++)
{
final PdfReader reader = new PdfReader(data.getData());
final int archivePageNums = reader.getNumberOfPages();
int pageFrom = segment.getPageFrom();
if (pageFrom <= 0)
{
// First page is 1 - See com.lowagie.text.pdf.PdfWriter.getImportedPage
pageFrom = 1;
}
int pageTo = segment.getPageTo();
if (pageTo > archivePageNums)
{
// shall not happen at this point
logger.debug("Page to ({}) is greater then number of pages. Considering number of pages: {}", new Object[] { pageTo, archivePageNums });
pageTo = archivePageNums;
}
if (pageFrom > pageTo)
{
// shall not happen at this point
logger.warn("Page from ({}) is greater then Page to ({}). Skipping: {}", pageFrom, pageTo, segment);
return 0;
}
logger.debug("PageFrom={}, PageTo={}, NumberOfPages={}", pageFrom, pageTo, archivePageNums); | for (int page = pageFrom; page <= pageTo; page++)
{
try
{
pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
}
catch (final BadPdfFormatException e)
{
throw new AdempiereException("@Invalid@ " + segment + " (Page: " + page + ")", e);
}
pagesAdded++;
}
pdfCopy.freeReader(reader);
reader.close();
}
logger.debug("Added {} pages", pagesAdded);
return pagesAdded;
}
@Override
public void close()
{
document.close();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFWriter.java | 1 |
请完成以下Java代码 | public void startWithHasLength(String key) {
Assert.hasLength(key, "key must not be null and must not the empty");
// ...
}
public void startWithHasText(String key) {
Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character");
// ...
}
public void startWithNotContain(String key) {
Assert.doesNotContain(key, "123", "key must not contain 123");
// ...
}
public void repair(Collection<String> repairParts) {
Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty");
// ...
}
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(repairParts, "map of repairParts mustn't be empty");
// ...
}
public void repair(String[] repairParts) {
Assert.notEmpty(repairParts, "array of repairParts must not be empty");
// ...
}
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(repairParts, "array of repairParts must not contain null elements");
// ...
}
public static void main(String[] args) {
Car car = new Car();
car.drive(50); | car.stop();
car.fuel();
car.сhangeOil("oil");
CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
} | repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java | 1 |
请完成以下Java代码 | public Builder setClientTree(final boolean clientTree)
{
this.clientTree = clientTree;
return this;
}
public boolean isClientTree()
{
return clientTree;
}
public Builder setAllNodes(final boolean allNodes)
{
this.allNodes = allNodes;
return this;
}
public boolean isAllNodes()
{
return allNodes; | }
public Builder setLanguage(final String adLanguage)
{
this.adLanguage = adLanguage;
return this;
}
private String getAD_Language()
{
if (adLanguage == null)
{
return Env.getADLanguageOrBaseLanguage(getCtx());
}
return adLanguage;
}
}
} // MTree | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree.java | 1 |
请完成以下Java代码 | public class CoreLogger extends ProcessEngineLogger {
public void debugMappingValueFromOuterScopeToInnerScope(Object value, AbstractVariableScope outerScope, String name, AbstractVariableScope innerScope) {
logDebug(
"001",
"Mapping value '{} from outer scope '{}' to variable '{}' in inner scope '{}'.",
value, outerScope, name, innerScope);
}
public void debugMappingValuefromInnerScopeToOuterScope(Object value, AbstractVariableScope innerScope, String name, AbstractVariableScope outerScope) {
logDebug(
"002",
"Mapping value '{}' from inner scope '{}' to variable '{}' in outer scope '{}'.",
value, innerScope, name, outerScope);
}
public void debugPerformingAtomicOperation(CoreAtomicOperation<?> atomicOperation, CoreExecution e) {
logDebug(
"003",
"Performing atomic operation {} on {}", atomicOperation, e);
}
public ProcessEngineException duplicateVariableInstanceException(CoreVariableInstance variableInstance) {
return new ProcessEngineException(exceptionMessage(
"004",
"Cannot add variable instance with name {}. Variable already exists",
variableInstance.getName()
));
} | // We left out id 005!
// please skip it unless you backport it to all maintained versions to avoid inconsistencies
public ProcessEngineException transientVariableException(String variableName) {
return new ProcessEngineException(exceptionMessage(
"006",
"Cannot set transient variable with name {} to non-transient variable and vice versa.",
variableName
));
}
public ProcessEngineException javaSerializationProhibitedException(String variableName) {
return new ProcessEngineException(exceptionMessage("007",
MessageFormat.format(ERROR_MSG, variableName)));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\CoreLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OnEnabledFilter extends OnEnabledComponent<GatewayFilterFactory<?>> {
@Override
protected String normalizeComponentName(Class<? extends GatewayFilterFactory<?>> filterClass) {
if (SpringCloudCircuitBreakerFilterFactory.class.isAssignableFrom(filterClass)) {
return "filter."
+ NameUtils.normalizeToCanonicalPropertyFormat(SpringCloudCircuitBreakerFilterFactory.NAME);
}
else {
return "filter." + NameUtils.normalizeFilterFactoryNameAsProperty(filterClass);
}
}
@Override
protected Class<?> annotationClass() {
return ConditionalOnEnabledFilter.class;
} | @Override
protected Class<? extends GatewayFilterFactory<?>> defaultValueClass() {
return DefaultValue.class;
}
static class DefaultValue implements GatewayFilterFactory<Object> {
@Override
public GatewayFilter apply(Object config) {
throw new UnsupportedOperationException("class DefaultValue is never meant to be intantiated");
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\conditional\OnEnabledFilter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AppContextRefreshedEventPropertiesPrinter {
private static final Logger LOGGER = LoggerFactory.getLogger(AppContextRefreshedEventPropertiesPrinter.class);
@EventListener
public void handleContextRefreshed(ContextRefreshedEvent event) {
printAllActiveProperties((ConfigurableEnvironment) event.getApplicationContext().getEnvironment());
printAllApplicationProperties((ConfigurableEnvironment) event.getApplicationContext().getEnvironment());
}
private void printAllActiveProperties(ConfigurableEnvironment env) {
LOGGER.info("************************* ALL PROPERTIES(EVENT) ******************************");
env.getPropertySources()
.stream()
.filter(ps -> ps instanceof MapPropertySource)
.map(ps -> ((MapPropertySource) ps).getSource().keySet())
.flatMap(Collection::stream)
.distinct()
.sorted()
.forEach(key -> LOGGER.info("{}={}", key, env.getProperty(key)));
LOGGER.info("******************************************************************************");
} | private void printAllApplicationProperties(ConfigurableEnvironment env) {
LOGGER.info("************************* APP PROPERTIES(EVENT) ******************************");
env.getPropertySources()
.stream()
.filter(ps -> ps instanceof MapPropertySource && ps.getName().contains("application.properties"))
.map(ps -> ((MapPropertySource) ps).getSource().keySet())
.flatMap(Collection::stream)
.distinct()
.sorted()
.forEach(key -> LOGGER.info("{}={}", key, env.getProperty(key)));
LOGGER.info("******************************************************************************");
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\log\AppContextRefreshedEventPropertiesPrinter.java | 2 |
请完成以下Java代码 | public MandateRelatedInformationSDD getMndtRltdInf() {
return mndtRltdInf;
}
/**
* Sets the value of the mndtRltdInf property.
*
* @param value
* allowed object is
* {@link MandateRelatedInformationSDD }
*
*/
public void setMndtRltdInf(MandateRelatedInformationSDD value) {
this.mndtRltdInf = value;
}
/**
* Gets the value of the cdtrSchmeId property.
*
* @return | * possible object is
* {@link PartyIdentificationSEPA3 }
*
*/
public PartyIdentificationSEPA3 getCdtrSchmeId() {
return cdtrSchmeId;
}
/**
* Sets the value of the cdtrSchmeId property.
*
* @param value
* allowed object is
* {@link PartyIdentificationSEPA3 }
*
*/
public void setCdtrSchmeId(PartyIdentificationSEPA3 value) {
this.cdtrSchmeId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\DirectDebitTransactionSDD.java | 1 |
请完成以下Java代码 | public void setOutputName(String outputName) {
this.outputName = outputName;
}
public TypedValue getValue() {
return value;
}
public void setValue(TypedValue value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DmnEvaluatedOutputImpl that = (DmnEvaluatedOutputImpl) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (outputName != null ? !outputName.equals(that.outputName) : that.outputName != null) return false; | return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (outputName != null ? outputName.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DmnEvaluatedOutputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", outputName='" + outputName + '\'' +
", value=" + value +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedOutputImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class Saml2RequestMatcher implements RequestMatcher {
private final SecurityContextHolderStrategy securityContextHolderStrategy;
Saml2RequestMatcher(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
@Override
public boolean matches(HttpServletRequest request) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
return false;
}
if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal) {
return true;
}
if (authentication.getCredentials() instanceof Saml2ResponseAssertionAccessor) { | return true;
}
return authentication instanceof Saml2Authentication;
}
}
private static class Saml2RelyingPartyInitiatedLogoutFilter extends LogoutFilter {
Saml2RelyingPartyInitiatedLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
super(logoutSuccessHandler, handlers);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2LogoutConfigurer.java | 2 |
请完成以下Java代码 | private void sizeIt()
{
// Frame
m_frame.pack();
// Dimension size = m_frame.getPreferredSize();
// size.width = WINDOW_WIDTH;
// m_frame.setSize(size);
} // size
/**
* Dispose
*/
@Override
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
removeAll();
} // dispose
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
/** Logger */
private static Logger log = LogManager.getLogger(ViewPI.class);
/** Confirmation Panel */
private ConfirmPanel confirmPanel = ConfirmPanel.newWithOK();
/**
* Init Panel
*/
private void initPanel()
{
BoxLayout layout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
MGoal[] goals = MGoal.getGoals(Env.getCtx());
for (int i = 0; i < goals.length; i++) | {
PerformanceIndicator pi = new PerformanceIndicator(goals[i]);
pi.addActionListener(this);
add (pi);
}
} // initPanel
/**
* Action Listener for Drill Down
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
dispose();
else if (e.getSource() instanceof PerformanceIndicator)
{
PerformanceIndicator pi = (PerformanceIndicator)e.getSource();
log.info(pi.getName());
MGoal goal = pi.getGoal();
if (goal.getMeasure() != null)
new PerformanceDetail(goal);
}
} // actionPerformed
} // ViewPI | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\ViewPI.java | 1 |
请完成以下Java代码 | public Set<CostElementId> getActiveCostElementIds()
{
return getIndexedCostElements()
.stream()
.map(CostElement::getId)
.collect(ImmutableSet.toImmutableSet());
}
private Stream<CostElement> streamByCostingMethod(@NonNull final CostingMethod costingMethod)
{
final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()));
return getIndexedCostElements()
.streamByClientId(clientId)
.filter(ce -> ce.getCostingMethod() == costingMethod);
}
private static class IndexedCostElements
{
private final ImmutableMap<CostElementId, CostElement> costElementsById;
private IndexedCostElements(final Collection<CostElement> costElements)
{
costElementsById = Maps.uniqueIndex(costElements, CostElement::getId);
}
public Optional<CostElement> getById(final CostElementId id)
{
return Optional.ofNullable(costElementsById.get(id)); | }
public Stream<CostElement> streamByClientId(@NonNull final ClientId clientId)
{
return stream().filter(ce -> ClientId.equals(ce.getClientId(), clientId));
}
public Stream<CostElement> streamByClientIdAndCostingMethod(@NonNull final ClientId clientId, @NonNull final CostingMethod costingMethod)
{
return streamByClientId(clientId).filter(ce -> costingMethod.equals(ce.getCostingMethod()));
}
public Stream<CostElement> stream()
{
return costElementsById.values().stream();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostElementRepository.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set PA_DashboardContent_ID.
@param PA_DashboardContent_ID PA_DashboardContent_ID */
public void setPA_DashboardContent_ID (int PA_DashboardContent_ID)
{
if (PA_DashboardContent_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID));
}
/** Get PA_DashboardContent_ID.
@return PA_DashboardContent_ID */
public int getPA_DashboardContent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Goal getPA_Goal() throws RuntimeException
{
return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name)
.getPO(getPA_Goal_ID(), get_TrxName()); }
/** Set Goal.
@param PA_Goal_ID
Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null); | else
set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set ZUL File Path.
@param ZulFilePath
Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath)
{
set_Value (COLUMNNAME_ZulFilePath, ZulFilePath);
}
/** Get ZUL File Path.
@return Absolute path to zul file
*/
public String getZulFilePath ()
{
return (String)get_Value(COLUMNNAME_ZulFilePath);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java | 1 |
请完成以下Java代码 | public int size() {
return historicProcessInstanceIds.size() + historicDecisionInstanceIds.size() + historicCaseInstanceIds.size() + historicBatchIds.size() + taskMetricIds.size();
}
public void performCleanup() {
CommandContext commandContext = Context.getCommandContext();
HistoryCleanupHelper.prepareNextBatch(this, commandContext);
if (size() > 0) {
if (historicProcessInstanceIds.size() > 0) {
commandContext.getHistoricProcessInstanceManager().deleteHistoricProcessInstanceByIds(historicProcessInstanceIds);
}
if (historicDecisionInstanceIds.size() > 0) {
commandContext.getHistoricDecisionInstanceManager().deleteHistoricDecisionInstanceByIds(historicDecisionInstanceIds);
}
if (historicCaseInstanceIds.size() > 0) {
commandContext.getHistoricCaseInstanceManager().deleteHistoricCaseInstancesByIds(historicCaseInstanceIds);
}
if (historicBatchIds.size() > 0) {
commandContext.getHistoricBatchManager().deleteHistoricBatchesByIds(historicBatchIds);
}
if (taskMetricIds.size() > 0) {
commandContext.getMeterLogManager().deleteTaskMetricsById(taskMetricIds);
}
}
}
@Override
protected Map<String, Long> reportMetrics() {
Map<String, Long> reports = new HashMap<>();
if (historicProcessInstanceIds.size() > 0) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES, (long) historicProcessInstanceIds.size());
}
if (historicDecisionInstanceIds.size() > 0) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES, (long) historicDecisionInstanceIds.size());
}
if (historicCaseInstanceIds.size() > 0) { | reports.put(Metrics.HISTORY_CLEANUP_REMOVED_CASE_INSTANCES, (long) historicCaseInstanceIds.size());
}
if (historicBatchIds.size() > 0) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS, (long) historicBatchIds.size());
}
if (taskMetricIds.size() > 0) {
reports.put(Metrics.HISTORY_CLEANUP_REMOVED_TASK_METRICS, (long) taskMetricIds.size());
}
return reports;
}
@Override
boolean shouldRescheduleNow() {
return size() >= getBatchSizeThreshold();
}
public Integer getBatchSizeThreshold() {
return Context
.getProcessEngineConfiguration()
.getHistoryCleanupBatchThreshold();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupBatch.java | 1 |
请完成以下Java代码 | private String getSql()
{
return getProcessInfo().getSQLStatement().orElseThrow(() -> new FillMandatoryException("SQLStatement"));
}
private Evaluatee getEvalContext()
{
final ArrayList<Evaluatee> contexts = new ArrayList<>();
//
// 1: Add process parameters
contexts.add(Evaluatees.ofRangeAwareParams(getParameterAsIParams()));
//
// 2: underlying record
final String recordTableName = getTableName();
final int recordId = getRecord_ID(); | if (recordTableName != null && recordId > 0)
{
final TableRecordReference recordRef = TableRecordReference.of(recordTableName, recordId);
final Evaluatee evalCtx = Evaluatees.ofTableRecordReference(recordRef);
if (evalCtx != null)
{
contexts.add(evalCtx);
}
}
//
// 3: global context
contexts.add(Evaluatees.ofCtx(getCtx()));
return Evaluatees.compose(contexts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\process\ExportToSpreadsheetProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void start(StartContext context) throws StartException {
provider.accept(this);
}
@Override
public void stop(StopContext context) {
provider.accept(null);
}
@Override
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
@Override
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunningWork(runnable);
} else {
return scheduleShortRunningWork(runnable);
}
}
protected boolean scheduleShortRunningWork(Runnable runnable) {
EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
try {
EnhancedQueueExecutor.execute(runnable);
return true;
} catch (Exception e) {
// we must be able to schedule this
log.log(Level.WARNING, "Cannot schedule long running work.", e);
} | return false;
}
protected boolean scheduleLongRunningWork(Runnable runnable) {
final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
boolean rejected = false;
try {
EnhancedQueueExecutor.execute(runnable);
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding
if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java | 2 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
ensureNotEmpty(BadUserRequestException.class,"variableInstanceId", variableInstanceId);
HistoricVariableInstanceEntity variable = commandContext.getHistoricVariableInstanceManager().findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
ensureNotNull(NotFoundException.class, "No historic variable instance found with id: " + variableInstanceId, "variable", variable);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricVariableInstance(variable);
}
commandContext
.getHistoricDetailManager()
.deleteHistoricDetailsByVariableInstanceId(variableInstanceId);
commandContext
.getHistoricVariableInstanceManager()
.deleteHistoricVariableInstanceByVariableInstanceId(variableInstanceId); | // create user operation log
ResourceDefinitionEntity<?> definition = null;
try {
if (variable.getProcessDefinitionId() != null) {
definition = commandContext.getProcessEngineConfiguration().getDeploymentCache().findDeployedProcessDefinitionById(variable.getProcessDefinitionId());
} else if (variable.getCaseDefinitionId() != null) {
definition = commandContext.getProcessEngineConfiguration().getDeploymentCache().findDeployedCaseDefinitionById(variable.getCaseDefinitionId());
}
} catch (NotFoundException e) {
// definition has been deleted already
}
commandContext.getOperationLogManager().logHistoricVariableOperation(
UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, variable, definition, new PropertyChange("name", null, variable.getName()));
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricVariableInstanceCmd.java | 1 |
请完成以下Java代码 | public class IndentedStringBuilder
{
private final StringBuilder sb;
// Config Parameters
private String indentToken = "\t";
private String newlineToken = "\n";
// State
private String _linePrefix = null;
private int indent = 0;
public IndentedStringBuilder(final StringBuilder sb)
{
super();
Check.assumeNotNull(sb, "sb not null");
this.sb = sb;
}
public IndentedStringBuilder()
{
this(new StringBuilder());
}
public String getIndentToken()
{
return indentToken;
}
public void setIndentToken(String indent)
{
Check.assumeNotNull(indent, "indent not null");
this.indentToken = indent;
this._linePrefix = null; // reset
}
public String getNewlineToken()
{
return newlineToken;
}
public void setNewlineToken(String newline)
{
Check.assumeNotNull(newline, "newline not null");
this.newlineToken = newline;
}
public int getIndent()
{
return indent;
}
public IndentedStringBuilder incrementIndent()
{
return setIndent(indent + 1);
}
public IndentedStringBuilder decrementIndent()
{
return setIndent(indent - 1);
}
private IndentedStringBuilder setIndent(int indent)
{
Check.assume(indent >= 0, "indent >= 0");
this.indent = indent; | this._linePrefix = null; // reset
return this;
}
private final String getLinePrefix()
{
if (_linePrefix == null)
{
final int indent = getIndent();
final String token = getIndentToken();
final StringBuilder prefix = new StringBuilder();
for (int i = 1; i <= indent; i++)
{
prefix.append(token);
}
_linePrefix = prefix.toString();
}
return _linePrefix;
}
public StringBuilder getInnerStringBuilder()
{
return sb;
}
@Override
public String toString()
{
return sb.toString();
}
public IndentedStringBuilder appendLine(final Object obj)
{
final String linePrefix = getLinePrefix();
sb.append(linePrefix).append(obj).append(getNewlineToken());
return this;
}
public IndentedStringBuilder append(final Object obj)
{
sb.append(obj);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\IndentedStringBuilder.java | 1 |
请完成以下Java代码 | public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
/**
* ProductLookup AD_Reference_ID=541499
* Reference name: _ProductLookup
*/ | public static final int PRODUCTLOOKUP_AD_Reference_ID=541499;
/** Product Id = ProductId */
public static final String PRODUCTLOOKUP_ProductId = "ProductId";
/** Product Number = ProductNumber */
public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber";
@Override
public void setProductLookup (final java.lang.String ProductLookup)
{
set_Value (COLUMNNAME_ProductLookup, ProductLookup);
}
@Override
public java.lang.String getProductLookup()
{
return get_ValueAsString(COLUMNNAME_ProductLookup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java | 1 |
请完成以下Java代码 | private List<String> resolveAll(Supplier<String> platformProvider, String... values) {
if (ObjectUtils.isEmpty(values)) {
return Collections.emptyList();
}
List<String> resolved = new ArrayList<>(values.length);
String platform = null;
for (String value : values) {
if (StringUtils.hasLength(value)) {
if (value.contains(this.placeholder)) {
platform = (platform != null) ? platform : platformProvider.get();
value = value.replace(this.placeholder, platform);
}
}
resolved.add(value);
}
return Collections.unmodifiableList(resolved);
}
private String determinePlatform(DataSource dataSource) { | DatabaseDriver databaseDriver = getDatabaseDriver(dataSource);
Assert.state(databaseDriver != DatabaseDriver.UNKNOWN, "Unable to detect database type");
return this.driverMappings.getOrDefault(databaseDriver, databaseDriver.getId());
}
DatabaseDriver getDatabaseDriver(DataSource dataSource) {
try {
String productName = JdbcUtils.commonDatabaseName(
JdbcUtils.extractDatabaseMetaData(dataSource, DatabaseMetaData::getDatabaseProductName));
return DatabaseDriver.fromProductName(productName);
}
catch (Exception ex) {
throw new IllegalStateException("Failed to determine DatabaseDriver", ex);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\PlatformPlaceholderDatabaseDriverResolver.java | 1 |
请完成以下Java代码 | private Integer find(Integer node) {
Integer parent = nodes.get(node).getParentNode();
if (parent.equals(node)) {
return node;
} else {
return find(parent);
}
}
private Integer pathCompressionFind(Integer node) {
DisjointSetInfo setInfo = nodes.get(node);
Integer parent = setInfo.getParentNode();
if (parent.equals(node)) {
return node;
} else {
Integer parentNode = find(parent);
setInfo.setParentNode(parentNode);
return parentNode;
}
}
private void union(Integer rootU, Integer rootV) {
DisjointSetInfo setInfoU = nodes.get(rootU);
setInfoU.setParentNode(rootV);
} | private void unionByRank(int rootU, int rootV) {
DisjointSetInfo setInfoU = nodes.get(rootU);
DisjointSetInfo setInfoV = nodes.get(rootV);
int rankU = setInfoU.getRank();
int rankV = setInfoV.getRank();
if (rankU < rankV) {
setInfoU.setParentNode(rootV);
} else {
setInfoV.setParentNode(rootU);
if (rankU == rankV) {
setInfoU.setRank(rankU + 1);
}
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\kruskal\CycleDetector.java | 1 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities != null ? authorities : Collections.emptyList();
}
@Override
public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true; | }
@Override
public boolean isEnabled() {
return Boolean.TRUE.equals(active);
}
@InstanceName
@DependsOnProperties({"firstName", "lastName", "username"})
public String getDisplayName() {
return String.format("%s %s [%s]", (firstName != null ? firstName : ""),
(lastName != null ? lastName : ""), username).trim();
}
@Override
public String getTimeZoneId() {
return timeZoneId;
}
public void setTimeZoneId(final String timeZoneId) {
this.timeZoneId = timeZoneId;
}
} | repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java | 1 |
请完成以下Java代码 | public Optional<TableReferenceInfo> loadTableReferenceInfo(final int adReferenceId)
{
final String sql = "SELECT"
+ " t.TableName, t.EntityType" // 1,2
+ ", ck.AD_Reference_ID" // 3
+ ", ck.IsKey" // 4
+ ", ck.AD_Reference_Value_ID as Key_Reference_Value_ID" // 5
+ " FROM AD_Ref_Table rt"
+ " INNER JOIN AD_Table t ON (t.AD_Table_ID=rt.AD_Table_ID)"
+ " INNER JOIN AD_Column ck ON (ck.AD_Table_ID=rt.AD_Table_ID AND ck.AD_Column_ID=rt.AD_Key)"
+ " WHERE rt.AD_Reference_ID=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
pstmt.setInt(1, adReferenceId);
rs = pstmt.executeQuery();
if (rs.next())
{
final String refTableName = rs.getString(1);
final String entityType = rs.getString(2);
final int refDisplayType = rs.getInt(3);
final boolean refIsKey = "Y".equals(rs.getString("IsKey"));
final int keyReferenceValueId = rs.getInt("Key_Reference_Value_ID"); | final TableReferenceInfo tableReferenceInfo = new TableReferenceInfo(refTableName, refDisplayType, entityType, refIsKey, keyReferenceValueId);
return Optional.of(tableReferenceInfo);
}
}
catch (final SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
}
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\TableAndColumnInfoRepository.java | 1 |
请完成以下Java代码 | public class C_PaySelection_CreatePayments extends JavaProcess implements IProcessPrecondition
{
// services
private final transient IPaySelectionBL paySelectionBL = Services.get(IPaySelectionBL.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if(!context.isSingleSelection())
{
ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final Optional<I_C_PaySelection> paySelection = paySelectionBL.getById(PaySelectionId.ofRepoId(context.getSingleSelectedRecordId()));
if (!paySelection.isPresent() || !paySelection.get().isProcessed()) | {
return ProcessPreconditionsResolution.rejectWithInternalReason("not processed");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final I_C_PaySelection paySelection = Check.assumePresent(paySelectionBL.getById(PaySelectionId.ofRepoId(getRecord_ID())), "should be present");
paySelectionBL.createPayments(paySelection);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\C_PaySelection_CreatePayments.java | 1 |
请完成以下Java代码 | public class CommonUtil {
/**
* 检查某版本是否比现在版本更大些
*
* @param version 某版本
* @param nowVersion 现在使用的版本
* @return 是否版本数更大
*/
public static boolean isNewer(String version, String nowVersion) {
try {
String[] versions = version.split("\\.");
String[] nowVersions = nowVersion.split("\\.");
if (versions.length != nowVersions.length) {
return false;
} | int sum = 0;
for (String v : versions) {
sum += sum * 10 + Integer.valueOf(v);
}
int nowSum = 0;
for (String nv : nowVersions) {
nowSum += nowSum * 10 + Integer.valueOf(nv);
}
return sum > nowSum;
} catch (NumberFormatException e) {
return false;
}
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\common\util\CommonUtil.java | 1 |
请完成以下Java代码 | public int toInt()
{
return intValue;
}
public BigDecimal toBigDecimal()
{
return BigDecimal.valueOf(intValue);
}
@Override
public int compareTo(@NonNull final QtyTU other)
{
return this.intValue - other.intValue;
}
public int compareTo(@NonNull final BigDecimal other)
{
return this.intValue - other.intValueExact();
}
public boolean isGreaterThan(@NonNull final QtyTU other) {return compareTo(other) > 0;}
public boolean isZero() {return intValue == 0;}
public boolean isPositive() {return intValue > 0;}
public boolean isOne() {return intValue == 1;}
public QtyTU add(@NonNull final QtyTU toAdd)
{
if (this.intValue == 0)
{
return toAdd;
}
else if (toAdd.intValue == 0)
{
return this;
}
else
{
return ofInt(this.intValue + toAdd.intValue);
} | }
public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract)
{
if (toSubtract.intValue == 0)
{
return this;
}
else
{
return ofInt(Math.max(this.intValue - toSubtract.intValue, 0));
}
}
public QtyTU min(@NonNull final QtyTU other)
{
return this.intValue <= other.intValue ? this : other;
}
public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal)
{
if (isZero())
{
throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal);
}
else if (isOne())
{
return qtyCUsTotal;
}
else
{
return qtyCUsTotal.divide(toInt());
}
}
public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU)
{
return qtyCUsPerTU.multiply(toInt());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getSearchKey() {
return searchKey;
}
public void setSearchKey(String searchKey) {
this.searchKey = searchKey;
}
@ApiModelProperty(example = "1:24:MP")
public String getSearchKey2() {
return searchKey2;
}
public void setSearchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
}
@ApiModelProperty(example = "1")
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@ApiModelProperty(example = "2")
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@ApiModelProperty(example = "bpmn")
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
} | public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@ApiModelProperty(example = "completed")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchPartResponse.java | 2 |
请完成以下Java代码 | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setProductPriceInStockUOM (final BigDecimal ProductPriceInStockUOM)
{
set_ValueNoCheck (COLUMNNAME_ProductPriceInStockUOM, ProductPriceInStockUOM);
}
@Override
public BigDecimal getProductPriceInStockUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ProductPriceInStockUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom); | }
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_ValueNoCheck (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_purchase_prices_in_stock_uom_plv_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isAutoCompact() {
return this.autoCompact;
}
public void setAutoCompact(boolean autoCompact) {
this.autoCompact = autoCompact;
}
public int getCompactionThreshold() {
return this.compactionThreshold;
}
public void setCompactionThreshold(int compactionThreshold) {
this.compactionThreshold = compactionThreshold;
}
public DirectoryProperties[] getDirectory() {
return this.directoryProperties;
}
public void setDirectory(DirectoryProperties[] directoryProperties) {
this.directoryProperties = directoryProperties;
}
public float getDiskUsageCriticalPercentage() {
return this.diskUsageCriticalPercentage;
}
public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) {
this.diskUsageCriticalPercentage = diskUsageCriticalPercentage;
}
public float getDiskUsageWarningPercentage() {
return this.diskUsageWarningPercentage;
}
public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) {
this.diskUsageWarningPercentage = diskUsageWarningPercentage;
} | public long getMaxOplogSize() {
return this.maxOplogSize;
}
public void setMaxOplogSize(long maxOplogSize) {
this.maxOplogSize = maxOplogSize;
}
public int getQueueSize() {
return this.queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public long getTimeInterval() {
return this.timeInterval;
}
public void setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
}
public int getWriteBufferSize() {
return this.writeBufferSize;
}
public void setWriteBufferSize(int writeBufferSize) {
this.writeBufferSize = writeBufferSize;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserProfile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "address")
private String address;
@Enumerated(EnumType.STRING)
@Column(name = "gender")
private Gender gender;
@Column(name = "birth_of_date")
private LocalDate birthOfDate;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userProfile")
private User user;
public UserProfile() {
}
public UserProfile(String phoneNumber, String address, Gender gender, LocalDate birthOfDate) {
super();
this.phoneNumber = phoneNumber;
this.address = address;
this.gender = gender;
this.birthOfDate = birthOfDate;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
} | public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public LocalDate getBirthOfDate() {
return birthOfDate;
}
public void setBirthOfDate(LocalDate birthOfDate) {
this.birthOfDate = birthOfDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-one-one-mapping\src\main\java\net\alanbinu\springboot\entity\UserProfile.java | 2 |
请完成以下Spring Boot application配置 | server.port=8090
spring.kafka.bootstrap-servers=127.0.0.1:9092
spring.kafka.consumer.group-id=springboot-kafka
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=2000
spring.kafka.listener.concurrency= 1
spring.kafka.consumer.max-poll-record | s=50
spring.kafka.consumer.max-poll-interval-ms=4000
# topic
log.statistical.kafka.topic=nginx_log
logging.file=./logs/springboot-kafka.log | repos\springBoot-master\springboot-kafka\src\main\resources\local\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractService<T> implements Service<T> {
@Autowired
protected Mapper<T> mapper;
private Class<T> modelClass; // 当前泛型真实类型的Class
public AbstractService() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
public void save(T model) {
mapper.insertSelective(model);
}
public void save(List<T> models) {
mapper.insertList(models);
}
public void deleteById(Integer id) {
mapper.deleteByPrimaryKey(id);
}
public void deleteByIds(String ids) {
mapper.deleteByIds(ids);
}
public void update(T model) {
mapper.updateByPrimaryKeySelective(model);
}
public T findById(Integer id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public T findBy(String fieldName, Object value) throws TooManyResultsException {
try {
T model = modelClass.newInstance(); | Field field = modelClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(model, value);
return mapper.selectOne(model);
} catch (ReflectiveOperationException e) {
throw new ServiceException(e.getMessage(), e);
}
}
public List<T> findByIds(String ids) {
return mapper.selectByIds(ids);
}
public List<T> findByCondition(Condition condition) {
return mapper.selectByCondition(condition);
}
public List<T> findAll() {
return mapper.selectAll();
}
} | repos\spring-boot-api-project-seed-master\src\main\java\com\company\project\core\AbstractService.java | 2 |
请完成以下Java代码 | public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
return getWrappedResolver().getFeatureDescriptors(wrapContext(context), base);
}
@Override
public Class< ? > getType(ELContext context, Object base, Object property) {
return getWrappedResolver().getType(wrapContext(context), base, property);
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
//we need to resolve a bean only for the first "member" of expression, e.g. bean.property1.property2
if (base == null) {
Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager());
if (result != null) {
context.setPropertyResolved(true);
}
return result;
} else {
return null;
} | }
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return getWrappedResolver().isReadOnly(wrapContext(context), base, property);
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
getWrappedResolver().setValue(wrapContext(context), base, property, value);
}
@Override
public Object invoke(ELContext context, Object base, Object method, java.lang.Class< ? >[] paramTypes, Object[] params) {
return getWrappedResolver().invoke(wrapContext(context), base, method, paramTypes, params);
}
protected javax.el.ELContext wrapContext(ELContext context) {
return new ElContextDelegate(context, getWrappedResolver());
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\CdiResolver.java | 1 |
请完成以下Java代码 | public PrinterHWList createPrinterHW()
{
final List<PrinterHW> printerHWs = new ArrayList<>();
for (final PrintService printService : getPrintServices())
{
final PrinterHW printerHW = new PrinterHW();
printerHW.setName(printService.getName());
final List<PrinterHWMediaSize> printerHWMediaSizes = new ArrayList<>();
printerHW.setPrinterHWMediaSizes(printerHWMediaSizes);
final List<PrinterHWMediaTray> printerHWMediaTrays = new ArrayList<>();
printerHW.setPrinterHWMediaTrays(printerHWMediaTrays);
// 04005: detect the default media tray
final MediaTray defaultMediaTray = (MediaTray)printService.getDefaultAttributeValue(MediaTray.class);
final Media[] medias = (Media[])printService.getSupportedAttributeValues(Media.class, null, null); // flavor=null, attributes=null
for (final Media media : medias)
{
if (media instanceof MediaSizeName)
{
final String name = media.toString();
// final MediaSizeName mediaSize = (MediaSizeName)media;
final PrinterHWMediaSize printerHWMediaSize = new PrinterHWMediaSize();
printerHWMediaSize.setName(name);
// printerHWMediaSize.setIsDefault(isDefault);
printerHWMediaSizes.add(printerHWMediaSize);
}
else if (media instanceof MediaTray) | {
final MediaTray mediaTray = (MediaTray)media;
final String name = mediaTray.toString();
final String trayNumber = Integer.toString(mediaTray.getValue());
final PrinterHWMediaTray printerHWMediaTray = new PrinterHWMediaTray();
printerHWMediaTray.setName(name);
printerHWMediaTray.setTrayNumber(trayNumber);
// 04005: default media tray shall be first in the list
if (mediaTray.equals(defaultMediaTray))
{
printerHWMediaTrays.add(0, printerHWMediaTray);
}
else
{
printerHWMediaTrays.add(printerHWMediaTray);
}
}
}
printerHWs.add(printerHW);
}
final PrinterHWList list = new PrinterHWList();
list.setHwPrinters(printerHWs);
return list;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintingEngine.java | 1 |
请完成以下Java代码 | public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
} | public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java | 1 |
请完成以下Java代码 | void init() {
// o_name and O_NAME, same
jdbcTemplate.setResultsMapCaseInsensitive(true);
simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("get_book_by_id");
}
private static final String SQL_STORED_PROC = ""
+ " CREATE OR REPLACE PROCEDURE get_book_by_id "
+ " ("
+ " p_id IN BOOKS.ID%TYPE,"
+ " o_name OUT BOOKS.NAME%TYPE,"
+ " o_price OUT BOOKS.PRICE%TYPE"
+ " ) AS"
+ " BEGIN"
+ " SELECT NAME, PRICE INTO o_name, o_price from BOOKS WHERE ID = p_id;"
+ " END;";
public void start() {
log.info("Creating Store Procedures and Function...");
jdbcTemplate.execute(SQL_STORED_PROC);
/* Test Stored Procedure */
Book book = findById(2L).orElseThrow(IllegalArgumentException::new);
// Book{id=2, name='Mkyong in Java', price=1.99}
System.out.println(book);
}
Optional<Book> findById(Long id) { | SqlParameterSource in = new MapSqlParameterSource()
.addValue("p_id", id);
Optional result = Optional.empty();
try {
Map out = simpleJdbcCall.execute(in);
if (out != null) {
Book book = new Book();
book.setId(id);
book.setName((String) out.get("O_NAME"));
book.setPrice((BigDecimal) out.get("O_PRICE"));
result = Optional.of(book);
}
} catch (Exception e) {
// ORA-01403: no data found, or any java.sql.SQLException
System.err.println(e.getMessage());
}
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\sp\StoredProcedure1.java | 1 |
请完成以下Java代码 | public final E next()
{
if (closed)
{
throw new NoSuchElementException("ResultSet already closed");
}
boolean keepAliveResultSet = false; // if false, underlying ResultSet will be closed in finally block
try
{
if (rs == null)
{
rs = createResultSet();
if (rs == null)
{
throw new IllegalStateException("No ResultSet was created");
}
}
if (!rs.next())
{
// we reached the end of result set
keepAliveResultSet = false; // flag that we need to close the ResultSet
return null;
}
final E item = fetch(rs);
keepAliveResultSet = true;
return item;
}
catch (SQLException e)
{
keepAliveResultSet = false; // make sure we will close the ResultSet
onSQLException(e);
// NOTE: we shall not reach this point because onSQLException is assumed to throw the exception
throw new DBException(e);
}
finally
{
if (!keepAliveResultSet)
{ | close();
}
}
}
/**
* Gets the {@link SQLException} and throws the proper exception (maybe with more informations)
*
* @param e
*/
protected void onSQLException(final SQLException e)
{
throw new DBException(e);
}
/**
* Closes the underlying {@link ResultSet}.
*/
@Override
public void close()
{
DB.close(rs);
rs = null;
closed = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\db\util\AbstractResultSetBlindIterator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getShippingCarrierCode()
{
return shippingCarrierCode;
}
public void setShippingCarrierCode(String shippingCarrierCode)
{
this.shippingCarrierCode = shippingCarrierCode;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
ShippingFulfillment shippingFulfillment = (ShippingFulfillment)o;
return Objects.equals(this.fulfillmentId, shippingFulfillment.fulfillmentId) &&
Objects.equals(this.lineItems, shippingFulfillment.lineItems) &&
Objects.equals(this.shipmentTrackingNumber, shippingFulfillment.shipmentTrackingNumber) &&
Objects.equals(this.shippedDate, shippingFulfillment.shippedDate) &&
Objects.equals(this.shippingCarrierCode, shippingFulfillment.shippingCarrierCode);
}
@Override
public int hashCode()
{
return Objects.hash(fulfillmentId, lineItems, shipmentTrackingNumber, shippedDate, shippingCarrierCode);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class ShippingFulfillment {\n");
sb.append(" fulfillmentId: ").append(toIndentedString(fulfillmentId)).append("\n"); | sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" shipmentTrackingNumber: ").append(toIndentedString(shipmentTrackingNumber)).append("\n");
sb.append(" shippedDate: ").append(toIndentedString(shippedDate)).append("\n");
sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).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\ShippingFulfillment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultTbRepositorySettingsService extends TbAbstractVersionControlSettingsService<RepositorySettings> implements TbRepositorySettingsService {
public static final String SETTINGS_KEY = "entitiesVersionControl";
public DefaultTbRepositorySettingsService(AdminSettingsService adminSettingsService, TbTransactionalCache<TenantId, RepositorySettings> cache) {
super(adminSettingsService, cache, RepositorySettings.class, SETTINGS_KEY);
}
@Override
public RepositorySettings restore(TenantId tenantId, RepositorySettings settings) {
RepositorySettings storedSettings = get(tenantId);
if (storedSettings != null) {
RepositoryAuthMethod authMethod = settings.getAuthMethod();
if (RepositoryAuthMethod.USERNAME_PASSWORD.equals(authMethod) && settings.getPassword() == null) {
settings.setPassword(storedSettings.getPassword());
} else if (RepositoryAuthMethod.PRIVATE_KEY.equals(authMethod) && settings.getPrivateKey() == null) {
settings.setPrivateKey(storedSettings.getPrivateKey());
if (settings.getPrivateKeyPassword() == null) {
settings.setPrivateKeyPassword(storedSettings.getPrivateKeyPassword()); | }
}
}
return settings;
}
@Override
public RepositorySettings get(TenantId tenantId) {
RepositorySettings settings = super.get(tenantId);
if (settings != null) {
settings = new RepositorySettings(settings);
}
return settings;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\repository\DefaultTbRepositorySettingsService.java | 2 |
请完成以下Java代码 | public IPreliminaryDocumentNoBuilder setNewDocType(@Nullable final I_C_DocType newDocType)
{
assertNotBuilt();
_newDocType = newDocType;
return this;
}
private I_C_DocType getNewDocType()
{
return _newDocType;
}
@Override
public IPreliminaryDocumentNoBuilder setOldDocType_ID(final int oldDocType_ID)
{
assertNotBuilt();
_oldDocType_ID = oldDocType_ID > 0 ? oldDocType_ID : -1;
return this;
}
private I_C_DocType getOldDocType()
{
if (_oldDocType == null)
{
final int oldDocTypeId = _oldDocType_ID;
if (oldDocTypeId > 0)
{
_oldDocType = InterfaceWrapperHelper.create(getCtx(), oldDocTypeId, I_C_DocType.class, ITrx.TRXNAME_None);
}
}
return _oldDocType;
}
@Override
public IPreliminaryDocumentNoBuilder setOldDocumentNo(final String oldDocumentNo)
{
assertNotBuilt();
_oldDocumentNo = oldDocumentNo;
return this;
}
private String getOldDocumentNo()
{
return _oldDocumentNo; | }
private boolean isNewDocumentNo()
{
final String oldDocumentNo = getOldDocumentNo();
if (oldDocumentNo == null)
{
return true;
}
if (IPreliminaryDocumentNoBuilder.hasPreliminaryMarkers(oldDocumentNo))
{
return true;
}
return false;
}
@Override
public IPreliminaryDocumentNoBuilder setDocumentModel(final Object documentModel)
{
_documentModel = documentModel;
return this;
}
private Object getDocumentModel()
{
Check.assumeNotNull(_documentModel, "_documentModel not null");
return _documentModel;
}
private java.util.Date getDocumentDate(final String dateColumnName)
{
final Object documentModel = getDocumentModel();
final Optional<java.util.Date> date = InterfaceWrapperHelper.getValue(documentModel, dateColumnName);
return date.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\PreliminaryDocumentNoBuilder.java | 1 |
请完成以下Java代码 | public class MockConsumerFactory<K, V> implements ConsumerFactory<K, V> {
private final Supplier<MockConsumer<K, V>> consumerProvider;
/**
* Create an instance with the supplied consumer provider.
* @param consumerProvider the consumer provider.
*/
public MockConsumerFactory(Supplier<MockConsumer<K, V>> consumerProvider) {
this.consumerProvider = consumerProvider;
}
@Override
public Map<String, Object> getConfigurationProperties() {
return Collections.emptyMap();
}
@Override | public Consumer<K, V> createConsumer(@Nullable String groupId, @Nullable String clientIdPrefix,
@Nullable String clientIdSuffix) {
return this.consumerProvider.get();
}
@Override
public Consumer<K, V> createConsumer(@Nullable String groupId, @Nullable String clientIdPrefix,
@Nullable String clientIdSuffix, @Nullable Properties properties) {
return this.consumerProvider.get();
}
@Override
public boolean isAutoCommit() {
return false;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\mock\MockConsumerFactory.java | 1 |
请完成以下Java代码 | public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException
{
return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name)
.getPO(getReversal_ID(), get_TrxName()); }
/** Set Reversal ID.
@param Reversal_ID
ID of document reversal
*/
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null); | else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_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\eevolution\model\X_HR_Process.java | 1 |
请完成以下Java代码 | class MySqlR2dbcDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> {
MySqlR2dbcDockerComposeConnectionDetailsFactory() {
super("mysql", "io.r2dbc.spi.ConnectionFactoryOptions");
}
@Override
protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new MySqlR2dbcDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link R2dbcConnectionDetails} backed by a {@code mysql} {@link RunningService}.
*/
static class MySqlR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements R2dbcConnectionDetails {
private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder(
"mysql", 3306); | private final ConnectionFactoryOptions connectionFactoryOptions;
MySqlR2dbcDockerComposeConnectionDetails(RunningService service) {
super(service);
MySqlEnvironment environment = new MySqlEnvironment(service.env());
this.connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, environment.getDatabase(),
environment.getUsername(), environment.getPassword());
}
@Override
public ConnectionFactoryOptions getConnectionFactoryOptions() {
return this.connectionFactoryOptions;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\MySqlR2dbcDockerComposeConnectionDetailsFactory.java | 1 |
请完成以下Java代码 | public Vector minus(Vector other)
{
float[] result = new float[size()];
for (int i = 0; i < result.length; i++)
{
result[i] = elementArray[i] - other.elementArray[i];
}
return new Vector(result);
}
public Vector add(Vector other)
{
float[] result = new float[size()];
for (int i = 0; i < result.length; i++)
{
result[i] = elementArray[i] + other.elementArray[i];
}
return new Vector(result);
}
public Vector addToSelf(Vector other)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] + other.elementArray[i];
}
return this;
}
public Vector divideToSelf(int n)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / n;
}
return this;
}
public Vector divideToSelf(float f)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / f; | }
return this;
}
/**
* 自身归一化
*
* @return
*/
public Vector normalize()
{
divideToSelf(norm());
return this;
}
public float[] getElementArray()
{
return elementArray;
}
public void setElementArray(float[] elementArray)
{
this.elementArray = elementArray;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java | 1 |
请完成以下Java代码 | public class Product implements Rankable, Serializable {
private String name;
private double price;
private int sales;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public int getRank() {
return sales;
}
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + ", sales=" + sales + "]";
}
// getters and setters
public String getName() {
return name;
}
public void setName(String name) { | this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\generics\Product.java | 1 |
请完成以下Java代码 | public void checkQueryOk() {
super.checkQueryOk();
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getIdOrKey() {
return idOrKey;
}
public String getKeyLike() {
return keyLike;
}
public Set<String> getKeys() {
return keys;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
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代码 | public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() { | return false;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\security\UserPrincipal.java | 1 |
请完成以下Java代码 | public String getAlbumPics() {
return albumPics;
}
public void setAlbumPics(String albumPics) {
this.albumPics = albumPics;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getForwardCount() {
return forwardCount;
}
public void setForwardCount(Integer forwardCount) {
this.forwardCount = forwardCount;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", title=").append(title);
sb.append(", pic=").append(pic);
sb.append(", productCount=").append(productCount);
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", createTime=").append(createTime);
sb.append(", collectCount=").append(collectCount);
sb.append(", readCount=").append(readCount);
sb.append(", commentCount=").append(commentCount);
sb.append(", albumPics=").append(albumPics);
sb.append(", description=").append(description);
sb.append(", showStatus=").append(showStatus);
sb.append(", forwardCount=").append(forwardCount);
sb.append(", categoryName=").append(categoryName);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java | 1 |
请完成以下Java代码 | public HUReceiptScheduleAllocBuilder setHU_QtyAllocated(@NonNull final StockQtyAndUOMQty huQtyAllocated)
{
_huQtyAllocated = huQtyAllocated;
return this;
}
private StockQtyAndUOMQty getHU_QtyAllocated()
{
return _huQtyAllocated;
}
private I_M_HU getM_LU_HU()
{
return _luHU;
}
public HUReceiptScheduleAllocBuilder setM_LU_HU(final I_M_HU luHU)
{
_luHU = luHU;
return this;
}
private I_M_HU getM_TU_HU()
{ | return _tuHU;
}
public HUReceiptScheduleAllocBuilder setM_TU_HU(final I_M_HU tuHU)
{
_tuHU = tuHU;
return this;
}
private I_M_HU getVHU()
{
return _vhu;
}
public HUReceiptScheduleAllocBuilder setVHU(final I_M_HU vhu)
{
_vhu = vhu;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\HUReceiptScheduleAllocBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PmsRole> listAllRole() {
return pmsRoleDao.listAll();
}
/**
* 判断此权限是否关联有角色
*
* @param permissionId
* @return
*/
public List<PmsRole> listByPermissionId(Long permissionId) {
return pmsRoleDao.listByPermissionId(permissionId);
}
/**
* 根据角色名或者角色编号查询角色
*
* @param roleName | * @param roleCode
* @return
*/
public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) {
return pmsRoleDao.getByRoleNameOrRoleCode(roleName, roleCode);
}
/**
* 删除
*
* @param roleId
*/
public void delete(Long roleId) {
pmsRoleDao.delete(roleId);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRoleServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class NormalClass {
}
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
class PrototypeClass {
}
@Configuration
@ComponentScan
public class BeanScopesLauncherApplication {
public static void main(String[] args) {
try (var context = | new AnnotationConfigApplicationContext
(BeanScopesLauncherApplication.class)) {
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(NormalClass.class));
System.out.println(context.getBean(PrototypeClass.class));
System.out.println(context.getBean(PrototypeClass.class));
System.out.println(context.getBean(PrototypeClass.class));
System.out.println(context.getBean(PrototypeClass.class));
}
}
} | repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\e1\BeanScopesLauncherApplication.java | 2 |
请完成以下Java代码 | public static void writeString(String s, DataOutputStream out) throws IOException
{
out.writeInt(s.length());
for (char c : s.toCharArray())
{
out.writeChar(c);
}
}
/**
* 判断字符串是否为空(null和空格)
*
* @param cs
* @return
*/
public static boolean isBlank(CharSequence cs)
{
int strLen;
if (cs == null || (strLen = cs.length()) == 0)
{
return true;
}
for (int i = 0; i < strLen; i++)
{
if (!Character.isWhitespace(cs.charAt(i)))
{
return false;
}
}
return true;
}
public static String join(String delimiter, Collection<String> stringCollection)
{
StringBuilder sb = new StringBuilder(stringCollection.size() * (16 + delimiter.length()));
for (String str : stringCollection)
{
sb.append(str).append(delimiter);
}
return sb.toString();
} | public static String combine(String... termArray)
{
StringBuilder sbSentence = new StringBuilder();
for (String word : termArray)
{
sbSentence.append(word);
}
return sbSentence.toString();
}
public static String join(Iterable<? extends CharSequence> s, String delimiter)
{
Iterator<? extends CharSequence> iter = s.iterator();
if (!iter.hasNext()) return "";
StringBuilder buffer = new StringBuilder(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
public static String combine(Sentence sentence)
{
StringBuilder sb = new StringBuilder(sentence.wordList.size() * 3);
for (IWord word : sentence.wordList)
{
sb.append(word.getValue());
}
return sb.toString();
}
public static String combine(List<Word> wordList)
{
StringBuilder sb = new StringBuilder(wordList.size() * 3);
for (IWord word : wordList)
{
sb.append(word.getValue());
}
return sb.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\TextUtility.java | 1 |
请完成以下Java代码 | public Integer getContinueSignDay() {
return continueSignDay;
}
public void setContinueSignDay(Integer continueSignDay) {
this.continueSignDay = continueSignDay;
}
public Integer getContinueSignPoint() {
return continueSignPoint;
}
public void setContinueSignPoint(Integer continueSignPoint) {
this.continueSignPoint = continueSignPoint;
}
public BigDecimal getConsumePerPoint() {
return consumePerPoint;
}
public void setConsumePerPoint(BigDecimal consumePerPoint) {
this.consumePerPoint = consumePerPoint;
}
public BigDecimal getLowOrderAmount() {
return lowOrderAmount;
}
public void setLowOrderAmount(BigDecimal lowOrderAmount) {
this.lowOrderAmount = lowOrderAmount;
}
public Integer getMaxPointPerOrder() {
return maxPointPerOrder;
}
public void setMaxPointPerOrder(Integer maxPointPerOrder) {
this.maxPointPerOrder = maxPointPerOrder;
}
public Integer getType() { | return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", continueSignDay=").append(continueSignDay);
sb.append(", continueSignPoint=").append(continueSignPoint);
sb.append(", consumePerPoint=").append(consumePerPoint);
sb.append(", lowOrderAmount=").append(lowOrderAmount);
sb.append(", maxPointPerOrder=").append(maxPointPerOrder);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberRuleSetting.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MessageInstance sendFor(
MessageInstance message,
Operation operation,
ConcurrentMap<QName, URL> overridenEndpointAddresses
) throws Exception {
Object[] arguments = this.getArguments(message);
Object[] results = this.safeSend(arguments, overridenEndpointAddresses);
return this.createResponseMessage(results, operation);
}
private Object[] getArguments(MessageInstance message) {
return message.getStructureInstance().toArray();
}
private Object[] safeSend(Object[] arguments, ConcurrentMap<QName, URL> overridenEndpointAddresses)
throws Exception {
Object[] results = null;
results = this.service.getClient().send(this.name, arguments, overridenEndpointAddresses);
if (results == null) {
results = new Object[] {}; | }
return results;
}
private MessageInstance createResponseMessage(Object[] results, Operation operation) {
MessageInstance message = null;
MessageDefinition outMessage = operation.getOutMessage();
if (outMessage != null) {
message = outMessage.createInstance();
message.getStructureInstance().loadFrom(results);
}
return message;
}
public WSService getService() {
return this.service;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\webservice\WSOperation.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<String> getImgCache(String key) {
RMapCache<String, List<String>> convertedList = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
return convertedList.get(key);
}
@Override
public Integer getPdfImageCache(String key) {
RMapCache<String, Integer> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
return convertedList.get(key);
}
@Override
public void putPdfImageCache(String pdfFilePath, int num) {
RMapCache<String, Integer> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
convertedList.fastPut(pdfFilePath, num);
}
@Override
public Map<String, String> getMediaConvertCache() {
return redissonClient.getMapCache(FILE_PREVIEW_MEDIA_CONVERT_KEY);
}
@Override
public void putMediaConvertCache(String key, String value) {
RMapCache<String, String> convertedList = redissonClient.getMapCache(FILE_PREVIEW_MEDIA_CONVERT_KEY);
convertedList.fastPut(key, value);
}
@Override
public String getMediaConvertCache(String key) {
RMapCache<String, String> convertedList = redissonClient.getMapCache(FILE_PREVIEW_MEDIA_CONVERT_KEY);
return convertedList.get(key);
}
@Override
public void cleanCache() {
cleanPdfCache();
cleanImgCache();
cleanPdfImgCache();
cleanMediaConvertCache();
}
@Override
public void addQueueTask(String url) {
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME);
queue.addAsync(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME); | return queue.take();
}
private void cleanPdfCache() {
RMapCache<String, String> pdfCache = redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
pdfCache.clear();
}
private void cleanImgCache() {
RMapCache<String, List<String>> imgCache = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
imgCache.clear();
}
private void cleanPdfImgCache() {
RMapCache<String, Integer> pdfImg = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
pdfImg.clear();
}
private void cleanMediaConvertCache() {
RMapCache<String, Integer> mediaConvertCache = redissonClient.getMapCache(FILE_PREVIEW_MEDIA_CONVERT_KEY);
mediaConvertCache.clear();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRedisImpl.java | 2 |
请完成以下Java代码 | public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '" + validatorSetName + "' | Problem: '" + problem + "'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (processDefinitionId != null) {
strb.append("processDefinitionId = " + processDefinitionId);
extraInfoAlreadyPresent = true;
}
if (processDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("processDefinitionName = " + processDefinitionName + " | ");
extraInfoAlreadyPresent = true;
}
if (activityId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = " + activityId + " | ");
extraInfoAlreadyPresent = true;
}
if (activityName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("activityName = " + activityName + " | "); | extraInfoAlreadyPresent = true;
}
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: " + xmlLineNumber + ", column: " + xmlColumnNumber + ")");
}
if (key != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append(" ( key: " + key + " )");
extraInfoAlreadyPresent = true;
}
if (params != null && !params.isEmpty()) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append(" ( ");
for (Map.Entry<String, String> param : params.entrySet()) {
strb.append(param.getKey() + " = " + param.getValue() + " | ");
}
strb.append(")");
extraInfoAlreadyPresent = true;
}
strb.append("]");
return strb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\ValidationError.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductEntity {
@Id
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() { | return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\exception\ProductEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor(
ProjectDescription description) {
return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main")
.parameters(Parameter.of("args", "Array<String>"))
.body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication",
description.getApplicationName())));
}
}
/**
* Kotlin source code contributions for projects using war packaging.
*/
@Configuration
@ConditionalOnPackaging(WarPackaging.ID)
static class WarPackagingConfiguration {
@Bean
ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer( | ProjectDescription description) {
return (typeDeclaration) -> {
KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure")
.modifiers(KotlinModifier.OVERRIDE)
.returning("org.springframework.boot.builder.SpringApplicationBuilder")
.parameters(
Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder"))
.body(CodeBlock.ofStatement("return application.sources($L::class.java)",
description.getApplicationName()));
typeDeclaration.addFunctionDeclaration(configure);
};
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java | 2 |
请完成以下Java代码 | public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Partner Category.
@param VendorCategory
Product Category of the Business Partner
*/
public void setVendorCategory (String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
/** Get Partner Category.
@return Product Category of the Business Partner | */
public String getVendorCategory ()
{
return (String)get_Value(COLUMNNAME_VendorCategory);
}
/** Set Partner Product Key.
@param VendorProductNo
Product Key of the Business Partner
*/
public void setVendorProductNo (String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
/** Get Partner Product Key.
@return Product Key of the Business Partner
*/
public String getVendorProductNo ()
{
return (String)get_Value(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, VariableType> variableTypeMap(
ObjectMapper objectMapper,
DateFormatterProvider dateFormatterProvider
) {
Map<String, VariableType> variableTypeMap = new HashMap<>();
variableTypeMap.put("boolean", new JavaObjectVariableType(Boolean.class));
variableTypeMap.put("string", new JavaObjectVariableType(String.class));
variableTypeMap.put("integer", new JavaObjectVariableType(Integer.class));
variableTypeMap.put("bigdecimal", new BigDecimalVariableType());
variableTypeMap.put("json", new JsonObjectVariableType(objectMapper));
variableTypeMap.put("file", new JsonObjectVariableType(objectMapper));
variableTypeMap.put("folder", new JsonObjectVariableType(objectMapper));
variableTypeMap.put("content", new JsonObjectVariableType(objectMapper));
variableTypeMap.put("date", new DateVariableType(Date.class, dateFormatterProvider));
variableTypeMap.put("datetime", new DateVariableType(Date.class, dateFormatterProvider));
variableTypeMap.put("array", new JsonObjectVariableType(objectMapper));
return variableTypeMap;
}
@Bean
public VariableValidationService variableValidationService(Map<String, VariableType> variableTypeMap) {
return new VariableValidationService(variableTypeMap); | }
@Bean
public VariableParsingService variableParsingService(Map<String, VariableType> variableTypeMap) {
return new VariableParsingService(variableTypeMap);
}
@Bean
@ConditionalOnMissingBean
public CachingProcessExtensionService cachingProcessExtensionService(
ProcessExtensionService processExtensionService
) {
return new CachingProcessExtensionService(processExtensionService);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\conf\ProcessExtensionsAutoConfiguration.java | 2 |
请完成以下Java代码 | private void sendAMQPMessage(final @NonNull String host, final int port, final @NonNull String msg, final @NonNull String exchangeName,
final @NonNull String routingKey, final @NonNull String userName, final @NonNull String password, final boolean isDurableQueue)
{
final CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
connectionFactory.setUsername(userName);
connectionFactory.setPassword(password);
final RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setRoutingKey(routingKey);
template.setExchange(exchangeName);
final RabbitAdmin admin = new RabbitAdmin(template.getConnectionFactory());
final Queue queue = new Queue(routingKey, isDurableQueue);
final DirectExchange exchange = new DirectExchange(exchangeName, isDurableQueue, false);
admin.declareExchange(exchange);
admin.declareQueue(queue);
// queue name and routing key are the same
admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(routingKey));
template.convertAndSend(msg);
log.info("AMQP Message sent!");
template.destroy();
connectionFactory.destroy();
}
@Override | public void createInitialParameters(final @NonNull MEXPProcessor processor)
{
processor.createParameter(
EXCHANGE_NAME_PARAMETER,
"Name of AMQP exchange from where xml will be exported",
"Export Processor Parameter Description",
"AMQP Export Processor Parameter Help",
"ExampleExchange");
processor.createParameter(
ROUTING_KEY_PARAMETER,
"AMQP routing key for the messages that will be exported",
"Export Processor Parameter Description",
"AMQP Export Processor Parameter Help",
"ExpRoutingKey");
processor.createParameter(
IS_DURABLE_QUEUE_PARAMETER,
"AMQP durable queue used for export",
"Export Processor Parameter Description",
"AMQP Export Processor Parameter Help",
"true");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\exp\RabbitMqExportProcessor.java | 1 |
请完成以下Java代码 | protected DecisionRequirementsDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return getDecisionRequirementsDefinitionManager().findDecisionRequirementsDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
@Override
protected DecisionRequirementsDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return getDecisionRequirementsDefinitionManager().findLatestDecisionRequirementsDefinitionByKeyAndTenantId(definitionKey, tenantId);
}
@Override
protected void persistDefinition(DecisionRequirementsDefinitionEntity definition) {
if (isDecisionRequirementsDefinitionPersistable(definition)) {
getDecisionRequirementsDefinitionManager().insertDecisionRequirementsDefinition(definition);
}
}
@Override
protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, DecisionRequirementsDefinitionEntity definition) {
if (isDecisionRequirementsDefinitionPersistable(definition)) {
deploymentCache.addDecisionRequirementsDefinition(definition);
}
}
@Override
protected void ensureNoDuplicateDefinitionKeys(List<DecisionRequirementsDefinitionEntity> definitions) {
// ignore decision requirements definitions which will not be persistent
ArrayList<DecisionRequirementsDefinitionEntity> persistableDefinitions = new ArrayList<DecisionRequirementsDefinitionEntity>();
for (DecisionRequirementsDefinitionEntity definition : definitions) {
if (isDecisionRequirementsDefinitionPersistable(definition)) {
persistableDefinitions.add(definition);
}
} | super.ensureNoDuplicateDefinitionKeys(persistableDefinitions);
}
public static boolean isDecisionRequirementsDefinitionPersistable(DecisionRequirementsDefinitionEntity definition) {
// persist no decision requirements definition for a single decision
return definition.getDecisions().size() > 1;
}
@Override
protected void updateDefinitionByPersistedDefinition(DeploymentEntity deployment, DecisionRequirementsDefinitionEntity definition,
DecisionRequirementsDefinitionEntity persistedDefinition) {
// cannot update the definition if it is not persistent
if (persistedDefinition != null) {
super.updateDefinitionByPersistedDefinition(deployment, definition, persistedDefinition);
}
}
//context ///////////////////////////////////////////////////////////////////////////////////////////
protected DecisionRequirementsDefinitionManager getDecisionRequirementsDefinitionManager() {
return getCommandContext().getDecisionRequirementsDefinitionManager();
}
// getters/setters ///////////////////////////////////////////////////////////////////////////////////
public DmnTransformer getTransformer() {
return transformer;
}
public void setTransformer(DmnTransformer transformer) {
this.transformer = transformer;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\deployer\DecisionRequirementsDefinitionDeployer.java | 1 |
请完成以下Java代码 | public String getText ()
{
String text = m_text.getText();
return text;
} // getText
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
* @param e event
*/
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure | } // focus Lost
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VURL | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
} | public String getDerivedCaseDefinitionUrl() {
return derivedCaseDefinitionUrl;
}
public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) {
this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl;
}
public String getStageInstanceUrl() {
return stageInstanceUrl;
}
public void setStageInstanceUrl(String stageInstanceUrl) {
this.stageInstanceUrl = stageInstanceUrl;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | private void setHelp(final String adLanguage, final String helpTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if(helpTrl == null)
{
return;
}
if(helpTrls == null)
{
helpTrls = new HashMap<>();
}
helpTrls.put(adLanguage, helpTrl);
}
void setReadWrite(final boolean readWrite)
{
this._isReadWrite = readWrite;
}
public boolean isReadWrite()
{
return Boolean.TRUE.equals(_isReadWrite);
}
private void setIsSOTrx(final boolean isSOTrx)
{
this._isSOTrx = isSOTrx;
}
public boolean isSOTrx()
{
return _isSOTrx;
}
public int getAD_Color_ID()
{
return AD_Color_ID;
}
public int getAD_Image_ID()
{
return AD_Image_ID;
}
public int getWinWidth() | {
return WinWidth;
}
public int getWinHeight()
{
return WinHeight;
}
public String getWindowType()
{
return WindowType;
}
private int getBaseTable_ID()
{
return _BaseTable_ID;
}
boolean isLoadAllLanguages()
{
return loadAllLanguages;
}
boolean isApplyRolePermissions()
{
return applyRolePermissions;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java | 1 |
请完成以下Java代码 | protected void enhanceScriptTrace(ScriptEngineRequest request, DefaultScriptTrace scriptTrace) {
if (defaultTraceEnhancer != null) {
defaultTraceEnhancer.enhanceScriptTrace(scriptTrace);
}
if (request.getTraceEnhancer() != null) {
request.getTraceEnhancer().enhanceScriptTrace(scriptTrace);
}
}
public ScriptBindingsFactory getScriptBindingsFactory() {
return scriptBindingsFactory;
}
public void setScriptBindingsFactory(ScriptBindingsFactory scriptBindingsFactory) {
this.scriptBindingsFactory = scriptBindingsFactory;
}
public ScriptTraceEnhancer getDefaultTraceEnhancer() {
return defaultTraceEnhancer;
}
public void setDefaultTraceEnhancer(ScriptTraceEnhancer defaultTraceEnhancer) {
this.defaultTraceEnhancer = defaultTraceEnhancer;
} | public ScriptTraceListener getScriptErrorListener() {
return scriptErrorListener;
}
public void setScriptErrorListener(ScriptTraceListener scriptErrorListener) {
this.scriptErrorListener = scriptErrorListener;
}
public ScriptTraceListener getScriptSuccessListener() {
return scriptSuccessListener;
}
public void setScriptSuccessListener(ScriptTraceListener scriptSuccessListener) {
this.scriptSuccessListener = scriptSuccessListener;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptingEngines.java | 1 |
请完成以下Java代码 | public Post findWithEntityGraph2(Long id) {
EntityManager entityManager = emf.createEntityManager();
EntityGraph<Post> entityGraph = entityManager.createEntityGraph(Post.class);
entityGraph.addAttributeNodes("subject");
entityGraph.addAttributeNodes("user");
entityGraph.addSubgraph("comments")
.addAttributeNodes("user");
Map<String, Object> properties = new HashMap<>();
properties.put("jakarta.persistence.fetchgraph", entityGraph);
Post post = entityManager.find(Post.class, id, properties);
entityManager.close();
return post;
}
public Post findUsingJpql(Long id) {
EntityManager entityManager = emf.createEntityManager();
EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users");
Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class)
.setParameter("id", id)
.setHint("jakarta.persistence.fetchgraph", entityGraph)
.getSingleResult();
entityManager.close();
return post;
}
public Post findUsingCriteria(Long id) { | EntityManager entityManager = emf.createEntityManager();
EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Post> criteriaQuery = criteriaBuilder.createQuery(Post.class);
Root<Post> root = criteriaQuery.from(Post.class);
criteriaQuery.where(criteriaBuilder.equal(root.<Long>get("id"), id));
TypedQuery<Post> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setHint("jakarta.persistence.loadgraph", entityGraph);
Post post = typedQuery.getSingleResult();
entityManager.close();
return post;
}
public void clean() {
emf.close();
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entitygraph\repo\PostRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void close() {
this.golfTournament = null;
}
public boolean isFinished(@Nullable GolfTournament golfTournament) {
return golfTournament == null || golfTournament.isFinished();
}
public boolean isNotFinished(@Nullable GolfTournament golfTournament) {
return !isFinished(golfTournament);
}
public PgaTourService manage(GolfTournament golfTournament) {
GolfTournament currentGolfTournament = this.golfTournament;
Assert.state(currentGolfTournament == null,
() -> String.format("Can only manage 1 golf tournament at a time; currently managing [%s]",
currentGolfTournament));
this.golfTournament = golfTournament;
return this;
}
// tag::play[]
@Scheduled(initialDelay = 5000L, fixedDelay = 2500L)
public void play() {
GolfTournament golfTournament = this.golfTournament;
if (isNotFinished(golfTournament)) {
playHole(golfTournament);
finish(golfTournament);
}
}
// end::play[]
private synchronized void playHole(@NonNull GolfTournament golfTournament) {
GolfCourse golfCourse = golfTournament.getGolfCourse();
Set<Integer> occupiedHoles = new HashSet<>();
for (GolfTournament.Pairing pairing : golfTournament) {
int hole = pairing.nextHole();
if (!occupiedHoles.contains(hole)) {
if (golfCourse.isValidHoleNumber(hole)) {
occupiedHoles.add(hole);
pairing.setHole(hole);
updateScore(this::calculateRunningScore, pairing.getPlayerOne());
updateScore(this::calculateRunningScore, pairing.getPlayerTwo());
}
}
}
}
private Golfer updateScore(@NonNull Function<Integer, Integer> scoreFunction, @NonNull Golfer player) {
player.setScore(scoreFunction.apply(player.getScore()));
this.golferService.update(player); | return player;
}
private int calculateFinalScore(@Nullable Integer scoreRelativeToPar) {
int finalScore = scoreRelativeToPar != null ? scoreRelativeToPar : 0;
int parForCourse = getGolfTournament()
.map(GolfTournament::getGolfCourse)
.map(GolfCourse::getParForCourse)
.orElse(GolfCourse.STANDARD_PAR_FOR_COURSE);
return parForCourse + finalScore;
}
private int calculateRunningScore(@Nullable Integer currentScore) {
int runningScore = currentScore != null ? currentScore : 0;
int scoreDelta = this.random.nextInt(SCORE_DELTA_BOUND);
scoreDelta *= this.random.nextBoolean() ? -1 : 1;
return runningScore + scoreDelta;
}
private void finish(@NonNull GolfTournament golfTournament) {
for (GolfTournament.Pairing pairing : golfTournament) {
if (pairing.signScorecard()) {
updateScore(this::calculateFinalScore, pairing.getPlayerOne());
updateScore(this::calculateFinalScore, pairing.getPlayerTwo());
}
}
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\PgaTourService.java | 2 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("tableName", tableName)
.add("async", async)
.toString();
}
@Override
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client)
{
engine.addDocValidate(tableName, this);
}
@Override
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception
{
if (timing != DocTimingType.AFTER_COMPLETE)
{
return; // nothing to do
}
final ICounterDocBL counterDocumentBL = Services.get(ICounterDocBL.class);
if (!counterDocumentBL.isCreateCounterDocument(model))
{
return; // nothing to do
}
counterDocumentBL.createCounterDocument(model, async);
}
/** {@link CounterDocHandlerInterceptor} instance builder */
public static final class Builder
{
private String tableName;
private boolean async = false;
private Builder()
{
super();
}
public CounterDocHandlerInterceptor build()
{
return new CounterDocHandlerInterceptor(this);
}
public Builder setTableName(String tableName) | {
this.tableName = tableName;
return this;
}
private final String getTableName()
{
Check.assumeNotEmpty(tableName, "tableName not empty");
return tableName;
}
public Builder setAsync(boolean async)
{
this.async = async;
return this;
}
private boolean isAsync()
{
return async;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\model\interceptor\CounterDocHandlerInterceptor.java | 1 |
请完成以下Java代码 | public class DispatcherTypeRequestMatcher implements RequestMatcher {
private final DispatcherType dispatcherType;
@Nullable
private final HttpMethod httpMethod;
/**
* Creates an instance which matches requests with the provided {@link DispatcherType}
* @param dispatcherType the type to match against
*/
public DispatcherTypeRequestMatcher(DispatcherType dispatcherType) {
this(dispatcherType, null);
}
/**
* Creates an instance which matches requests with the provided {@link DispatcherType}
* and {@link HttpMethod}
* @param dispatcherType the type to match against
* @param httpMethod the HTTP method to match. May be null to match all methods.
*/
public DispatcherTypeRequestMatcher(DispatcherType dispatcherType, @Nullable HttpMethod httpMethod) {
this.dispatcherType = dispatcherType;
this.httpMethod = httpMethod;
}
/**
* Performs the match against the request's method and dispatcher type.
* @param request the request to check for a match
* @return true if the http method and dispatcher type align
*/ | @Override
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && StringUtils.hasText(request.getMethod())
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
return this.dispatcherType == request.getDispatcherType();
}
@Override
public String toString() {
return "DispatcherTypeRequestMatcher{" + "dispatcherType=" + this.dispatcherType + ", httpMethod="
+ this.httpMethod + '}';
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\DispatcherTypeRequestMatcher.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.