8 Commits
develop ... RC2

37 changed files with 2328 additions and 13610 deletions

View File

@@ -1,67 +0,0 @@
image: harbor.fjy8018.top:8883/library/docker:19.03
variables:
MAVEN_CLI_OPTS: "-s .m2/settings.xml --batch-mode -Dmaven.test.skip=true"
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
DOCKER_DRIVER: overlay
DOCKER_HOST: tcp://localhost:2375
DOCKER_TLS_CERTDIR: ""
SPRING_PROFILES_ACTIVE: docker
IMAGE_VERSION: "V2.9.13"
DOCKER_REGISTRY_MIRROR: "https://clayphwh.mirror.aliyuncs.com"
stages:
- test
- package
- deploy
maven-build:
image: harbor.fjy8018.top:8883/library/maven:3-jdk-8
stage: test
retry: 2
script:
- mvn $MAVEN_CLI_OPTS clean package -U -B -T 2C
artifacts:
expire_in: 1 week
paths:
- target/*.jar
maven-scan:
stage: test
retry: 2
image: harbor.fjy8018.top:8883/library/maven:3-jdk-8
script:
- mvn $MAVEN_CLI_OPTS verify sonar:sonar
maven-deploy:
stage: deploy
retry: 2
image: harbor.fjy8018.top:8883/library/maven:3-jdk-8
script:
- mvn $MAVEN_CLI_OPTS deploy
docker-harbor-build:
stage: package
retry: 2
image:
name: harbor.fjy8018.top:8883/google_container/kaniko-executor:debug
entrypoint: [""]
script:
- echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
- /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile --destination $CI_REGISTRY_IMAGE:$IMAGE_VERSION
deploy_live:
image: harbor.fjy8018.top:8883/offical/kubectl:v1.14.0
stage: deploy
retry: 2
environment:
name: prod
url: https://cms.fjy8018.xin
script:
- kubectl version
- kubectl get pods -n cms
- cd manifests/
- sed -i "s/__IMAGE_VERSION_SLUG__/${IMAGE_VERSION}/" deployment.yaml
- kubectl apply -f deployment.yaml
- kubectl get pods -n cms

View File

@@ -1,83 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<mirrors>
<mirror>
<id>fjy-nexus</id>
<!--*指的是访问任何仓库都使用我们的私服-->
<mirrorOf>central</mirrorOf>
<name>Nexus myself</name>
<url>http://192.168.1.30:8081/repository/maven-public/</url>
</mirror>
</mirrors>
<servers>
<server>
<id>maven-central</id>
<username>${env.MAVEN_USER}</username>
<password>${env.MAVEN_PASSWORD}</password>
</server>
<server>
<id>maven-public</id>
<username>${env.MAVEN_USER}</username>
<password>${env.MAVEN_PASSWORD}</password>
</server>
<server>
<id>maven-snapshots</id>
<username>${env.MAVEN_USER}</username>
<password>${env.MAVEN_PASSWORD}</password>
</server>
</servers>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.host.url>
http://192.168.1.27:19000
</sonar.host.url>
</properties>
</profile>
<profile>
<id>fjy-nexus</id>
<!-- 远程仓库列表 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>maven-public</id>
<name>maven-public</name>
<url>http://192.168.1.30:8081/repository/maven-public/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<!--插件库地址-->
<pluginRepository>
<id>maven-public</id>
<url>http://192.168.1.30:8081/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>

View File

@@ -1,11 +0,0 @@
FROM harbor.fjy8018.top:8883/library/openjdk:8-jre
MAINTAINER fjy8018 fjy8018@gmail.com
COPY target/spring-V2.9.13.jar /cms-springboot.jar
# 设置时区默认为UTC
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' > /etc/timezone
ENTRYPOINT ["java","-jar","/cms-springboot.jar","--spring.profiles.active=k8s"]
EXPOSE 8080

373
LICENSE
View File

@@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -1,7 +1,4 @@
# 班级作业提交系统 # 班级作业提交系统
[![pipeline status](http://gitlab.fjy8018.top:8099/fjy8018/cms/badges/master/pipeline.svg)](http://gitlab.fjy8018.top:8099/fjy8018/gcb-invest/commits/master)
[系统介绍和详细截图](https://www.fjy8018.xin/index.php/archives/100/) [系统介绍和详细截图](https://www.fjy8018.xin/index.php/archives/100/)
## 起因 ## ## 起因 ##
@@ -10,6 +7,8 @@
## 系统成品 ## ## 系统成品 ##
[作业提交系统正式版(点击访问正式版网站本体)][1] [作业提交系统正式版(点击访问正式版网站本体)][1]
[作业提交系统测试服务器版本(点击访问测试服务器网站本体)][2]
[系统使用说明(点击访问)][3] [系统使用说明(点击访问)][3]
## 系统优点 ## ## 系统优点 ##
@@ -31,4 +30,4 @@
[1]: https://cms.fjy8018.xin/cms/index [1]: https://cms.fjy8018.xin/cms/index
[2]: http://s2.fjy8018.top:8085/cms/index [2]: http://s2.fjy8018.top:8085/cms/index
[3]: https://blog.fjy8018.top/index.php/archives/99/ [3]: http://home.fjy8018.top:8090/blog/index.php/archives/99/

File diff suppressed because it is too large Load Diff

View File

@@ -1,76 +0,0 @@
apiVersion: v1
kind: Namespace
metadata:
name: cms
---
apiVersion: v1
kind: Secret
metadata:
name: harbor-login
namespace: cms
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: ewoJImF1dGhzIjogewoJCSJoYXJib3IuZmp5ODAxOC50b3A6ODg4MyI6IHsKCQkJImF1dGgiOiAiYXpoek9rczRjMmhoY21KdmNnPT0iCgkJfQoJfQp9
---
#deploy
apiVersion: apps/v1
kind: Deployment
metadata:
name: cms
namespace: cms
labels:
app: cms
spec:
selector:
matchLabels:
app: cms
replicas: 1
template:
metadata:
labels:
app: cms
spec:
imagePullSecrets:
- name: harbor-login
containers:
- name: cms
imagePullPolicy: Always
image: harbor.fjy8018.top:8883/fjy8018/cms:__IMAGE_VERSION_SLUG__
ports:
- containerPort: 8080
---
#service
apiVersion: v1
kind: Service
metadata:
name: cms
namespace: cms
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8080
selector:
app: cms
type: ClusterIP
---
#ingress
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: cms
namespace: cms
spec:
rules:
- host: cms.fjy8018.xin
http:
paths:
- path: /
backend:
serviceName: cms
servicePort: 80

View File

@@ -1,21 +0,0 @@
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cms-gitlab-ci
namespace: cms
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
name: cms-gitlab-role
namespace: cms
subjects:
- kind: ServiceAccount
name: cms-gitlab-ci
namespace: cms
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: admin

101
pom.xml
View File

@@ -5,7 +5,7 @@
<groupId>com.fjy</groupId> <groupId>com.fjy</groupId>
<artifactId>spring</artifactId> <artifactId>spring</artifactId>
<version>V2.9.13</version> <version>V3.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>spring</name> <name>spring</name>
@@ -14,7 +14,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version> <version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
@@ -22,7 +22,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<skipTests>true</skipTests>
</properties> </properties>
<dependencies> <dependencies>
@@ -45,6 +44,7 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
@@ -54,7 +54,12 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
<version>1.5.9.RELEASE</version> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
@@ -73,26 +78,36 @@
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.6</version> <version>2.6</version>
</dependency> </dependency>
<!--https://github.com/osiegmar/logback-gelf-->
<dependency>
<groupId>de.siegmar</groupId>
<artifactId>logback-gelf</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
<distributionManagement> <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<repository> <dependency>
<id>maven-public</id> <groupId>commons-net</groupId>
<name>Release Deploy</name> <artifactId>commons-net</artifactId>
<url>http://192.168.1.30:8081/repository/maven-releases/</url> <version>3.6</version>
</repository> </dependency>
<snapshotRepository>
<id>maven-snapshots</id> <dependency>
<name>Snapshot Deploy</name> <groupId>ch.ethz.ganymed</groupId>
<url>http://192.168.1.30:8081/repository/maven-snapshots/</url> <artifactId>ganymed-ssh2</artifactId>
</snapshotRepository> <version>build210</version>
</distributionManagement> </dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
</dependencies>
<build> <build>
@@ -103,4 +118,44 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project> </project>

188
sql.sql
View File

@@ -1,9 +1,4 @@
DROP DATABASE IF EXISTS db_imis2; CREATE DATABASE db_imis2
CREATE DATABASE db_imis2;
use db_imis2;
GRANT ALL ON db_imis2.* TO imis2@'%' IDENTIFIED BY '2015imis2';
FLUSH PRIVILEGES;
CREATE TABLE tb_user CREATE TABLE tb_user
( (
@@ -15,13 +10,11 @@ CREATE TABLE tb_user
colrealname VARCHAR(20) NOT NULL colrealname VARCHAR(20) NOT NULL
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
CREATE UNIQUE INDEX tb_user_colname_uindex ON tb_user (colname); CREATE UNIQUE INDEX tb_user_colname_uindex ON tb_user (colname);
INSERT INTO tb_user (colname, colpassword, colemail, colstudentno, colrealname) INSERT INTO tb_user (colname, colpassword, colemail, colstudentno, colrealname) VALUES ('root','-4e4hc3pvvu8n0rj1uena76948n37q23r','root@gmail.com','00001','FJY');
VALUES ('root', '-4e4hc3pvvu8n0rj1uena76948n37q23r', 'root@gmail.com', '00001', 'FJY'); SELECT * FROM tb_user;
SELECT *
FROM tb_user;
CREATE TABLE tb_file CREATE TABLE tb_file
@@ -34,13 +27,9 @@ CREATE TABLE tb_file
colfilename VARCHAR(255), colfilename VARCHAR(255),
colfilesize VARCHAR(32), colfilesize VARCHAR(32),
colfilepath VARCHAR(128) colfilepath VARCHAR(128)
) ENGINE = InnoDB )ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci;
CHARSET = utf8mb4 ALTER TABLE tb_file COMMENT = '文件表';
COLLATE utf8mb4_general_ci; ALTER TABLE tb_file ADD CONSTRAINT FK_fileuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid);
ALTER TABLE tb_file
COMMENT = '文件表';
ALTER TABLE tb_file
ADD CONSTRAINT FK_fileuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid);
CREATE TABLE tb_admin CREATE TABLE tb_admin
( (
@@ -50,10 +39,9 @@ CREATE TABLE tb_admin
CONSTRAINT FK_adminuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid) CONSTRAINT FK_adminuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_admin ALTER TABLE tb_admin COMMENT = '管理员表';
COMMENT = '管理员表';
CREATE TABLE tb_student CREATE TABLE tb_student
( (
@@ -61,11 +49,8 @@ CREATE TABLE tb_student
coluserid INT(10), coluserid INT(10),
coltime VARCHAR(128) NOT NULL, coltime VARCHAR(128) NOT NULL,
CONSTRAINT FK_sutdentuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid) CONSTRAINT FK_sutdentuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid)
) ENGINE = InnoDB )ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci;
CHARSET = utf8mb4 ALTER TABLE tb_student COMMENT = '学生表';
COLLATE utf8mb4_general_ci;
ALTER TABLE tb_student
COMMENT = '学生表';
CREATE TABLE tb_teacher CREATE TABLE tb_teacher
( (
@@ -73,11 +58,8 @@ CREATE TABLE tb_teacher
coluserid INT(10), coluserid INT(10),
coltime VARCHAR(128) NOT NULL, coltime VARCHAR(128) NOT NULL,
CONSTRAINT FK_teacheruser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid) CONSTRAINT FK_teacheruser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid)
) ENGINE = InnoDB )ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci;
CHARSET = utf8mb4 ALTER TABLE tb_teacher COMMENT = '老师表';
COLLATE utf8mb4_general_ci;
ALTER TABLE tb_teacher
COMMENT = '老师表';
CREATE TABLE tb_log CREATE TABLE tb_log
( (
@@ -89,8 +71,8 @@ CREATE TABLE tb_log
CONSTRAINT FK_loguser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid) CONSTRAINT FK_loguser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_log ALTER TABLE tb_log
COMMENT = '日志表'; COMMENT = '日志表';
@@ -103,16 +85,15 @@ CREATE TABLE tb_course
CONSTRAINT FK_teacherid FOREIGN KEY (teacherid) REFERENCES tb_teacher (teacherid) CONSTRAINT FK_teacherid FOREIGN KEY (teacherid) REFERENCES tb_teacher (teacherid)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_course ALTER TABLE tb_course COMMENT = '课程表';
COMMENT = '课程表';
CREATE TABLE tb_homework CREATE TABLE tb_homework
( (
workId INT(10) PRIMARY KEY AUTO_INCREMENT, workId INT(10) PRIMARY KEY AUTO_INCREMENT,
workName VARCHAR(128) NOT NULL, workName VARCHAR(128) NOT NULL,
workTime VARCHAR(128) NOT NULL, workTime VARCHAR(128) NOT NULL ,
colfileid INT(10), colfileid INT(10),
workFolder VARCHAR(255) NOT NULL, workFolder VARCHAR(255) NOT NULL,
courseNo INT(10), courseNo INT(10),
@@ -121,10 +102,9 @@ CREATE TABLE tb_homework
CONSTRAINT FK_courseNo FOREIGN KEY (courseNo) REFERENCES tb_course (courseNo) CONSTRAINT FK_courseNo FOREIGN KEY (courseNo) REFERENCES tb_course (courseNo)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_homework ALTER TABLE tb_homework COMMENT = '作业表';
COMMENT = '作业表';
CREATE TABLE tb_workstatus CREATE TABLE tb_workstatus
( (
@@ -136,10 +116,9 @@ CREATE TABLE tb_workstatus
CONSTRAINT FK_workId FOREIGN KEY (workId) REFERENCES tb_homework (workId) CONSTRAINT FK_workId FOREIGN KEY (workId) REFERENCES tb_homework (workId)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_workstatus ALTER TABLE tb_workstatus COMMENT = '作业提交状态表';
COMMENT = '作业提交状态表';
CREATE TABLE tb_feedback CREATE TABLE tb_feedback
( (
@@ -150,10 +129,9 @@ CREATE TABLE tb_feedback
CONSTRAINT FK_feedbackuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid) CONSTRAINT FK_feedbackuser FOREIGN KEY (coluserid) REFERENCES tb_user (coluserid)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_workstatus ALTER TABLE tb_workstatus COMMENT = '反馈信息表';
COMMENT = '反馈信息表';
CREATE TABLE tb_notice CREATE TABLE tb_notice
( (
@@ -164,27 +142,15 @@ CREATE TABLE tb_notice
CONSTRAINT FK_noticeuser FOREIGN KEY (adminid) REFERENCES tb_admin (adminid) CONSTRAINT FK_noticeuser FOREIGN KEY (adminid) REFERENCES tb_admin (adminid)
) )
ENGINE = InnoDB ENGINE = InnoDB
CHARSET = utf8mb4 CHARSET = utf8
COLLATE utf8mb4_general_ci; COLLATE utf8_general_ci;
ALTER TABLE tb_workstatus ALTER TABLE tb_workstatus COMMENT = '公告表';
COMMENT = '公告表';
CREATE TABLE tb_userque
(
coluserid INT(10) PRIMARY KEY,
colquestion VARCHAR(64),
colanswer VARCHAR(255)
)
ENGINE = InnoDB
CHARSET = utf8mb4
COLLATE utf8mb4_general_ci;
ALTER TABLE tb_userque
COMMENT = '用户问题表';
CREATE VIEW v_workdetail CREATE VIEW v_workdetail
AS AS
SELECT workId, SELECT
workId,
workName, workName,
workTime, workTime,
f.colfileid, f.colfileid,
@@ -192,64 +158,60 @@ SELECT workId,
c.courseName, c.courseName,
workRemark, workRemark,
h.workFolder h.workFolder
FROM tb_homework h, FROM tb_homework h, tb_course c, tb_file f
tb_course c, WHERE h.colfileid = f.colfileid AND h.courseNo = c.courseNo;
tb_file f
WHERE h.colfileid = f.colfileid
AND h.courseNo = c.courseNo;
CREATE VIEW v_log CREATE VIEW v_log
AS AS
SELECT logid, SELECT
logid,
colname, colname,
coltime, coltime ,
colip, colip ,
colheader colheader
FROM tb_log, FROM tb_log,tb_user
tb_user WHERE tb_user.coluserid = tb_log.coluserid;
WHERE tb_user.coluserid = tb_log.coluserid;
CREATE VIEW v_feedback CREATE VIEW v_feedback
AS AS
SELECT feedbackid, SELECT
feedbackid,
colname, colname,
feedbackContent, feedbackContent,
issueTime issueTime
FROM tb_feedback, FROM tb_feedback, tb_user
tb_user WHERE tb_user.coluserid = tb_feedback.coluserid;
WHERE tb_user.coluserid = tb_feedback.coluserid;
CREATE VIEW v_course CREATE VIEW v_course
AS AS
SELECT courseNo, SELECT
courseNo,
courseName, courseName,
courseTime, courseTime,
colrealname, colrealname,
colname colname
FROM tb_course, FROM tb_course, tb_teacher,tb_user
tb_teacher, WHERE tb_user.coluserid = tb_teacher.coluserid AND tb_teacher.teacherid=tb_course.teacherid;
tb_user
WHERE tb_user.coluserid = tb_teacher.coluserid
AND tb_teacher.teacherid = tb_course.teacherid;
CREATE VIEW v_homework CREATE VIEW v_homework
AS AS
SELECT workId, SELECT
workId,
workName, workName,
workTime, workTime,
colfileid, colfileid,
workFolder, workFolder,
courseName, courseName,
workRemark workRemark
FROM tb_homework, FROM tb_homework, tb_course
tb_course WHERE tb_homework.courseNo = tb_course.courseNo;
WHERE tb_homework.courseNo = tb_course.courseNo;
CREATE VIEW v_userfile CREATE VIEW v_userfile
AS AS
SELECT tb_file.colfileid, SELECT
colfileid,
coltime, coltime,
colip, colip,
colfilename, colfilename,
@@ -259,31 +221,29 @@ SELECT tb_file.colfileid,
workFolder, workFolder,
tb_user.colrealname, tb_user.colrealname,
colstudentno colstudentno
FROM tb_file, FROM tb_file, tb_user
tb_user, WHERE tb_user.coluserid = tb_file.coluserid;
tb_course,
tb_homework
WHERE tb_user.coluserid = tb_file.coluserid;
CREATE VIEW v_userinfo CREATE VIEW v_userinfo
AS AS
SELECT coluserid, SELECT
coluserid,
colname, colname,
colemail, colemail,
colstudentno, colstudentno,
colrealname colrealname
FROM tb_user; FROM tb_user;
CREATE VIEW v_userque CREATE VIEW v_userque
AS AS
SELECT tb_user.coluserid, SELECT
tb_user.coluserid,
colname, colname,
colquestion, colquestion,
colanswer, colanswer,
colrealname colrealname
FROM tb_userque, FROM tb_userque,tb_user
tb_user WHERE tb_user.coluserid=tb_userque.coluserid;
WHERE tb_user.coluserid = tb_userque.coluserid;

View File

@@ -11,7 +11,6 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger; import java.math.BigInteger;
import java.text.Format;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@@ -55,17 +54,7 @@ public class DataController {
@GetMapping("/home/findAllHomework") @GetMapping("/home/findAllHomework")
public List<VWorkDetail> findAllHomework() { public List<VWorkDetail> findAllHomework() {
Format f = new SimpleDateFormat("yyyy-MM-dd"); List<VWorkDetail> homeworks = workDetailService.findAll();
Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(today);
// 今天-2天因为数据库比较是">"号,即不包含当天
c.add(Calendar.DAY_OF_MONTH, -2);
Date yesterday = c.getTime();
List<VWorkDetail> homeworks = workDetailService.findAllVWorkDetailAfterTime(f.format(yesterday));
if (homeworks != null) { if (homeworks != null) {
return homeworks; return homeworks;
} }
@@ -110,17 +99,7 @@ public class DataController {
@GetMapping("/home/findallvhomework") @GetMapping("/home/findallvhomework")
public List<VHomework> findAllVHomework() { public List<VHomework> findAllVHomework() {
Format f = new SimpleDateFormat("yyyy-MM-dd"); List<VHomework> vHomeworks = homeworkService.findAllVHomework();
Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(today);
// 今天-2天因为数据库比较是">"号,即不包含当天
c.add(Calendar.DAY_OF_MONTH, -5);
Date yesterday = c.getTime();
List<VHomework> vHomeworks = homeworkService.findAllVHomeworkAfterTime(f.format(yesterday));
if (vHomeworks != null) { if (vHomeworks != null) {
return vHomeworks; return vHomeworks;
} }

View File

@@ -5,9 +5,12 @@ import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser; import com.fjy.spring.domain.TbUser;
import com.fjy.spring.enums.ResultEnum; import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException; import com.fjy.spring.exception.UserException;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.service.FileService; import com.fjy.spring.service.FileService;
import com.fjy.spring.service.LogService; import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.FtpOperationUtil;
import com.fjy.spring.untils.GetIPAddrUtil; import com.fjy.spring.untils.GetIPAddrUtil;
import com.fjy.spring.untils.RemoteCommandUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@@ -19,6 +22,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@@ -33,6 +37,9 @@ public class DeleteController {
@Autowired @Autowired
private FileService fileService; private FileService fileService;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
@Autowired @Autowired
private LogService logService; private LogService logService;
@@ -41,54 +48,59 @@ public class DeleteController {
@GetMapping("/home/findfile") @GetMapping("/home/findfile")
@ResponseBody @ResponseBody
public String findFilePath(@RequestParam(value = "fileid") Integer fileid){ public String findFilePath(@RequestParam(value = "fileid") Integer fileid) {
TbFile tbFile = new TbFile(); TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid); tbFile.setColfileid(fileid);
TbFile resfile = fileService.findFileById(tbFile); TbFile resfile = fileService.findFileById(tbFile);
return resfile.getColfilepath(); return resfile.getColfilepath();
} }
/** /**
* 删除文件,可以是文件或文件夹 * 删除文件,可以是文件或文件夹
*/ */
@RequestMapping("/home/filedelete") @RequestMapping("/home/filedelete")
@ResponseBody @ResponseBody
public boolean delete(@RequestParam(value = "fileid") Integer fileid)throws Exception { public boolean delete(@RequestParam(value = "fileid") Integer fileid) throws Exception {
TbFile tbFile = new TbFile(); TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid); tbFile.setColfileid(fileid);
TbFile resfile = fileService.findFileById(tbFile); TbFile resfile = fileService.findFileById(tbFile);
File filepath = new File(resfile.getColfilepath()); File filepath = new File(resfile.getColfilepath());
if (!filepath.exists()) {
log.error("删除文件失败:" + resfile.getColfilename() + "不存在!");
return false;
} else {
if (filepath.isFile()){
deleteFile(resfile.getColfilepath(),resfile.getColfileid());
return true;
}
else{
deleteDirectory(resfile.getColfilepath());
return true;
}
} return deleteFTPFile(resfile);
} }
/** /**
* 删除单个文件 * 删除单个文件
*/ */
public boolean deleteFile(String fileName,Integer fileid) { public boolean deleteFile(String fileName, Integer fileid) {
File file = new File(fileName); File file = new File(fileName);
TbFile tbFile = new TbFile(); TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid); tbFile.setColfileid(fileid);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) { if (file.exists() && file.isFile()) {
try {
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
System.out.println("【fileName】" + fileName);
boolean flagExistsFile = ftpOperationUtil.isExistsFile(fileName, tbFile.getColfilename());
if (flagExistsFile) {
boolean flagDeleteFile = ftpOperationUtil.deleteFile(fileName);
System.out.println("【flagDeleteFile】" + flagDeleteFile);
}
} catch (IOException e) {
e.printStackTrace();
}
if (file.delete()) { if (file.delete()) {
fileService.deleteFileById(tbFile); fileService.deleteFileById(tbFile);
log.info("删除单个文件" + fileName + "成功!"); log.info("删除单个文件" + fileName + "成功!");
TbUser user =(TbUser)request.getSession().getAttribute(USER_SESSION_KEY); TbUser user = (TbUser) request.getSession().getAttribute(USER_SESSION_KEY);
//写入日志信息 //写入日志信息
Date date = new Date(); Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -114,11 +126,38 @@ public class DeleteController {
} }
} }
public boolean deleteFTPFile(TbFile tbFile) throws IOException {
tbFile.setColfileid(tbFile.getColfileid());
String path = fileService.findFileById(tbFile).getColfilepath();
//直接删除
RemoteCommandUtil.deleteFile(path, remoteExecuteProperties);
fileService.deleteFileById(tbFile);
log.info("删除单个文件" + path + "成功!");
TbUser user = (TbUser) request.getSession().getAttribute(USER_SESSION_KEY);
//写入日志信息
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateNowStr = sdf.format(date);
TbLog log = new TbLog();
log.setUserid(user.getColuserid());
log.setColtime(dateNowStr);
log.setColheader("删除单个文件" + path + "成功!");
log.setRequestURL(request.getRequestURL().toString());
//解决nginx代理后IP地址获取问题
log.setColip(GetIPAddrUtil.getIpAddr(request));
logService.addLogRec(log);
return true;
}
/** /**
* 删除目录及目录下的文件 * 删除目录及目录下的文件
*功能暂时不开放 * 功能暂时不开放
* @param path *
* 要删除的目录的文件路径 * @param path 要删除的目录的文件路径
* @return 目录删除成功返回true否则返回false * @return 目录删除成功返回true否则返回false
*/ */
public boolean deleteDirectory(String path) { public boolean deleteDirectory(String path) {

View File

@@ -5,11 +5,15 @@ import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser; import com.fjy.spring.domain.TbUser;
import com.fjy.spring.enums.ResultEnum; import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException; import com.fjy.spring.exception.UserException;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.properties.ServerProperties; import com.fjy.spring.properties.ServerProperties;
import com.fjy.spring.service.FileService; import com.fjy.spring.service.FileService;
import com.fjy.spring.service.LogService; import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.LogUtil; import com.fjy.spring.untils.*;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -30,6 +34,7 @@ import java.util.zip.ZipOutputStream;
import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY; import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY;
@Controller @Controller
@Slf4j
public class DownLoadController { public class DownLoadController {
/** /**
* 服务器配置信息 * 服务器配置信息
@@ -37,6 +42,9 @@ public class DownLoadController {
@Autowired @Autowired
private ServerProperties serverProperties; private ServerProperties serverProperties;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
@Autowired @Autowired
private FileService fileService; private FileService fileService;
@@ -75,7 +83,7 @@ public class DownLoadController {
throw new UserException(ResultEnum.EMPTY_DATA); throw new UserException(ResultEnum.EMPTY_DATA);
} }
@RequestMapping("/home/download/dodownload")
public String download(@RequestParam Integer fileId, HttpServletRequest request, HttpServletResponse response) { public String download(@RequestParam Integer fileId, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8"); response.setContentType("text/html;charset=utf-8");
@@ -84,8 +92,8 @@ public class DownLoadController {
} catch (UnsupportedEncodingException e1) { } catch (UnsupportedEncodingException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
java.io.BufferedInputStream bis = null; BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null; BufferedOutputStream bos = null;
TbFile file = new TbFile(); TbFile file = new TbFile();
file.setColfileid(fileId); file.setColfileid(fileId);
@@ -111,7 +119,7 @@ public class DownLoadController {
bos.write(buff, 0, bytesRead); bos.write(buff, 0, bytesRead);
} }
//记录下载日志 //记录下载日志
addVisitLog("下载文件"+tbFile.getColrealname()+" "+tbFile.getColfilename()); addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
} catch (Exception e) { } catch (Exception e) {
@@ -138,6 +146,74 @@ public class DownLoadController {
} }
@RequestMapping("/home/download/dodownload")
public String downloadFromFTP(@RequestParam Integer fileId, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
TbFile file = new TbFile();
file.setColfileid(fileId);
TbFile tbFile = fileService.findFileById(file);
String ctxPath = tbFile.getColfilepath();
String downLoadPath = ctxPath;
FtpOperationUtil ftpUtil = new FtpOperationUtil();
try {
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(tbFile.getColfilename().getBytes("utf-8"), "ISO8859-1"));
ftpUtil.connectServer();
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
String path = "/upload/" + tbFile.getCourseName() + "/" + tbFile.getWorkFolder() + "/";
System.out.println("【path】" + path);
InputStream inputStream = ftpUtil.downFile(path, tbFile.getColfilename());
System.out.println("【available】" + inputStream.available());
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
// 记录下载日志
addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
ftpUtil.closeServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/** /**
* 传入课程名和文件夹名称,打包下载目录下所有文件 * 传入课程名和文件夹名称,打包下载目录下所有文件
* *
@@ -145,7 +221,6 @@ public class DownLoadController {
* @param folder * @param folder
* @param response * @param response
*/ */
@GetMapping("/home/admin/download/downloadzip")
public void batDownload(@RequestParam(value = "courseName") String courseName, public void batDownload(@RequestParam(value = "courseName") String courseName,
@RequestParam(value = "Folder") String folder, HttpServletResponse response) { @RequestParam(value = "Folder") String folder, HttpServletResponse response) {
//获取文件夹名称 //获取文件夹名称
@@ -196,7 +271,7 @@ public class DownLoadController {
} }
//记录下载日志 //记录下载日志
addVisitLog("下载压缩文件"+zipFile.getName()); addVisitLog("下载压缩文件" + zipFile.getName());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -217,8 +292,8 @@ public class DownLoadController {
} }
} }
//将打包好的文件输出到客户端 //将打包好的文件输出到客户端
java.io.BufferedInputStream bis = null; BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null; BufferedOutputStream bos = null;
try { try {
long fileLength = new File(desPath).length(); long fileLength = new File(desPath).length();
response.setContentType("application/x-msdownload;"); response.setContentType("application/x-msdownload;");
@@ -253,6 +328,49 @@ public class DownLoadController {
} }
} }
@GetMapping("/home/admin/download/downloadzip")
public void batFTPDownloadZip(@RequestParam(value = "courseName") String courseName,
@RequestParam(value = "Folder") String folder, HttpServletResponse response) throws IOException {
//获取文件夹名称
String paths = "/upload/" + courseName + "/" + folder;
String zipPath = "/zip/";
List<String> pathList;
pathList = getFileString(paths);
//需要压缩的文件--包括文件地址和文件名
String[] path = pathList.toArray(new String[0]);
// 要生成的压缩文件地址和文件名称
String zipFileName = courseName + folder + ".zip";
String desPath = zipPath + "/" + zipFileName;
//System.out.println("打包文件存储地址:"+desPath);
//登录FTP
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
if (!ftpOperationUtil.existDirectory(zipPath)) {
ftpOperationUtil.createDirectory(zipPath);
}
String desZipPath = remoteExecuteProperties.getPath() + "zip/";
RemoteCommandUtil.zipFile(desZipPath,zipFileName,remoteExecuteProperties,"upload/" + courseName + "/" + folder);
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(zipFileName.getBytes("utf-8"), "ISO8859-1"));
InputStream inputStream = ftpOperationUtil.downFile("/zip/",zipFileName);
System.out.println("【available】" + inputStream.available());
//将打包好的文件输出到客户端
BufferedInputStream bis = new BufferedInputStream(inputStream);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
// 记录下载日志
addVisitLog("下载文件" + desZipPath + zipFileName);
}
/** /**
* 获取目录下所有文件的路径 * 获取目录下所有文件的路径
* *
@@ -299,6 +417,48 @@ public class DownLoadController {
} }
}*/ }*/
public void downloadConfigFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
FTPClient ftpClient = new FTPClient();
try {
int reply;
ftpClient.connect("120.120.120.156", 21);
ftpClient.login("user1", "user1");
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return;
}
ftpClient.changeWorkingDirectory("/GOS_CAS/BACKUP/cas_config_backup");//转移到FTP服务器目录
FTPFile[] fs = ftpClient.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].getName().equals(fileName)) {
String saveAsFileName = new String(fs[i].getName().getBytes("UTF-8"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName);
OutputStream os = response.getOutputStream();
ftpClient.retrieveFile(fs[i].getName(), os);
os.flush();
os.close();
break;
}
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
}
/** /**
* 登陆后的访问日志记录 * 登陆后的访问日志记录
* *

View File

@@ -5,15 +5,13 @@ import com.fjy.spring.domain.Homework;
import com.fjy.spring.domain.TbFile; import com.fjy.spring.domain.TbFile;
import com.fjy.spring.domain.TbLog; import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser; import com.fjy.spring.domain.TbUser;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.properties.ServerProperties; import com.fjy.spring.properties.ServerProperties;
import com.fjy.spring.service.FileService; import com.fjy.spring.service.FileService;
import com.fjy.spring.service.HomeworkService; import com.fjy.spring.service.HomeworkService;
import com.fjy.spring.service.LogService; import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.FormatFileSizeUtil; import com.fjy.spring.untils.*;
import com.fjy.spring.untils.GetIPAddrUtil;
import com.fjy.spring.untils.LogUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -24,10 +22,9 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY; import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY;
@@ -42,6 +39,9 @@ public class UpLoadController {
@Autowired @Autowired
private ServerProperties serverProperties; private ServerProperties serverProperties;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
/** /**
* 文件相关数据库操作 * 文件相关数据库操作
*/ */
@@ -160,7 +160,7 @@ public class UpLoadController {
TbUser user = (TbUser) request.getSession().getAttribute(GlobalConstant.USER_SESSION_KEY); TbUser user = (TbUser) request.getSession().getAttribute(GlobalConstant.USER_SESSION_KEY);
Date date = new Date(); Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String dateNowStr = sdf.format(date); String dateNowStr = sdf.format(date);
String dateNowStr2 = sdf2.format(date); String dateNowStr2 = sdf2.format(date);
String uploadUrl; String uploadUrl;
@@ -171,15 +171,8 @@ public class UpLoadController {
uploadUrl = serverProperties.getFilePath() + "upload/"; uploadUrl = serverProperties.getFilePath() + "upload/";
} }
File dir = new File(uploadUrl);
if (!dir.exists()) {
dir.mkdirs();
}
List<String> fileList = new ArrayList<String>();
for (MultipartFile file : files.values()) { for (MultipartFile file : files.values()) {
Homework homework = new Homework(); Homework homework = new Homework();
//管理员上传不需要传workId //管理员上传不需要传workId
if (workId != null) { if (workId != null) {
@@ -204,33 +197,6 @@ public class UpLoadController {
tbFile.setColfilename(filename); tbFile.setColfilename(filename);
} }
File targetFile = new File(pathname);
//若文件已存在则自动重命名
if (targetFile.exists()) {
String bakpathname;
if (rename) {
bakpathname = uploadUrl + "bak/" + user.getColstudentno() + user.getColrealname() + suffix;
} else {
bakpathname = uploadUrl + "bak/" + filename;
}
log.info("源文件路径:" + pathname);
TbFile file1 = fileService.findByFilepath(pathname);
file1.setColfilepath(bakpathname + "." + dateNowStr2 + ".bak");
file1.setColfilename(file1.getColfilename() + "." + dateNowStr2 + ".bak");
if (fileService.addFile(file1)) {
log.info("重命名文件数据库更新成功");
} else {
log.error("重命名文件数据库更新失败");
}
File mvfile = new File(bakpathname + "." + dateNowStr2 + ".bak");
try {
FileUtils.moveFile(targetFile, mvfile);
log.info("源文件:" + targetFile.getName() + "已重命名为:" + mvfile.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("文件上传到: " + uploadUrl + filename); log.info("文件上传到: " + uploadUrl + filename);
log.info("文件大小: " + FormatFileSizeUtil.GetFileSize(file.getSize())); log.info("文件大小: " + FormatFileSizeUtil.GetFileSize(file.getSize()));
log.info("文件名: " + filename); log.info("文件名: " + filename);
@@ -246,6 +212,45 @@ public class UpLoadController {
tbFile.setCourseName(courseName); tbFile.setCourseName(courseName);
tbFile.setWorkFolder(folder); tbFile.setWorkFolder(folder);
try {
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
InputStream inputStream = file.getInputStream();
String path = "/upload/" + courseName + "/" + folder + "/";
boolean flagExistsFile = ftpOperationUtil.isExistsFile(path, tbFile.getColfilename());
System.out.println("flagExistsFile" + flagExistsFile);
//若文件已存在则自动重命名
if (flagExistsFile) {
String oldFileName;
if (rename) {
oldFileName = path + "bak/" + filePrefix + user.getColstudentno() + user.getColrealname() + fileSuffix + suffix;
} else {
oldFileName = path + "bak/" + filename;
}
log.info("源文件路径:" + pathname);
String newFileName = tbFile.getColfilename() + "." + dateNowStr2 + ".bak";
// 数据库查找已存在文件的记录
TbFile file1 = fileService.findByFilepath(pathname);
file1.setColfilepath(oldFileName + "." + dateNowStr2 + ".bak");
file1.setColfilename(file1.getColfilename() + "." + dateNowStr2 + ".bak");
String bakPath = path + "bak/";
System.out.println("【path】" + bakPath + "【originPath】" + pathname +
"【filename】" + tbFile.getColfilename() + "【newFileName】" + newFileName);
RemoteCommandUtil.moveFile(pathname, bakPath, newFileName, remoteExecuteProperties);
log.info("源文件:" + oldFileName + "已重命名为:" + newFileName);
if (fileService.addFile(file1)) {
log.info("重命名文件数据库更新成功");
} else {
log.error("重命名文件数据库更新失败");
}
}
boolean flag = ftpOperationUtil.uploadFile(inputStream,
tbFile.getColfilename(), path);
if (fileService.addFile(tbFile)) { if (fileService.addFile(tbFile)) {
log.info("记录写入数据库成功"); log.info("记录写入数据库成功");
@@ -254,29 +259,17 @@ public class UpLoadController {
} else { } else {
log.error("记录写入数据库失败"); log.error("记录写入数据库失败");
} }
ftpOperationUtil.closeServer();
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
try {
file.transferTo(targetFile);
fileList.add(
request.getScheme() + "://" + request.getServerName() + ":"
+ serverProperties.getPortNum() + request.getContextPath() + "/upload/"
+ file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
}
} }
} }
/** /**
* 登陆后的访问日志记录 * 登陆后的访问日志记录
*
* @param content * @param content
*/ */
private void addVisitLog(String content) { private void addVisitLog(String content) {

View File

@@ -13,24 +13,24 @@ import javax.persistence.*;
public class VHomework { public class VHomework {
@Id @Id
@Column(name = "workid") @Column(name = "workid")
private Integer id; private Integer Id;
@Column(name = "workname") @Column(name = "workname")
private String name; private String Name;
@Column(name = "worktime") @Column(name = "worktime")
private String time; private String Time;
@Column(name = "colfileid") @Column(name = "colfileid")
private Integer fileid; private Integer fileid;
@Column(name = "workfolder") @Column(name = "workfolder")
private String folder; private String Folder;
@Column(name = "coursename") @Column(name = "coursename")
private String courseName; private String courseName;
@Column(name = "workremark") @Column(name = "workremark")
private String remark; private String Remark;
} }

View File

@@ -0,0 +1,23 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-07 19:52
*/
@Data
public class FtpProperties {
//服务器地址名称
private String server = "104.223.24.81";
//端口号
private int port = 21;
//用户名称
private String username = "cms";
//密码
private String password = "imis2";
//工作目录
private String location = null;
}

View File

@@ -0,0 +1,20 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-10 12:34
*/
@Data
@ConfigurationProperties(prefix = "remoteproperties")
@Component
public class RemoteExecuteProperties {
private String ip;
private String user;
private String password;
private String path;
private int port;
}

View File

@@ -1,27 +1,13 @@
package com.fjy.spring.properties; package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
@ConfigurationProperties(prefix = "serverproperties") @ConfigurationProperties(prefix = "serverproperties")
@Data
public class ServerProperties { public class ServerProperties {
private String portNum; private String portNum;
private String filePath; private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getPortNum() {
return portNum;
}
public void setPortNum(String portNum) {
this.portNum = portNum;
}
} }

View File

@@ -3,14 +3,6 @@ package com.fjy.spring.repository;
import com.fjy.spring.domain.VHomework; import com.fjy.spring.domain.VHomework;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface VHomeworkRepository extends JpaRepository<VHomework,Integer> { public interface VHomeworkRepository extends JpaRepository<VHomework,Integer> {
/**
* 找出指定时间之前的所有作业
* @param destime
* @return
*/
List<VHomework> findAllByTimeAfter(String destime);
} }

View File

@@ -3,13 +3,5 @@ package com.fjy.spring.repository;
import com.fjy.spring.domain.VWorkDetail; import com.fjy.spring.domain.VWorkDetail;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface WorkDetailRepository extends JpaRepository<VWorkDetail,Integer> { public interface WorkDetailRepository extends JpaRepository<VWorkDetail,Integer> {
/**
* 找出指定时间之前的所有作业详情
* @param worktime
* @return
*/
List<VWorkDetail> findAllByWorktimeAfter(String worktime);
} }

View File

@@ -33,8 +33,4 @@ public class HomeworkService {
} }
return null; return null;
} }
public List<VHomework> findAllVHomeworkAfterTime(String time){
return vHomeworkRepository.findAllByTimeAfter(time);
}
} }

View File

@@ -15,8 +15,4 @@ public class WorkDetailService {
public List<VWorkDetail> findAll(){ public List<VWorkDetail> findAll(){
return workDetailRepository.findAll(); return workDetailRepository.findAll();
} }
public List<VWorkDetail> findAllVWorkDetailAfterTime(String time){
return workDetailRepository.findAllByWorktimeAfter(time);
}
} }

View File

@@ -0,0 +1,641 @@
package com.fjy.spring.untils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import com.fjy.spring.properties.FtpProperties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-07 19:56
*/
public class FtpOperationUtil {
private FTPClient ftpClient;
private static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
private static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
/**
* 利用FtpProperties进行服务器连接
*
* @throws SocketException
* @throws IOException
*/
public void connectServer() throws SocketException,
IOException {
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
public void connectServer(String path) throws SocketException,
IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(path)) {
createDirectory(path);
}
ftpClient.changeWorkingDirectory(path);
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
/**
* 使用详细信息进行服务器连接
*
* @param server服务器地址名称
* @param port端口号
* @param user用户名
* @param password用户密码
* @param path转移到FTP服务器目录
* @throws SocketException
* @throws IOException
*/
public void connectServer(String server, int port, String user,
String password, String path) throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
System.out.println("Connected to " + server + ".");
//连接成功后的回应码
System.out.println(ftpClient.getReplyCode());
ftpClient.login(user, password);
if (path != null && path.length() != 0) {
ftpClient.changeWorkingDirectory(path);
}
ftpClient.setBufferSize(1024);//设置上传缓存大小
ftpClient.setControlEncoding("UTF-8");//设置编码
ftpClient.setFileType(BINARY_FILE_TYPE);//设置文件类型
}
/**
* 设置传输文件类型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE
* 二进制文件或文本文件
*
* @param fileType
* @throws IOException
*/
public void setFileType(int fileType) throws IOException {
ftpClient.setFileType(fileType);
}
/**
* 关闭连接
*
* @throws IOException
*/
public void closeServer() throws IOException {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.logout();//退出FTP服务器
ftpClient.disconnect();//关闭FTP连接
}
}
/**
* 转移到FTP服务器工作目录
*
* @param path
* @return
* @throws IOException
*/
public boolean changeDirectory(String path) throws IOException {
return ftpClient.changeWorkingDirectory(path);
}
/**
* 在服务器上创建目录
*
* @param pathName
* @return
* @throws IOException
*/
public boolean createDirectory(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.makeDirectory(pathName);
}
/**
* 创建多级目录
*
* @param multiDirectory
* @return
*/
public boolean createMultiDirectory(String multiDirectory) {
boolean bool = false;
try {
String[] dirs = multiDirectory.split("/");
ftpClient.changeWorkingDirectory("/");
//按顺序检查目录是否存在,不存在则创建目录
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
if (ftpClient.makeDirectory(dirs[i])) {
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
return false;
}
} else {
return false;
}
}
}
bool = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
return bool;
}
}
/**
* 在服务器上删除目录
*
* @param path
* @return
* @throws IOException
*/
public boolean removeDirectory(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.removeDirectory(path);
}
/**
* 删除所有文件和目录
*
* @param path
* @param isAll true:删除所有文件和目录
* @return
* @throws IOException
*/
public boolean removeDirectory(String path, boolean isAll)
throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!isAll) {
return removeDirectory(path);
}
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr == null || ftpFileArr.length == 0) {
return removeDirectory(path);
}
//
for (FTPFile ftpFile : ftpFileArr) {
String name = ftpFile.getName();
if (ftpFile.isDirectory()) {
System.out.println("* [sD]Delete subPath [" + path + "/" + name + "]");
removeDirectory(path + "/" + name, true);
} else if (ftpFile.isFile()) {
System.out.println("* [sF]Delete file [" + path + "/" + name + "]");
deleteFile(path + "/" + name);
} else if (ftpFile.isSymbolicLink()) {
} else if (ftpFile.isUnknown()) {
}
}
return ftpClient.removeDirectory(path);
}
/**
* 检查目录在服务器上是否存在 true存在 false不存在
*
* @param dirName
* @return
* @throws IOException
*/
public boolean existDirectory(String dirName) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles("/");
for (FTPFile ftpFile : ftpFileArr) {
if (ftpFile.isDirectory()
&& ftpFile.getName().equalsIgnoreCase(dirName)) {
flag = true;
break;
}
}
return flag;
}
/**
* 判断给定路径是否存在
*
* @param path
* @return
* @throws IOException
*/
public boolean existMultiDirectory(String path) throws IOException {
boolean flag = false;
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 0; dirs != null && i < dirs.length; i++) {
FTPFile[] ftpFileArr = ftpClient.listFiles();
for (FTPFile ftpFile : ftpFileArr) {
// 判断是否为最后一级目录
if (ftpFile.isDirectory()
&& ftpFile.getName().equalsIgnoreCase(dirs[dirs.length - 1])) {
flag = true;
break;
}
}
// 进入下一级目录
ftpClient.changeWorkingDirectory(new String(dirs[i].getBytes("UTF-8"), "iso-8859-1"));
}
}
return flag;
}
public boolean isExistsFile(String fileName) {
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] file = ftpClient.listFiles(fileName);
return file.length > 0 ? true : false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 查看指定路径下是否存在该文件
*
* @param path
* @param fileName
* @return
*/
public boolean isExistsFile(String path, String fileName) throws IOException {
boolean flagChange = false;
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
flagChange = ftpClient.changeWorkingDirectory(dirs[i]);
}
}
// 该语句必须位于创建目录之后
System.out.println("【目录切换】" + path + flagChange);
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] file = ftpClient.listFiles(fileName);
return file.length > 0;
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
return false;
}
}
/**
* 实现文件移动操作
* @param desPath
* @param originPath
* @param oldFileName
* @param newFileName
* @return
* @throws IOException
*/
public boolean moveFile(String desPath, String originPath, String oldFileName,String newFileName) throws IOException {
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
ftpClient.enterLocalPassiveMode();
boolean moveFlag;
// 目标文件目录是否存在
System.out.println("【desPath】"+desPath);
if (!existMultiDirectory(desPath)) {
System.out.println("【创建目录】"+createMultiDirectory(desPath));
}
// 切换到源文件目录
changWorkingDir(originPath);
//转换成输入流
InputStream is = null;
is = ftpClient.retrieveFileStream(oldFileName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
System.out.println("【inputStream】"+is.available()+" "+bufferedInputStream.available());
is.close();
boolean cpcflag = ftpClient.completePendingCommand();
System.out.println("【completePendingCommand】"+cpcflag);
// 切换到目标文件目录
changWorkingDir(desPath);
//复制文件
moveFlag = ftpClient.storeFile(newFileName, bufferedInputStream);
System.out.println("【创建目录】"+moveFlag);
if (moveFlag) {
changWorkingDir(originPath);
//删除源文件
ftpClient.deleteFile(oldFileName);
bufferedInputStream.close();
}
return moveFlag;
}
/**
* 得到文件列表,listFiles返回包含目录和文件它返回的是一个FTPFile数组
* listNames():只包含目录的字符串数组
* String[] fileNameArr = ftpClient.listNames(path);
*
* @param path:服务器上的文件目录:/DF4
*/
public List<String> getFileList(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] ftpFiles = ftpClient.listFiles(path);
//通过FTPFileFilter遍历只获得文件
/* FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
@Override
public boolean accept(FTPFile ftpFile) {
return ftpFile.isFile();
}
}); */
List<String> retList = new ArrayList<String>();
if (ftpFiles == null || ftpFiles.length == 0) {
return retList;
}
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.isFile()) {
retList.add(ftpFile.getName());
}
}
return retList;
}
/**
* 获取所有文件和目录
*
* @return
* @throws IOException
*/
public String[] list() throws IOException {
return ftpClient.listNames();
}
public String[] list(String path) throws IOException {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
ftpClient.enterLocalPassiveMode();
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
ftpClient.changeWorkingDirectory(dirs[i]);
}
return ftpClient.listNames();
}
/**
* 删除服务器上的文件
*
* @param pathName
* @return
* @throws IOException
*/
public boolean deleteFile(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.deleteFile(pathName);
}
public boolean renameFile(String oldFileName, String newFileName) throws IOException {
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.rename(oldFileName, newFileName);
}
/**
* 上传文件到ftp服务器
* 在进行上传和下载文件的时候,设置文件的类型最好是:
* ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE)
* localFilePath:本地文件路径和名称
* remoteFileName:服务器文件名称
*/
public boolean uploadFile(String localFilePath, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(localFilePath)) {
createDirectory(localFilePath);
ftpClient.changeWorkingDirectory(localFilePath);
}
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(localFilePath);
//我们可以使用BufferedInputStream进行封装
//BufferedInputStream bis=new BufferedInputStream(iStream);
//flag = ftpClient.storeFile(remoteFileName, bis);
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
public boolean uploadFile(String localFilePath, String path, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(localFilePath);
if (path != null && path.length() != 0) {
createDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 上传文件到ftp服务器上传新的文件名称和原名称一样
*
* @param fileName文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(String fileName) throws IOException {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
return uploadFile(fileName, fileName);
}
/**
* 上传文件到ftp服务器
*
* @param iStream 输入流
* @param newName 新文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String newName)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 上传文件到ftp服务器
*
* @param iStream 输入流
* @param newName 新文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String newName, String path)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
if (path != null && path.length() != 0) {
createMultiDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 从ftp服务器上下载文件到本地
*
* @param remoteFileNameftp服务器上文件名称
* @param localFileName本地文件名称
* @return
* @throws IOException
*/
public boolean download(String remoteFileName, String localFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
File outfile = new File(localFileName);
OutputStream oStream = null;
try {
oStream = new FileOutputStream(outfile);
//我们可以使用BufferedOutputStream进行封装
//BufferedOutputStream bos=new BufferedOutputStream(oStream);
//flag = ftpClient.retrieveFile(remoteFileName, bos);
flag = ftpClient.retrieveFile(remoteFileName, oStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
oStream.close();
}
return flag;
}
/**
* 从ftp服务器上下载文件到本地
*
* @param sourceFileName服务器资源文件名称
* @return InputStream 输入流
* @throws IOException
*/
public InputStream downFile(String sourceFileName) throws IOException {
sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.retrieveFileStream(sourceFileName);
}
public InputStream downFile(String path, String sourceFileName) throws IOException {
sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1");
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (path != null && path.length() != 0) {
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + path + flagChange);
}
return ftpClient.retrieveFileStream(sourceFileName);
}
/**
* 采用递归方式切换目录
*
* @param path
* @throws IOException
*/
public void changWorkingDir(String path) throws IOException {
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 0; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
ftpClient.changeWorkingDirectory(dirs[i]);
System.out.println("【当前目录】" + new String(ftpClient.printWorkingDirectory().getBytes("iso-8859-1"), "UTF-8"));
}
}
}
}

View File

@@ -0,0 +1,430 @@
package com.fjy.spring.untils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author F嘉阳
* @date 2018-05-06 11:35
*/
public class FtpUtils {
// private static final String FTP_URL = "176.122.138.235";
private static final String FTP_URL = "192.168.79.138";
private static final int PORT = 21;
private static final String USER_NAME = "cms";
private static final String PASSWORD = "imis2";
/**
* 本地字符编码
*/
private static final String LOCAL_CHARSET = "UTF-8";
/**
* FTP协议里面规定文件名编码为iso-8859-1
*/
private static String SERVER_CHARSET = "iso-8859-1";
/**
* ftp上传单个文件
*
* @param directory 上传至ftp的路径名不包括ftp地址
* @param srcFileName 要上传的文件全路径名
* @param destName 上传至ftp后存储的文件名
* @throws IOException
*/
public static boolean upload(String directory, String srcFileName, String destName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
destName = new String(destName.getBytes("UTF-8"), "iso-8859-1");
FTPClient ftpClient = makeConnectionFactory();
FileInputStream fis = null;
boolean result = false;
try {
File srcFile = new File(srcFileName);
fis = new FileInputStream(srcFile);
// 设置上传目录
ftpClient.changeWorkingDirectory(directory);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding(LOCAL_CHARSET);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
result = ftpClient.storeFile(destName, fis);
return result;
} catch (NumberFormatException e) {
System.out.println("FTP端口配置错误:不是数字:");
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* FTP单个文件下载
*
* @param directory 要下载的文件所在ftp的路径名不包含ftp地址
* @param destFileName 要下载的文件名
* @param downloadName 下载后存储的文件名全路径
*/
public static boolean download(String directory, String destFileName, String downloadName) throws IOException {
FTPClient ftpClient = makeConnectionFactory();
boolean result = false;
try {
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.changeWorkingDirectory(directory);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
System.out.println("destFileName:" + destFileName + ",downloadName:" + downloadName);
FileOutputStream fileOutputStream = new FileOutputStream(downloadName);
result = ftpClient.retrieveFile(destFileName, fileOutputStream);
fileOutputStream.flush();
return result;
} catch (NumberFormatException e) {
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param remotePath
* @param fileName
* @param localPath
* @return
* @author xh 测试成功 可以下载中文文件 ftp默认的编码为gbk
*/
public static boolean downFtpFile(String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(FTP_URL, PORT);
// 如果采用默认端口可以使用ftp.connect(url)的方式直接连接FTP服务器
// 登录
ftp.login(USER_NAME, PASSWORD);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
String fname = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");
if (fname.equals(fileName)) {
File localFile = new File(localPath + fname);
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
break;
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* @param fileName
* @return
* @author xh 测试成功 可以下载中文文件 ftp默认的编码为gbk
*/
public static OutputStream downFtpFileByStream(String fileName) {
String remotePath = "/www/ftp/cms/";
boolean success = false;
OutputStream is = null;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(FTP_URL, PORT);
// 如果采用默认端口可以使用ftp.connect(url)的方式直接连接FTP服务器
// 登录
ftp.login(USER_NAME, PASSWORD);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return null;
}
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
String fname = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");
if (fname.equals(fileName)) {
File localFile = new File(fname);
is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
return is;
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert is != null;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return null;
}
/**
* @param directory 要重命名的文件所在ftp的路径名不包含ftp地址
* @param oldFileName 要重命名的文件名
* @param newFileName 重命名后的文件名
* @throws IOException
*/
public static boolean rename(String directory, String oldFileName, String newFileName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否重命名成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
//重命名远程文件
result = ftpClient.rename(oldFileName, newFileName);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要删除的文件所在ftp的路径名不包含ftp地址
* @param fileName 要删除的文件名
* @return
* @throws IOException
*/
public static boolean remove(String directory, String fileName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
//删除远程文件
result = ftpClient.deleteFile(fileName);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要创建的目录所在ftp的路径名不包含ftp地址
* @param newDirectory 要创建的新目录名
* @return
* @throws IOException
*/
public static boolean makeDirecotory(String directory, String newDirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
newDirectory = new String(newDirectory.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.makeDirectory(newDirectory);//创建新目录
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要重命名的目录所在ftp的路径名不包含ftp地址
* @param oldDirectory 要重命名的旧目录名
* @param newDirectory 重命名后的新目录
* @return
* @throws IOException
*/
public static boolean renameDirecotory(String directory, String oldDirectory, String newDirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
oldDirectory = new String(oldDirectory.getBytes("UTF-8"), "iso-8859-1");
newDirectory = new String(newDirectory.getBytes("UTF-8"), "iso-8859-1");
// 判断远程文件是否移除成功如果成功返回true否则返回false
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
// 重命名目录
result = ftpClient.rename(oldDirectory, newDirectory);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要重命名的目录所在ftp的路径名不包含ftp地址
* @param deldirectory 要删除的目录名
* @return
* @throws IOException
*/
public static boolean removeDirecotory(String directory, String deldirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
deldirectory = new String(deldirectory.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.removeDirectory(deldirectory);//删除目录
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory
* @return
* @throws IOException
*/
public static String[] list(String directory) throws IOException {
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
ftpClient.enterLocalPassiveMode();
//删除目录
return ftpClient.listNames();
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* 创建FTP连接的工厂方法
*
* @return
* @throws IOException
*/
private static FTPClient makeConnectionFactory() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(FTP_URL, PORT);
ftpClient.login(USER_NAME, PASSWORD);
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding(LOCAL_CHARSET);
return ftpClient;
}
}

View File

@@ -0,0 +1,92 @@
package com.fjy.spring.untils;
import com.fjy.spring.properties.RemoteExecuteProperties;
import lombok.extern.slf4j.Slf4j;
/**
* 封装Linux远程命令
*
* @author F嘉阳
* @date 2018-05-13 09:11
*/
@Slf4j
public class RemoteCommandUtil {
private static RemoteExecuteCommandUtil REC;
private static String cmd;
/**
* 生成压缩文件
*
* @param desZipPath 压缩文件目标地址
* @param zipFileName 压缩文件名
* @param remoteExecuteProperties 远程参数配置类
* @param originPath 目标文件、文件夹地址
*/
public static void zipFile(String desZipPath,
String zipFileName,
RemoteExecuteProperties remoteExecuteProperties,
String originPath) {
login(remoteExecuteProperties);
desZipPath = remoteExecuteProperties.getPath() + desZipPath;
originPath = remoteExecuteProperties.getPath() + originPath;
cmd = "zip -r " + desZipPath + zipFileName + " " + originPath;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
log.error("【cmd创建压缩文件失败】" + cmd);
}
/**
* 移动文件
*
* @param originPath 源文件路径
* @param desPath 目标路径
* @param remoteExecuteProperties 远程参数配置类
* @return
*/
public static void moveFile(String originPath, String desPath, String newName, RemoteExecuteProperties remoteExecuteProperties) {
login(remoteExecuteProperties);
// 创建目标目录
mkdir(desPath, remoteExecuteProperties);
desPath = remoteExecuteProperties.getPath() + desPath;
originPath = remoteExecuteProperties.getPath() + originPath;
cmd = "mv " + originPath + " " + desPath + newName;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
/**
* 创建多级目录
*
* @param path
* @param remoteExecuteProperties
*/
public static void mkdir(String path, RemoteExecuteProperties remoteExecuteProperties) {
login(remoteExecuteProperties);
path = remoteExecuteProperties.getPath() + path;
cmd = "mkdir -p " + path;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
public static void deleteFile(String path, RemoteExecuteProperties remoteExecuteProperties){
login(remoteExecuteProperties);
path = remoteExecuteProperties.getPath() + path;
cmd = "rm -f " + path;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
private static void login(RemoteExecuteProperties remoteExecuteProperties) {
//远程登录SSH
REC = new RemoteExecuteCommandUtil(
remoteExecuteProperties.getIp(),
remoteExecuteProperties.getUser(),
remoteExecuteProperties.getPassword(),
remoteExecuteProperties.getPort());
REC.login();
}
}

View File

@@ -0,0 +1,163 @@
package com.fjy.spring.untils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.StringUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
* @author F嘉阳
* @date 2018-05-10 12:16
*/
public class RemoteExecuteCommandUtil {
//字符编码默认是utf-8
private static String DEFAULTCHART="UTF-8";
private Connection conn;
private String ip;
private String userName;
private String userPwd;
private int port;
public RemoteExecuteCommandUtil(String ip, String userName, String userPwd,int port) {
this.ip = ip;
this.userName = userName;
this.userPwd = userPwd;
this.port = port;
}
public RemoteExecuteCommandUtil() {
}
/**
* 远程登录linux的主机
* @author Ickes
* @since V0.1
* @return
* 登录成功返回true否则返回false
*/
public Boolean login(){
boolean flg=false;
try {
conn = new Connection(ip,port);
conn.connect();//连接
flg=conn.authenticateWithPassword(userName, userPwd);//认证
} catch (IOException e) {
e.printStackTrace();
}
return flg;
}
/**
* @author Ickes
* 远程执行shll脚本或者命令
* @param cmd
* 即将执行的命令
* @return
* 命令执行完后返回的结果值
* @since V0.1
*/
public String execute(String cmd){
String result="";
try {
if(login()){
Session session= conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result=processStdout(session.getStdout(),DEFAULTCHART);
//如果为得到标准输出为空,说明脚本执行出错了
if(StringUtils.isBlank(result)){
result=processStdout(session.getStderr(),DEFAULTCHART);
}
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @author Ickes
* 远程执行shll脚本或者命令
* @param cmd
* 即将执行的命令
* @return
* 命令执行成功后返回的结果值如果命令执行失败返回空字符串不是null
* @since V0.1
*/
public String executeSuccess(String cmd){
String result="";
try {
if(login()){
Session session= conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result=processStdout(session.getStdout(),DEFAULTCHART);
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 解析脚本执行返回的结果集
* @author Ickes
* @param in 输入流对象
* @param charset 编码
* @since V0.1
* @return
* 以纯文本的格式返回
*/
private String processStdout(InputStream in, String charset){
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
String line=null;
while((line=br.readLine()) != null){
buffer.append(line+"\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void setCharset(String charset) {
DEFAULTCHART = charset;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}

View File

@@ -7,7 +7,13 @@ server:
port: 8080 port: 8080
serverproperties: serverproperties:
port_num: 8080 port_num: 8080
filePath: F:\JAVA Workspace\Temp\ filePath: /
remoteproperties:
ip: 104.223.24.81
port: 26460
user: root
password: 27894869root
path: /www/wwwroot/cmsftp
spring: spring:
thymeleaf: thymeleaf:
prefix: classpath:/templates/ prefix: classpath:/templates/

View File

@@ -1,39 +0,0 @@
#运行环境配置文件
server:
servlet:
context-path: /cms
session:
timeout: 1440s
port: 8080
tomcat:
remote-ip-header: x-forwarded-for
protocol-header: x-forwarded-proto
port-header: X-Forwarded-Port
use-forward-headers: true
serverproperties:
port_num: 80
filePath: /www/cmsfile/
spring:
thymeleaf:
prefix: classpath:/templates/
cache: true
check-template: true
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.1.25/db_imis2?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: imis2
password: 2015imis2
servlet:
multipart:
max-file-size: 100Mb
max-request-size: 100Mb
jpa:
hibernate:
ddl-auto: update
show-sql: false
#resources:
# static-locations: classpath:/templates/
debug: false

View File

@@ -13,6 +13,12 @@ server:
serverproperties: serverproperties:
port_num: 8085 port_num: 8085
filePath: /www/cmsfile/ filePath: /www/cmsfile/
ftp:
server: 176.122.138.235
port: 21
username: cms
password: imis2
location: /www/ftp/cms/
spring: spring:
thymeleaf: thymeleaf:
prefix: classpath:/templates/ prefix: classpath:/templates/

View File

@@ -1,54 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration> <configuration>
<appender name="GELF" class="de.siegmar.logbackgelf.GelfUdpAppender"> <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<graylogHost>192.168.1.27</graylogHost> <layout class="ch.qos.logback.classic.PatternLayout">
<graylogPort>12201</graylogPort> <pattern>
<maxChunkSize>508</maxChunkSize> %d - %msg%n
<useCompression>true</useCompression> </pattern>
<encoder class="de.siegmar.logbackgelf.GelfEncoder"> </layout>
<includeRawMessage>false</includeRawMessage>
<includeMarker>true</includeMarker>
<includeMdcData>true</includeMdcData>
<includeCallerData>false</includeCallerData>
<includeRootCauseData>false</includeRootCauseData>
<!--显示日志级别名称,默认为数字-->
<includeLevelName>true</includeLevelName>
<shortPatternLayout class="ch.qos.logback.classic.PatternLayout">
<pattern>%m%nopex</pattern>
</shortPatternLayout>
<fullPatternLayout class="ch.qos.logback.classic.PatternLayout">
<pattern>%m%n</pattern>
</fullPatternLayout>
<!--配置应用名称-->
<staticField>app_name:cms</staticField>
<staticField>os_arch:${os.arch}</staticField>
<staticField>os_name:${os.name}</staticField>
<staticField>os_version:${os.version}</staticField>
</encoder>
</appender> </appender>
<!--每天输出一个文件使用RollingFileAppender滚动输出策略-->
<!-- 彩色日志 --> <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 彩色日志依赖的渲染类 --> <!--根据范围仅保留info的日志-->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/> <filter class="ch.qos.logback.classic.filter.LevelFilter">
<conversionRule conversionWord="wex" <level>ERROR</level>
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/> <onMatch>DENY</onMatch>
<conversionRule conversionWord="wEx" <onMismatch>ACCEPT</onMismatch>
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/> </filter>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!-- Console 输出设置 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder> <encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern> <pattern>
%d - %msg%n
</pattern>
<charset>utf8</charset> <charset>utf8</charset>
</encoder> </encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<fileNamePattern>F:\JAVA Workspace\Temp\log\%d\info.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/info.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender>
<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--根据范围过滤ERROR等级以下的日志-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%d - %msg%n
</pattern>
<charset>utf8</charset>
</encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<fileNamePattern>F:\JAVA Workspace\Temp\log\error.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/error.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender> </appender>
<root level="info"> <root level="info">
<!-- 控制台输出 --> <appender-ref ref="consoleLog"/>
<appender-ref ref="CONSOLE"/> <appender-ref ref="fileInfoLog"/>
<appender-ref ref="GELF"/> <appender-ref ref="fileErrorLog"/>
</root> </root>
</configuration> </configuration>

View File

@@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%d - %msg%n
</pattern>
</layout>
</appender>
<!--每天输出一个文件使用RollingFileAppender滚动输出策略-->
<appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--根据范围仅保留info的日志-->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%d - %msg%n
</pattern>
<charset>utf8</charset>
</encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<fileNamePattern>F:\JAVA Workspace\Temp\log\%d\info.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/info.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender>
<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--根据范围过滤ERROR等级以下的日志-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%d - %msg%n
</pattern>
<charset>utf8</charset>
</encoder>
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<fileNamePattern>F:\JAVA Workspace\Temp\log\error.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/error.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender>
<root level="info">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileInfoLog"/>
<appender-ref ref="fileErrorLog"/>
</root>
</configuration>

View File

@@ -1,49 +0,0 @@
package com.fjy.spring.service;
import com.fjy.spring.domain.VHomework;
import org.junit.Test;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
public class HomeworkServiceTest {
@Test
public void findAll() {
}
@Test
public void findAllVHomework() {
}
@Test
public void findById() {
Format f = new SimpleDateFormat("yyyy-MM-dd");
Date today = new Date();
System.out.println("今天是:" + f.format(today));
Calendar c = Calendar.getInstance();
c.setTime(today);
c.add(Calendar.DAY_OF_MONTH, -1);// 今天+1天
Date tomorrow = c.getTime();
System.out.println("昨天是:" + f.format(tomorrow));
}
@Test
public void findAllVHomeworkAfterTime() {
HomeworkService homeworkService = new HomeworkService();
List<VHomework> homeworkList = homeworkService.findAllVHomeworkAfterTime("2018-05-28");
if (homeworkList!=null){
for (VHomework vHomework : homeworkList){
System.out.println(vHomework.toString());
}
}
}
}

View File

@@ -0,0 +1,162 @@
package com.fjy.spring.untils;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
public class FtpOperationUtilTest {
private static final String FILE_NAME = "ERP实验1销售预测与SOP.doc";
private static final String DESTINATION = "F:\\JAVA Workspace\\Temp\\upload\\ERP实验1销售预测与SOP.doc";
private static final String LOCAL_DESTINATION = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
private static FtpOperationUtil makeConnectionFactory() {
FtpOperationUtil ftpUtil = new FtpOperationUtil();
try {
ftpUtil.connectServer();
} catch (IOException e) {
e.printStackTrace();
}
return ftpUtil;
}
private static void listFiles(FtpOperationUtil ftpUtil) throws IOException {
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
}
@Test
public void createDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.createDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void removeDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void removeDirectory1() throws IOException {
createDirectory();
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录", true);
listFiles(ftpUtil);
}
@Test
public void existDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory1:" + flag);
ftpUtil.createDirectory("创建目录");
flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory2:" + flag);
ftpUtil.removeDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void changWorkingDir() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.changWorkingDir("/upload/信息安全/时间测试/");
String[] lists = ftpUtil.list();
for (String list : lists) {
System.out.println(list);
}
ftpUtil.changWorkingDir("/");
String[] lists2 = ftpUtil.list();
for (String list : lists2) {
System.out.println(list);
}
}
@Test
public void existMultiDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.existMultiDirectory("/upload/信息安全/时间测试/");
System.out.println("existMultiDirectory:" + flag);
}
@Test
public void isExistsFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.isExistsFile("/信息安全/","15级15251101261FJY实验二.doc.2018_05_09_21_25_47.bak");
System.out.println("isExistsFile:" + flag);
listFiles(ftpUtil);
}
@Test
public void getFileList() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.getFileList("/");
}
@Test
public void list() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
String[] lists = ftpUtil.list("/upload/");
for (String list : lists) {
System.out.println(list);
}
}
@Test
public void deleteFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.deleteFile(FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile2() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
File file = new File(DESTINATION);
InputStream in = new FileInputStream(file);
ftpUtil.uploadFile(in, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile3() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION,"/信息安全/", FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void download() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.download(FILE_NAME, DESTINATION);
listFiles(ftpUtil);
}
@Test
public void moveFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
String desPath = "/upload/bak/";
String originPath = "/upload/";
ftpUtil.moveFile(desPath,originPath,FILE_NAME,FILE_NAME);
listFiles(ftpUtil);
}
}

View File

@@ -0,0 +1,83 @@
package com.fjy.spring.untils;
import org.junit.Test;
import static org.junit.Assert.*;
public class FtpUtilsTest {
private static final String destName = "ERP实验1销售预测与SOP.doc";
private static final String directory = "/www/ftp/cms/";
@Test
public void upload() throws Exception{
String srcFileName = "F:\\JAVA Workspace\\Temp\\upload\\ERP实验1销售预测与SOP.doc";
FtpUtils.upload(directory,srcFileName,destName);
list();
}
/**
* WIN10下载文件为0kb请勿使用
* @throws Exception
*/
@Test
public void download() throws Exception{
String downloadName = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
FtpUtils.download(directory,destName,downloadName);
}
@Test
public void downFtpFile() throws Exception{
String downloadName = "F:\\JAVA Workspace\\Temp\\";
boolean res = FtpUtils.downFtpFile(directory,destName,downloadName);
System.out.println(res);
}
@Test
public void rename() throws Exception{
String oldFileName = destName;
String newFileName = "新名称.doc";
FtpUtils.rename(directory,oldFileName, newFileName);
list();
}
@Test
public void remove() throws Exception{
FtpUtils.remove(directory,"新名称.doc");
list();
}
@Test
public void makeDirecotory() throws Exception{
String newDirectory = "test";
String newDirectoryZH = "新目录";
FtpUtils.makeDirecotory(directory,newDirectory);
FtpUtils.makeDirecotory(directory,newDirectoryZH);
list();
}
@Test
public void renameDirecotory() throws Exception{
String oldDirectoryZH = "新目录";
String newDirectoryZH = "重命名目录";
FtpUtils.renameDirecotory(directory,oldDirectoryZH,newDirectoryZH);
list();
}
@Test
public void removeDirecotory() throws Exception{
String newDirectory = "test";
String newDirectoryZH = "重命名目录";
FtpUtils.removeDirecotory(directory,newDirectory);
FtpUtils.removeDirecotory(directory,newDirectoryZH);
list();
}
@Test
public void list() throws Exception{
String[] lists = FtpUtils.list(directory);
for (String list : lists){
System.out.println(list);
}
}
}

View File

@@ -0,0 +1,44 @@
package com.fjy.spring.untils;
import com.fjy.spring.properties.RemoteExecuteProperties;
import org.junit.Test;
import static org.junit.Assert.*;
public class RemoteCommandUtilTest {
private RemoteExecuteProperties rep = new RemoteExecuteProperties();
private boolean flag;
@Test
public void zipFile() {
dataSet();
String desZipPath = "/test/";
String zipFileName = "test.zip";
String originPath = "/upload/";
RemoteCommandUtil.zipFile(desZipPath, zipFileName, rep, originPath);
}
@Test
public void moveFile() {
dataSet();
String desPath = "/test/zip/";
String newName = "test.zip";
String originPath = "/test/test.zip";
RemoteCommandUtil.moveFile(originPath,desPath,newName,rep);
}
@Test
public void mkdir() {
dataSet();
String path = "/test/zip/";
RemoteCommandUtil.mkdir(path,rep);
}
private void dataSet() {
rep.setIp("104.223.24.81");
rep.setPassword("27894869root");
rep.setUser("root");
rep.setPath("/www/wwwroot/cmsftp");
rep.setPort(26460);
}
}

View File

@@ -0,0 +1,67 @@
package com.fjy.spring.untils;
import org.junit.Test;
import static org.junit.Assert.*;
public class RemoteExecuteCommandUtilTest {
RemoteExecuteCommandUtil rec=new RemoteExecuteCommandUtil("104.223.24.81", "root","27894869root",26460);
@Test
public void login() {
rec.login();
System.out.println(rec.execute("cd /1/2/3/4"));
}
@Test
public void execute() {
}
@Test
public void executeZip() {
rec.login();
System.out.println(rec.execute("zip -r /home/ftp/cms/upload/信息安全时间测试.zip /home/ftp/cms/upload/信息安全"));
}
@Test
public void executeSuccess() {
}
@Test
public void setCharset() {
}
@Test
public void getConn() {
}
@Test
public void setConn() {
}
@Test
public void getIp() {
}
@Test
public void setIp() {
}
@Test
public void getUserName() {
}
@Test
public void setUserName() {
}
@Test
public void getUserPwd() {
}
@Test
public void setUserPwd() {
}
}