Skip to content

Commit

Permalink
Merge pull request #2 from spacious-team/develop
Browse files Browse the repository at this point in the history
Релиз 2024.1
  • Loading branch information
vananiev committed Apr 22, 2024
2 parents 4a5c1bd + e074111 commit c8bf2f1
Show file tree
Hide file tree
Showing 14 changed files with 1,176 additions and 24 deletions.
28 changes: 28 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
name: Отчет об ошибке
about: Создайте отчет об ошибке, чтобы улучшить приложение
title: ''
labels: bug
assignees: ''

---

**Опишите ошибку**
Ясное и краткое описание ошибки.

**Последовательность действий для воспроизведения**
Шаги по воспроизведению ошибки.

**Ожидаемый результат**
Ясное и краткое описание того, что вы ожидали.

**Скриншоты**
Если возможно, добавьте скриншоты, чтобы объяснить проблему.

**Окружение:**
- ОС: [например windows 10]
- Версия Java [например 19]
- Версия приложения[например 2020.1]

**Дополнительный контекст**
Любой другой контекст проблемы.
20 changes: 20 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
name: Запрос новой функциональности
about: Предложите идею для этого проекта
title: ''
labels: feature
assignees: ''

---

**Связан ли ваш запрос новой функциональности с проблемой? Пожалуйста, опишите.**
Четкое и краткое описание проблемы. Например, я всегда расстраиваюсь, когда [...]

**Опишите желаемое решение**
Четкое и краткое описание того, что вы хотите сделать.

**Опишите альтернативы, которые вы рассмотрели**
Четкое и краткое описание любых рассмотренных вами альтернативных решений или функций.

**Дополнительный контекст**
Любой другой контекст.
47 changes: 47 additions & 0 deletions .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Unit Tests

on:
workflow_dispatch:
pull_request:
branches:
- 'master'
- 'develop'
push:
branches:
- 'master'
- 'develop'

jobs:
tests:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Set up JDK
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'liberica'
cache: maven

- name: Maven Tests
run: mvn --batch-mode clean test

- name: Test Coverage
uses: codecov/codecov-action@v4.0.1
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

- name: SonarCloud Analyze
run: >
mvn --batch-mode sonar:sonar
-Dsonar.projectKey=spacious-team_table-wrapper-spring-boot-starter
-Dsonar.organization=spacious-team
-Dsonar.host.url=https://sonarcloud.io
-Dsonar.login=$SONAR_TOKEN
-Dsonar.coverage.jacoco.xmlReportPaths=./target/site/jacoco/jacoco.xml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
40 changes: 26 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
[![spring-boot-version](https://img.shields.io/badge/spring--boot-2.7+-brightgreen?style=flat-square)](https://github.com/spring-projects/spring-boot/releases)
[![jitpack-last-release](https://jitpack.io/v/spacious-team/table-wrapper-spring-boot-starter.svg?style=flat-square)](
https://jitpack.io/#spacious-team/table-wrapper-api)
[![Unit tests](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fspacious-team%2Ftable-wrapper-spring-boot-starter%2Fbadge%3Fref%3Ddevelop&style=flat-square&label=Test&logo=none)](
https://github.com/spacious-team/table-wrapper-spring-boot-starter/actions/workflows/unit-tests.yml)
[![Coverage](https://img.shields.io/codecov/c/github/spacious-team/table-wrapper-spring-boot-starter/develop?label=Coverage&style=flat-square&token=kqEvgEiKnQ)](
https://codecov.io/gh/spacious-team/table-wrapper-spring-boot-starter)

### Назначение
Позволяет работать с табличным представлением данных в форматах Excel, Xml и Csv через единый интерфейс
Expand Down Expand Up @@ -67,7 +71,7 @@ Spring Boot Starter настраивает реализации фабрик `Ex
- короткий десяти значный номер коммита для сборки зависимости с указанного коммита.

### Пример использования
Определяются колонки таблицы вне зависимости от формата файла (excel, xml, csv и др.):
Определяются колонки таблицы:
```java
@lombok.Getter
@lombok.RequiredArgsConstructor
Expand All @@ -78,20 +82,28 @@ enum TableHeader implements TableHeaderColumn {
private final TableColumn column;
}
```
Извлекаем данные в описанном формате, например, из Excel файла через Stream API
Извлекаем данные из таблицы с указанными колонками вне зависимости от формата файла (excel, xml, csv и др.):
```java
Workbook book = new XSSFWorkbook(xlsFileinputStream); // открываем Excel файл
ReportPage reportPage = new ExcelSheet(book.getSheetAt(0)); // используем 1-ый лист Excel файла для поиска таблицы
@org.springframework.beans.factory.annotation.Autowired
ReportPageFactory reportPageFactory;

// Регистронезависимо найдет ячейку с текстом "Таблица 1",
// парсит следующую за ней строку как заголовок таблицы,
// оставшиеся строки парсятся как данные до пустой строки или конца файла
Table table = reportPage.create("таблица 1", TableHeader.class); // метод использует бин ExcelTableFactory для создания таблицы
void parse() {
// Получаем страницу с данными. Используем бин ReportPageFactory для построения абстракции
ReportPage reportPage = reportPageFactory.create("1.xlsx");
// ... или reportPageFactory.create("1.xml");
// ... или reportPageFactory.create("1.csv");

// Извлекаем и обрабатываем строки таблицы
table.stream()
.forEach(row -> {
String product = row.getStringCellValue(TableHeader.PRODUCT);
BigDecimal price = getBigDecimalCellValue(TableHeader.PRICE);
});
// Метод найдет ячейку с текстом "Таблица 1",
// воспринимает следующую за ней строку как заголовок таблицы (который описан через enum TableHeader).
// Из последующих строк (до пустой строки или конца файла) извлекаются данные
// (метод использует бин ExcelTableFactory для создания таблицы Table на основе ReportPage)
Table table = reportPage.create("Таблица 1", TableHeader.class);

// Итерируемся по строкам таблицы и извлекаем ячейки из строк по заголовку таблицы
table.stream()
.forEach(row -> {
String product = row.getStringCellValue(TableHeader.PRODUCT);
BigDecimal price = getBigDecimalCellValue(TableHeader.PRICE);
});
}
```
42 changes: 34 additions & 8 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>org.spacious-team</groupId>
<artifactId>table-wrapper-spring-boot-starter</artifactId>
<version>2023.1</version>
<version>2024.1</version>
<packaging>jar</packaging>

<name>Spring Boot Starter for Table Wrapper</name>
Expand All @@ -30,7 +30,8 @@
<maven.compiler.release>11</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.10</spring-boot.version>
<spring-boot.version>2.7.18</spring-boot.version>
<lombok.version>1.18.32</lombok.version>
</properties>

<repositories>
Expand Down Expand Up @@ -62,7 +63,7 @@
<dependency>
<groupId>com.github.spacious-team</groupId>
<artifactId>table-wrapper-excel-impl</artifactId>
<version>2023.1</version>
<version>2024.1</version>
</dependency>
<dependency>
<groupId>com.github.spacious-team</groupId>
Expand All @@ -72,7 +73,7 @@
<dependency>
<groupId>com.github.spacious-team</groupId>
<artifactId>table-wrapper-csv-impl</artifactId>
<version>2023.1</version>
<version>2024.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -85,27 +86,52 @@
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version> <!-- JUnit 5 requirement -->
<version>3.2.5</version> <!-- JUnit 5 requirement -->
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<version>3.13.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>0.8.12</version>
<executions>
<execution>
<id>prepare-agent</id>
Expand All @@ -125,7 +151,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.1</version>
<executions>
<execution>
<id>attach-sources</id>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Table Wrapper Spring Boot Starter
* Copyright (C) 2024 Spacious Team <spacious-team@ya.ru>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

package org.spacious_team.table_wrapper.autoconfigure;

import org.spacious_team.table_wrapper.api.ReportPage;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

public interface ContextAwareReportPageFactory extends ReportPageFactory {

/**
* Returns the ReportPage implementation classes that can be instantiated by this factory.
*/
List<Class<? extends ReportPage>> getRegisteredReportPageTypes();

/**
* Register prototype spring bean definition for ReportPage implementation.
* This class instance can subsequently be created using the method {@link #create(Object...)}
*/
void registerBeanDefinition(Class<? extends ReportPage> clazz);

/**
* Chooses ReportPage implementation by its constructor argument types and creates it.
* Use this method if ReportPage should be created with nonstandard configuration.
*
* @throws ReportPageInstantiationException if ReportPage implementations' constructor not found
* or ReportPage instance creation fails
* @see ReportPageFactory#create(Path)
* @see ReportPageFactory#create(InputStream)
*/
ReportPage create(Object... args);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Table Wrapper Spring Boot Starter
* Copyright (C) 2024 Spacious Team <spacious-team@ya.ru>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

package org.spacious_team.table_wrapper.autoconfigure;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.spacious_team.table_wrapper.api.ReportPage;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

@Getter
@RequiredArgsConstructor
public class DefaultContextAwareReportPageFactory extends DefaultReportPageFactory implements ContextAwareReportPageFactory {

private final List<Class<? extends ReportPage>> registeredReportPageTypes = new CopyOnWriteArrayList<>();
private final ApplicationContext context;

@Override
public void registerBeanDefinition(Class<? extends ReportPage> clazz) {
registeredReportPageTypes.add(clazz);
String beanName = getBeanName(clazz);
BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(clazz)
.setScope(SCOPE_PROTOTYPE)
.getBeanDefinition();
getBeanDefinitionRegistry()
.registerBeanDefinition(beanName, beanDefinition);
}

private static String getBeanName(Class<?> clazz) {
char[] chars = clazz.getSimpleName().toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}

private BeanDefinitionRegistry getBeanDefinitionRegistry() {
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
return (BeanDefinitionRegistry) factory;
}

@Override
public ReportPage create(Object... args) {
for (Class<? extends ReportPage> clazz : registeredReportPageTypes) {
try {
return context.getBean(clazz, args);
} catch (Exception ignore) {
}
}
throw new ReportPageInstantiationException("Can't create ReportPage with arguments: " + List.of(args));
}
}
Loading

0 comments on commit c8bf2f1

Please sign in to comment.