Commit fed92d32 authored by 霍传世's avatar 霍传世

pdfGe

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>PDFGenerator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>PDFGenerator</name>
<description>PDFGenerator</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.32</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.133</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.example.pdfgenerator.Dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BasicReportParameters {
private String school;
private String province;
private String region;
private String examId;
private String subSubject;
private String command;
}
package com.example.pdfgenerator.Dto;
import lombok.Data;
@Data
public class ClassBasicReportParameters {
private String className;
private String school;
private String examId;
private String province;
private String region;
private String subSubject;
private String command;
}
package com.example.pdfgenerator.Dto;
import lombok.Data;
@Data
public class ClassDtoArgs {
private String region;
private String school;
private String className;
}
package com.example.pdfgenerator.Dto;
public class Dto {
private String school;
private String region;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
package com.example.pdfgenerator.Dto;
public class DtoArgs {
private String quesType;
private Double stuQtScoreRate;
private String subSubject;
private String stuId;
public String getQuesType() {
return quesType;
}
public void setQuesType(String quesType) {
this.quesType = quesType;
}
public Double getStuQtScoreRate() {
return stuQtScoreRate;
}
public void setStuQtScoreRate(Double stuQtScoreRate) {
this.stuQtScoreRate = stuQtScoreRate;
}
public String getSubSubject() {
return subSubject;
}
public void setSubSubject(String subSubject) {
this.subSubject = subSubject;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
}
package com.example.pdfgenerator.Dto;
public class DtoAsw {
private String quesNo;
private String stuId;
private Double stuQuesAswTime;
private String subSubject;
public String getQuesNo() {
return quesNo;
}
public void setQuesNo(String quesNo) {
this.quesNo = quesNo;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public Double getStuQuesAswTime() {
return stuQuesAswTime;
}
public void setStuQuesAswTime(Double stuQuesAswTime) {
this.stuQuesAswTime = stuQuesAswTime;
}
public String getSubSubject() {
return subSubject;
}
public void setSubSubject(String subSubject) {
this.subSubject = subSubject;
}
}
package com.example.pdfgenerator.Dto;
public class Params {
private String province;
private String region;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
package com.example.pdfgenerator.Dto;
import lombok.Data;
import java.util.List;
@Data
public class ProvinceAllTypeClass {
private List<BasicReportParameters> synthesisSchoolSubjectReportParameters;
private List<BasicReportParameters> synthesisSchoolReportParameters;
private List<ClassBasicReportParameters> synthesisClassSubjectReportParameters;
private List<ClassBasicReportParameters> synthesisClassReportParameters;
private String provinceName;
}
package com.example.pdfgenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PdfGeneratorApplication {
public static void main(String[] args) {
SpringApplication.run(PdfGeneratorApplication.class, args);
}
}
package com.example.pdfgenerator.config;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CommonConfig {
@Bean(name = "cosClient")
public COSClient cosClient() {
COSCredentials cred = new BasicCOSCredentials("AKID61zliQDpBOgqALHvLl25sRmvnV9cohPt", "TkqtgCUaYJhx1rTpztY2LQRO9h2pPmun");
Region region = new Region("ap-beijing");
ClientConfig clientConfig = new ClientConfig(region);
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}
}
package com.example.pdfgenerator.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
/**
* @author yn
* @version 1.0
* @date 2020/9/15 15:30
*/
@Configuration
public class MyDataSourceConfig {
private static JdbcTemplate reportJdbcTemplate;
private static JdbcTemplate mkReportJdbcTemplate;
private static JdbcTemplate campsiteJdbcTemplate;
@PostConstruct
private void init() {
initReport();
initMkReport();
// initCampCenter();
}
public static JdbcTemplate getReportJdbcTemplate(){
return reportJdbcTemplate;
}
public static JdbcTemplate getMkReportJdbcTemplate() { return mkReportJdbcTemplate; }
public static JdbcTemplate getCampsiteJdbcTemplate(){
return campsiteJdbcTemplate;
}
public DataSource initReport(){
System.err.println("print init reportSource...");
//外网
String url = "jdbc:mysql://192.168.0.46:3306/tempnew?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8";
DruidDataSource dataSource = getDataSource(url);
dataSource.setUsername("jiru");
dataSource.setPassword("Jiru@20231026");
reportJdbcTemplate = new JdbcTemplate(dataSource);
return dataSource;
}
public DataSource initMkReport(){
System.err.println("print init mkSource...");
//外网
String url = "jdbc:mysql://192.168.0.11:3306/boye_20240911?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8";
DruidDataSource dataSource = getDataSource(url);
dataSource.setUsername("root");
dataSource.setPassword("Thu#DSS#0419");
mkReportJdbcTemplate = new JdbcTemplate(dataSource);
return dataSource;
}
// public DataSource initCampCenter(){
// System.err.println("print init campsiteSource...");
// //外网
// String url = "jdbc:mysql://10.0.0.8:3306/yingdi?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8";
// DruidDataSource dataSource = getDataSource(url);
// dataSource.setUsername("root");
// dataSource.setPassword("sunny@campcenter1017");
// reportJdbcTemplate = new JdbcTemplate(dataSource);
// return dataSource;
// }
private DruidDataSource getDataSource(String url) {
DruidDataSource dataSource = new DruidDataSource();
//设置连接池里面的连接连接池的必要参数
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername("thussat");
dataSource.setPassword("Thussat@2020");
dataSource.setInitialSize(8);
dataSource.setMaxActive(20);
dataSource.setMinIdle(5);
dataSource.setMaxWait(60000);
dataSource.setDefaultAutoCommit(true);
dataSource.setValidationQuery("SELECT 1 FROM DUAL");
dataSource.setValidationQueryTimeout(60000);
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setTestWhileIdle(true);
dataSource.setTimeBetweenEvictionRunsMillis(60000);
dataSource.setMinEvictableIdleTimeMillis(300000);
dataSource.setBreakAfterAcquireFailure(false);//出错时不把正在提交的数据抛弃
return dataSource;
}
}
package com.example.pdfgenerator.controller;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
public class CosController {
@Autowired
private COSClient cosClient;
private static final String BUCKET_NAME = "schoolreportpdf-1317275686";
@GetMapping("/download-folder")
public ResponseEntity<InputStreamResource> downloadFolder(@RequestParam(required = false ,defaultValue = "class/basic/改革/山东省/东平县高级中学") String folderPath) throws IOException {
//删除目录下面的服务器本地上面的zip文件
// List objects in the folder
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(BUCKET_NAME)
.withPrefix(folderPath);
ObjectListing listObjectsResponse = cosClient.listObjects(listObjectsRequest);
List<COSObjectSummary> objectSummaries = listObjectsResponse.getObjectSummaries();
// Create a temporary file for ZIP
File tempZipFile = File.createTempFile("zipFile", ".zip");
// Create ZIP file
try (FileOutputStream fos = new FileOutputStream(tempZipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (COSObjectSummary objectSummary : objectSummaries) {
String key = objectSummary.getKey();
String fileName = key.substring(key.lastIndexOf('/') + 1);
COSObject s3Object = cosClient.getObject(BUCKET_NAME, key);
try (COSObjectInputStream inputStream = s3Object.getObjectContent()) {
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
}
}
var resource = new InputStreamResource(new ByteArrayInputStream(java.nio.file.Files.readAllBytes(tempZipFile.toPath())));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"zipFile.zip\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}finally {
if(tempZipFile!=null&&tempZipFile.exists()){
tempZipFile.delete();
}
}
}
}
package com.example.pdfgenerator.controller;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ListObjectsRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Controller
public class CosDownloadZipFileController {
@Autowired
private COSClient cosClient;
@GetMapping("/getClassReportPdfZipFile")
public ResponseEntity<FileSystemResource> CosClientGen(@RequestParam("region")String region,@RequestParam("province")String province,@RequestParam("school")String school) throws IOException {
String bucketName = "schoolreportpdf-1317275686";
String folderName = "class/"+region+"/"+province+"/"+school;
String localPath = "";
String finishPath = "";
String osName = System.getProperty("os.name").toLowerCase();
// 根据操作系统设置目录
if (osName.contains("win")) {
// Windows系统
localPath = "D:/classZipInit/"+school;
finishPath = "D:/classZipFinish/"+school+".zip";
} else if (osName.contains("nix") || osName.contains("nux")) {
// Linux 系统
localPath = "/customDir/classZipInit/"+school;
finishPath = "/customDir/classZipFinish/"+school+".zip";
}
try {
downloadFolder(cosClient, bucketName, folderName, localPath);
zipDirectory(localPath,finishPath);
} catch (Exception e){
e.printStackTrace();
}finally {
deleteDirectory(Paths.get(localPath));
return downloadZip(finishPath);
}
}
private static void downloadFolder(COSClient cosClient, String bucketName, String folderName, String localPath) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(folderName);
for (COSObjectSummary objectSummary : cosClient.listObjects(listObjectsRequest).getObjectSummaries()) {
String key = objectSummary.getKey();
String localFilePath = localPath +"/"+key.substring(folderName.length());
downloadFile(cosClient, bucketName, key, localFilePath);
}
}
private static void downloadFile(COSClient cosClient, String bucketName, String key, String localFilePath) {
try {
File localFile = new File(localFilePath);
localFile.getParentFile().mkdirs(); // 创建目录
InputStream inputStream = cosClient.getObject(new GetObjectRequest(bucketName, key)).getObjectContent();
try (FileOutputStream fos = new FileOutputStream(localFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
System.out.println("Downloaded: " + key);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void zipDirectory(String sourceFolder, String zipFilePath) throws IOException {
Path zipFile = Paths.get(zipFilePath);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile.toFile()))) {
Path srcPath = Paths.get(sourceFolder);
Files.walk(srcPath)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(srcPath.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path,zos);
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
public static void deleteZipFile(String filePath) throws IOException {
Path path = Paths.get(filePath);
Files.delete(path);
}
public static void deleteDirectory(Path path) throws IOException {
// 使用Files.walkFileTree来遍历文件夹
Files.walk(path)
.sorted((p1, p2) -> p2.compareTo(p1)) // 反向排序以确保从子文件夹到父文件夹删除
.forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
System.err.println("无法删除文件: " + p + " " + e.getMessage());
}
});
}
public ResponseEntity<FileSystemResource> downloadZip(String zipPath) throws UnsupportedEncodingException {
File zipFile = new File(zipPath); // 你的ZIP文件路径
if (!zipFile.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
FileSystemResource resource = new FileSystemResource(zipFile);
HttpHeaders headers = new HttpHeaders();
System.out.println(zipFile.getName());
headers.add("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(zipFile.getName(), "UTF-8")+"\"");
new Thread(() -> {
try {
// 等待响应发送后再删除文件
Thread.sleep(2000); // 可根据需要调整延迟
if (zipFile.exists()) {
zipFile.delete();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
return ResponseEntity.ok()
.headers(headers)
.contentLength(zipFile.length())
.contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
server:
port: 8059
spring:
datasource:
url: jdbc:mysql://192.168.0.46:3306/temp_test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: jiru
password: Jiru@20231026
druid:
initial-size: 5
max-active: 200
min-idle: 5
max-wait: 6000
redis:
host: 192.168.0.4
port: 6379
password: Thussat@2023
database: 101
lettuce:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
token :
prefix: authentication
redis: "user_name:"
verification :
prefix: "login_verification:"
package com.example.pdfgenerator.CampsitePackages;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SpringBootTest
public class CampsiteTestClass {
@Test
public void ExcelExport(){
String code = "1A027422328";
// 定义正则表达式
String regex = "^\\d[A-Z]\\d{9}$";
// 编译正则表达式
Pattern pattern = Pattern.compile(regex);
// 创建匹配器
Matcher matcher = pattern.matcher(code);
// 检查是否匹配
if (matcher.matches()) {
System.out.println("1");
} else {
System.out.println("2");
}
}
}
package com.example.pdfgenerator;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ciModel.common.MediaOutputObject;
import com.qcloud.cos.model.ciModel.job.FileCompressConfig;
import com.qcloud.cos.model.ciModel.job.FileProcessJobResponse;
import com.qcloud.cos.model.ciModel.job.FileProcessJobType;
import com.qcloud.cos.model.ciModel.job.FileProcessRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@SpringBootTest
public class CosClientDownloadZipFile {
@Autowired
private COSClient cosClient;
@Test
public void CosClientGen() throws IOException {
String bucketName = "schoolreportpdf-1317275686";
String folderName = "class/basic/改革/山东省/东平县高级中学";
String localPath = "D:/classZipInit/东平县高级中学/";
String finishPath = "D:/classZipFinish/东平县高级中学.zip";
try {
downloadFolder(cosClient, bucketName, folderName, localPath);
zipDirectory(localPath,finishPath);
} finally {
cosClient.shutdown();
}
}
private static void downloadFolder(COSClient cosClient, String bucketName, String folderName, String localPath) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(folderName);
for (COSObjectSummary objectSummary : cosClient.listObjects(listObjectsRequest).getObjectSummaries()) {
String key = objectSummary.getKey();
String localFilePath = localPath + key.substring(folderName.length());
downloadFile(cosClient, bucketName, key, localFilePath);
}
}
private static void downloadFile(COSClient cosClient, String bucketName, String key, String localFilePath) {
try {
File localFile = new File(localFilePath);
localFile.getParentFile().mkdirs(); // 创建目录
InputStream inputStream = cosClient.getObject(new GetObjectRequest(bucketName, key)).getObjectContent();
try (FileOutputStream fos = new FileOutputStream(localFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
System.out.println("Downloaded: " + key);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void zipDirectory(String sourceFolder, String zipFilePath) throws IOException {
Path zipFile = Paths.get(zipFilePath);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile.toFile()))) {
Path srcPath = Paths.get(sourceFolder);
Files.walk(srcPath)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(srcPath.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
@Test
public void delDirectory(){
String directoryPath = "D:/classZipInit/东平县高级中学"; // 替换为你的文件夹路径
try {
deleteDirectory(Paths.get(directoryPath));
System.out.println("文件夹已成功删除");
} catch (IOException e) {
System.err.println("删除文件夹时出错: " + e.getMessage());
}
}
public static void deleteDirectory(Path path) throws IOException {
// 使用Files.walkFileTree来遍历文件夹
Files.walk(path)
.sorted((p1, p2) -> p2.compareTo(p1)) // 反向排序以确保从子文件夹到父文件夹删除
.forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
System.err.println("无法删除文件: " + p + " " + e.getMessage());
}
});
}
@Test
public void delZipFile() {
String zipFilePath = "D:/classZipFinish/东平县高级中学.zip"; // 替换为你的ZIP文件路径
try {
deleteZipFile(zipFilePath);
System.out.println("ZIP文件已成功删除");
} catch (IOException e) {
System.err.println("删除ZIP文件时出错: " + e.getMessage());
}
}
public static void deleteZipFile(String filePath) throws IOException {
Path path = Paths.get(filePath);
Files.delete(path);
}
@Test
public void DownloadZipFile(){
//1.创建任务请求对象
FileProcessRequest request=new FileProcessRequest();
//2.添加请求参数 参数详情请见 API 接口文档
request.setBucketName("schoolreportpdf-1317275686");
request.setTag(FileProcessJobType.FileCompress);
FileCompressConfig fileCompressConfig=request.getOperation().getFileCompressConfig();
fileCompressConfig.setFormat("zip");
fileCompressConfig.setFlatten("0");
fileCompressConfig.setPrefix("class/basic/改革/山东省/东平县高级中学/");
// List<String> keyList=fileCompressConfig.getKey();
// keyList.add("mark/pic-1.jpg");
// keyList.add("mark/pic-1.pdf");
MediaOutputObject output=request.getOperation().getOutput();
output.setBucket("schoolreportpdf-1317275686");
output.setRegion("ap-beijing");
output.setObject("output/demo.zip");
//3.调用接口,获取任务响应对象
FileProcessJobResponse response= cosClient.createFileProcessJob(request);
response.getJobDetail().getJobId();
FileProcessRequest queryRequest = new FileProcessRequest();
queryRequest.setBucketName("schoolreportpdf-1317275686");
queryRequest.setJobId(response.getJobDetail().getJobId());
FileProcessJobResponse queryResponse = null;
do{
queryResponse = cosClient.describeFileProcessJob(queryRequest);
}while(!queryResponse.getJobDetail().getState().equals("SUCCESS"));
System.out.println(response.getJobDetail().getMessage());
}
}
package com.example.pdfgenerator.DataProcessing;
import com.example.pdfgenerator.DtoKn;
import com.example.pdfgenerator.config.MyDataSourceConfig;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@SpringBootTest
public class Garbge {
// @Test
public void meanRegion(){
JdbcTemplate jdbcTemplate = MyDataSourceConfig.getReportJdbcTemplate();
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
String sql = "select region from base_school_subject_tda20240919 where subject_type = '常规' group by region";
List<String> regions = jdbcTemplate.queryForList(sql, String.class);
for (String region : regions) {
meanRegionTest(region,namedParameterJdbcTemplate);
}
}
public void meanRegionTest(String region, NamedParameterJdbcTemplate reportJdbcTemplate){
String sql = "select \n" +
"knowledge,\n" +
"stu_kn_score_rate,\n" +
"sub_subject,\n" +
"stu_id\n" +
"from\n" +
"base_student_knowledge_tda20240919\n" +
"where\n" +
"region = '"+region+"' and subject_type = '常规'";
List<DtoKn> list = reportJdbcTemplate.query(sql,new BeanPropertyRowMapper<>(DtoKn.class));
Map<String, List<DtoKn>> collect = list.stream().collect(Collectors.groupingBy(DtoKn::getSubSubject));
for (String subject : collect.keySet()) {
List<DtoKn> subjectLis =collect.get(subject);
String sql2 = "select \n" +
"stu_id\n" +
"from \n" +
"base_student_subject_tda20240919\n" +
"where\n" +
"sub_subject = '"+subject+"'\n" +
"and\n" +
"subject_type = '常规'\n" +
"and\n" +
"region = '"+region+"'\n" +
"and \n" +
"stu_subject_score_rate_region_pct_rank >= 0.73";
List<String> ids = reportJdbcTemplate.queryForList(sql2,new HashMap<>(),String.class);
List<DtoKn> collect1 = subjectLis.stream().filter(x -> ids.contains(x.getStuId())).collect(Collectors.toList());
Map<String, List<DtoKn>> collect2 = collect1.stream().collect(Collectors.groupingBy(DtoKn::getKnowledge));
for (String knowledge : collect2.keySet()) {
//优生知识点层级
List<DtoKn> dataList = collect2.get(knowledge);
Double sumRate = dataList.stream().mapToDouble(DtoKn::getStuKnScoreRate).sum();
Double resultRate = sumRate/dataList.size();
if(Double.isNaN(resultRate)||Double.isInfinite(resultRate)){
resultRate = 0.0;
}
HashMap paramsYi = new HashMap(){{
put("subSubject",subject);
put("knowledge",knowledge);
put("region",region);
}};
paramsYi.put("rate",resultRate);
reportJdbcTemplate.update("insert into knowledge_region_excellent20240919(sub_subject,knowledge,region,rate) value (:subSubject,:knowledge,:region,:rate)",new MapSqlParameterSource(paramsYi));
}
}
}
}
package com.example.pdfgenerator.DataProcessing;
import com.example.pdfgenerator.Dto.Params;
import com.example.pdfgenerator.DtoKn;
import com.example.pdfgenerator.config.MyDataSourceConfig;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@SpringBootTest
public class NumberTwo {
// @Test
public void ProvinceExKnow(){
JdbcTemplate jdbcTemplate = MyDataSourceConfig.getReportJdbcTemplate();
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
String sql = "select region,province from base_school_subject_tda20240919 where subject_type = '常规' group by region,province";
List<Params> paramsList = namedParameterJdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Params.class));
for (Params param : paramsList) {
provinceExe(param.getRegion(),param.getProvince(),namedParameterJdbcTemplate);
}
}
public void provinceExe(String region,String province,NamedParameterJdbcTemplate reportTemplate){
String sql = "select \n" +
"knowledge,\n" +
"stu_kn_score_rate,\n" +
"sub_subject,\n" +
"stu_id\n" +
"from\n" +
"base_student_knowledge_tda20240919\n" +
"where\n" +
"region = '"+region+"' and subject_type = '常规' and province = '"+province+"'";
List<DtoKn> list = reportTemplate.query(sql,new HashMap<>(),new BeanPropertyRowMapper<>(DtoKn.class));
Map<String, List<DtoKn>> collect = list.stream().collect(Collectors.groupingBy(DtoKn::getSubSubject));
for (String subject : collect.keySet()) {
//单个科目
List<DtoKn> data = collect.get(subject);
String sql3 = "\t\t\t\tSELECT\n" +
"\t\t\tstu_id \n" +
"\t\tFROM\n" +
"\t\t\tbase_student_subject_tda20240919 \n" +
"\t\tWHERE\n" +
"\t\t\tprovince = '"+province+"' \n" +
"\t\t\tAND region = '"+region+"' \n" +
"\t\t\tAND subject_type = '常规' \n" +
"\t\t\tAND exam_id = 'TDA20240919G2' \n" +
"\t\t\tAND sub_subject = '"+subject+"' \n" +
"\t\t\tAND stu_subject_score_rate_province_pct_rank >= (1-0.27) ";
List<String> ids = reportTemplate.queryForList(sql3,new HashMap<>(),String.class);
List<DtoKn> collect1 = data.stream().filter(x -> ids.contains(x.getStuId())).collect(Collectors.toList());
Map<String, List<DtoKn>> collect2 = collect1.stream().collect(Collectors.groupingBy(DtoKn::getKnowledge));
for (String knowledge : collect2.keySet()) {
List<DtoKn> goods = collect2.get(knowledge);
Double sumRate = goods.stream().mapToDouble(DtoKn::getStuKnScoreRate).sum();
Double result = sumRate/goods.size();
if(Double.isNaN(result)||Double.isInfinite(result)){
result = 0.0;
}
HashMap paramsYi = new HashMap(){{
put("subSubject",subject);
put("knowledge",knowledge);
put("region",region);
put("province",province);
}};
paramsYi.put("rate",result);
reportTemplate.update("insert into knowledge_province_excellent20240919(sub_subject,knowledge,region,rate,province) value (:subSubject,:knowledge,:region,:rate,:province)",new MapSqlParameterSource(paramsYi));
}
}
}
}
package com.example.pdfgenerator;
public class DeFenLu {
private String region;
private String subSubject;
private String subjectType;
private String examId;
private String quesNo;
private Double regionQuesStandardDifficulty;
private Double stuQuesScore;
private Double quesMaxScore;
private String stuId;
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getSubSubject() {
return subSubject;
}
public void setSubSubject(String subSubject) {
this.subSubject = subSubject;
}
public String getSubjectType() {
return subjectType;
}
public void setSubjectType(String subjectType) {
this.subjectType = subjectType;
}
public String getExamId() {
return examId;
}
public void setExamId(String examId) {
this.examId = examId;
}
public String getQuesNo() {
return quesNo;
}
public void setQuesNo(String quesNo) {
this.quesNo = quesNo;
}
public Double getRegionQuesStandardDifficulty() {
return regionQuesStandardDifficulty;
}
public void setRegionQuesStandardDifficulty(Double regionQuesStandardDifficulty) {
this.regionQuesStandardDifficulty = regionQuesStandardDifficulty;
}
public Double getStuQuesScore() {
return stuQuesScore;
}
public void setStuQuesScore(Double stuQuesScore) {
this.stuQuesScore = stuQuesScore;
}
public Double getQuesMaxScore() {
return quesMaxScore;
}
public void setQuesMaxScore(Double quesMaxScore) {
this.quesMaxScore = quesMaxScore;
}
}
package com.example.pdfgenerator;
public class DtoKn {
private String knowledge;
private Double stuKnScoreRate;
private String subSubject;
private String stuId;
public String getKnowledge() {
return knowledge;
}
public void setKnowledge(String knowledge) {
this.knowledge = knowledge;
}
public Double getStuKnScoreRate() {
return stuKnScoreRate;
}
public void setStuKnScoreRate(Double stuKnScoreRate) {
this.stuKnScoreRate = stuKnScoreRate;
}
public String getSubSubject() {
return subSubject;
}
public void setSubSubject(String subSubject) {
this.subSubject = subSubject;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class DimensionDto {
private String sortNum;
private String dimensionName;
private String questionIndex;
private Double kcpl;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class ProvinceDifficultyAvgScoreMean {
private String province;
private String region;
private Double scoreMean;
private String difficulty;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class ProvinceExcellentDifficulty {
private String zkzNum;
private String score;
private String percentG;
private String difficulty;
private Double scoreMean;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class QuesTypeDto {
private String zkzNum;
private String quesIndex;
private Double score;
private Double fullScore;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class SchoolDifficultyPreview {
private String region;
private String school;
private String zkzNum;
private String name;
private String subSubject;
private String quesId;
private String quesIndex;
private Double score;
private Double fullScore;
private String nandu;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class SchoolQuesTypeScoreMean {
private String quesType;
private String school;
private String region;
private String province;
private String quesTypeScoreMeanAvg;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class StudentDifficultyAvgScoreMean {
private String name;
private String difficulty;
private Double scoreMean;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class StudentDimension {
private String zkzNum;
private String quesIndex;
private Double score;
private Double fullScore;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class StudentDimensionScoreMean {
private String zkzNum;
private String sortNum;
private String dimensionName;
private Double scoreMean;
private Double fullScore;
private Double kcpl;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class StudentHistogram {
private String zkzNum;
private String studentName;
private String type;
private String score;
private String provincePercent;
private String countryPercent;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class StudentQuesTypeScoreMean {
private String zkzNum;
private String quesType;
private Double quesScoreMean;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class TempStudentScoreMean {
private String quesType;
private String ZkzNum;
private Double ScoreMean;
}
package com.example.pdfgenerator.MKReport.BeanProject;
import lombok.Data;
@Data
public class thQuesTypeAnalysis {
private String subSubject;
private String quesTypeName;
private String quesIndex;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment