Commit 1d2a57f0 by wxh

first commit

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
#*.class
#
##package file
#
#*.war
#*.ear
#
##kdiff3 ignore
#*.orig
#
##maven ignore
#target/
#
##eclipse ignore
#.settings/
#.project
#.classpatch
#
##idea
#.idea/
#/idea/
#*.ipr
#*.iml
#*.iws
#
## temp file
#
#*.log
#*.cache
#*.diff
#*.patch
#*.tmp
#
##system ignore
#.DS_Store
#Thumbs.db
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.orhon.smartcampus</groupId>
<artifactId>material</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>material</name>
<description>Demo project for Spring Boot</description>
<properties>
<druid.version>1.1.10</druid.version>
<java.version>1.8</java.version>
<fastjson.version>1.2.46</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.10.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/webapp</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spring</id>
<url>https://maven.aliyun.com/repository/spring</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
package com.orhon.smartcampus.material;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import graphql.servlet.config.ObjectMapperConfigurer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@ComponentScan({"com.alibaba.fastjson.support.spring", "com.orhon.smartcampus.material"})
@EnableTransactionManagement
@EnableDiscoveryClient
public class MaterialApplication {
public static void main(String[] args) {
SpringApplication.run(MaterialApplication.class, args);
}
}
package com.orhon.smartcampus.material.basicComponents;
import org.mapstruct.Mapper;
import org.mapstruct.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
@Mapper
public interface ConvertHelper {
//id安全转换器
@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Id {
}
@Id
default public Long id(Map<String, Object> in) {
Long ret = null;
try{
ret = Long.valueOf(String.valueOf(in.get("id"))).longValue();
}
catch (Exception e) {}
return ret;
}
}
package com.orhon.smartcampus.material.basicComponents;
import lombok.Data;
@Data
public class GQLCardType {
private Long id;
private String name;
}
package com.orhon.smartcampus.material.basicComponents;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Optional;
import lombok.Data;
import java.util.Map;
@Data
public class GQLLang {
private String zh;
private String en;
private String mn;
public GQLLang(){
}
public static String getZhs(String jsonStr){
Map<String,String> jLang = (Map) JSON.parse(jsonStr);
String ret = "";
try{
ret = jLang.get("zh");
}
catch (Exception e){
ret = "";
}
return ret;
}
public static String getEns(String jsonStr){
Map<String,String> jLang = (Map) JSON.parse(jsonStr);
String ret = "";
try{
ret = jLang.get("en");
}
catch (Exception e){
ret = "";
}
return ret;
}
public static String getMns(String jsonStr){
Map<String,String> jLang = (Map) JSON.parse(jsonStr);
String ret = "";
try{
ret = jLang.get("mn");
}
catch (Exception e){
ret = "";
}
return ret;
}
public GQLLang(String jsonStr){
Map<String,String> jLang = (Map) JSON.parse(jsonStr);
try {
Optional<String> m_ZH = Optional.fromNullable(jLang.get("zh"));
Optional<String> m_EN = Optional.fromNullable(jLang.get("en"));
Optional<String> m_MN = Optional.fromNullable(jLang.get("mn"));
this.zh = m_ZH.or("");
this.en = m_EN.or("");
this.mn = m_MN.or("");
}
catch (Exception e){
this.zh = "";
this.en = "";
this.mn = "";
}
}
}
package com.orhon.smartcampus.material.basicComponents;
import lombok.Data;
@Data
public class GQLLangInput {
private String zh;
private String en;
private String mn;
}
package com.orhon.smartcampus.material.basicComponents;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class Result extends HashMap<String, Object> {
private int code;
private String msg;
private Object data;
private Object pagenation;
private static final long serialVersionUID = 1L;
public Result() {
put("code", 200);
put("msg", "success");
}
public static Result error() {
Result r = new Result();
r.put("code", 500);
r.put("msg", "错误!");
return r;
}
public static Result error(String msg) {
return error(500, msg);
}
public static Result error(int code, String msg) {
Result r = new Result();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static Result ok(String msg) {
Result r = new Result();
r.put("msg", msg);
return r;
}
public static Result ok(Map<String, Object> map) {
Result r = new Result();
r.putAll(map);
return r;
}
public static Result ok() {
return new Result();
}
public static Result timeOut() {
Result r = new Result();
r.put("code", 10000);
r.put("msg", "修改超时");
return r;
}
public static Result parameterIsNul() {
Result r = new Result();
r.put("code", 10001);
r.put("msg", "参数为空");
return r;
}
public static Result Repeat() {
Result r = new Result();
r.put("msg", "重复提交");
return r;
}
public Result put(String key, Object value) {
if(value==null) {
Object object = new Object();
super.put(key, object);
return this;
}
super.put(key, value);
return this;
}
}
package com.orhon.smartcampus.material.basicComponents.baseDao;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate4.HibernateTemplate;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface BaseDao<T> {
public T save(T t) throws Exception;
public T add(T t) throws Exception;
public void saveOrUpdate(T t) throws Exception;
public void update(T t) throws Exception;
public void merge(T t) throws Exception;
public void delete(T t) throws Exception;
public T get(Class<T> entityClass, Serializable id);
public void deleteById(Serializable id) throws Exception;
public T findById(Serializable id) throws Exception;
public List<T> find(String hql, String[] paramNames, Object[] values);
public List find(final String hql, final Map<String, Object> param, final int pageNo,
final int pageSize);
public List<T> find(final String hql, final Map<String, Object> param);
public Object getById(Class c, Serializable id);
public List findHql(final String hql, final Map<String, Object> param);
public int updateHql(String hql);
public List<T> find(String hql);
public List findHql(String hql);
public HibernateTemplate getTemplate();
public List myFind(final String hql, final Map<String, Object> param, final int pageNo,
final int pageSize);
public int total(final String hql, final Map<String, Object> param);
public Long getTotalCount(String entityName);
public Criteria createCriteria(String entityName);
public List<?> findByCriteria(DetachedCriteria criteria, Integer page, Integer limit);
public List<?> findByCriteria(DetachedCriteria criteria);
public Session getSession();
public Object findId(final String hql, final Map<String, Object> param);
}
package com.orhon.smartcampus.material.basicComponents.router;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.orhon.smartcampus.material.gql.scalars.ExtendedScalars;
//import com.orhon.smartcampus.material.modules.management.fetcher.GoodsClassifyFetcher;
//import com.orhon.smartcampus.material.modules.management.fetcher.MaterialFetchersLoader;
//import com.orhon.smartcampus.modules.base.fetcher.BaseFetchersLoader;
//import com.orhon.smartcampus.modules.baseinfo.fetcher.BaseInfoFetcherLoader;
//import com.orhon.smartcampus.modules.gql.fetcher.UserDetailsFetcher;
//import com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars;
//import com.orhon.smartcampus.modules.material.fetcher.MaterialFetchersLoader;
//import com.orhon.smartcampus.modules.student.fetcher.StudentFetchersLoader;
//import com.orhon.smartcampus.modules.systemctl.fetcher.SystemCtlFetchersLoader;
//import com.orhon.smartcampus.modules.teacher.fetcher.TeacherFetchersLoader;
//import com.orhon.smartcampus.modules.user.fetcher.UserFetchersLoader;
import com.orhon.smartcampus.material.modules.management.fetcher.MaterialFetchersLoader;
import graphql.schema.*;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
/**
* 整合第三方工具,整合springboot
* 2019年
*
* @Author M
*/
@Component
public class SpringBootStart {
protected final static String TYPE_QUERY = "Query";
protected final static String TYPE_MUTATION = "Mutation";
public final static String SCHEMA_ROOT = "graphql/root.graphqls";
public final static String SCHEMA_BASIC = "graphql/basic.graphqls";
// public final static String SCHEMA_USER = "graphql/user.graphqls";
// public final static String SCHEMA_TEACHER = "graphql/teacher.graphqls";
// public final static String SCHEMA_STUDENT = "graphql/student.graphqls";
// public final static String SCHEMA_ECLASS = "graphql/eclass.graphqls";
public final static String SCHEMA_MATERIAL = "graphql/material.graphqls";
// public final static String SCHEMA_SCHOOLBASEINFO= "graphql/schoolbaseinfo.graphqls";
// public final static String SCHEMA_SYSTEMCTL= "graphql/systemctl.graphqls";
// public final static String SCHEMA_STATISTICS= "graphql/teacherstatistics.graphqls";
// @Autowired
// SystemCtlFetchersLoader systemCtlFetchersLoader;
// @Autowired
// UserFetchersLoader userFetchersLoaderl;
//
// @Autowired
// StudentFetchersLoader studentFetchersLoader;
//
// @Autowired
// TeacherFetchersLoader teacherFetchersLoader;
//
// @Autowired
// BaseInfoFetcherLoader baseInfoFetcherLoader;
//
// @Autowired
// BaseFetchersLoader baseFetchersLoader;
@Autowired
MaterialFetchersLoader materialFetchersLoader;
@Bean
public GraphQLSchema schema() throws IOException {
GraphQLSchema schema = loadSchma();
return schema;
}
public void init(){
}
/**
* 定义schema文件列表...
*/
protected String[] getSchemas(){
return new String[]{SCHEMA_ROOT , SCHEMA_BASIC ,SCHEMA_MATERIAL};
//return new String[]{SCHEMA_ROOT , SCHEMA_BASIC ,SCHEMA_USER , SCHEMA_TEACHER ,SCHEMA_STUDENT, SCHEMA_ECLASS,SCHEMA_MATERIAL, SCHEMA_SCHOOLBASEINFO,SCHEMA_SYSTEMCTL,SCHEMA_STATISTICS };
}
/**
* 获取graphql schema结构...
*/
private GraphQLSchema loadSchma() throws IOException {
SchemaParser parser = new SchemaParser();
SchemaGenerator generator = new SchemaGenerator();
String[] fileList = getSchemas();
TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
for(String current: fileList) {
String schemaSDL = loadSchemaFile(current);
typeRegistry.merge(parser.parse(schemaSDL));
}
GraphQLSchema schema = generator.makeExecutableSchema(typeRegistry, buildDynamicRuntimeWiring());
return schema;
}
/**
* 加载schema文件
* @param fileName
* @return
* @throws IOException
*/
protected String loadSchemaFile(String fileName) throws IOException {
URL url = Resources.getResource(fileName);
String sdl = Resources.toString(url, Charsets.UTF_8);
return sdl;
}
/**
* 自定义变量 , 本办法在框架中被抛弃,需要重构 。。。
*/
public static final GraphQLScalarType GQLDate = new GraphQLScalarType("Date" , "" , new Coercing(){
@Override
public Object serialize(Object dataFetcherResult) throws CoercingSerializeException {
Date d = (Date)dataFetcherResult;
Long orgData = d.getTime();
return orgData / 1000;
}
@Override
public Object parseValue(Object input) throws CoercingParseValueException {
return input;
}
@Override
public Object parseLiteral(Object input) throws CoercingParseLiteralException {
return input;
}
});
protected RuntimeWiring buildDynamicRuntimeWiring() {
RuntimeWiring.Builder builder = RuntimeWiring.newRuntimeWiring();
//builder.scalar(GQLDate);
builder.scalar(ExtendedScalars.Time);
builder.scalar(ExtendedScalars.DateTime);
builder.scalar(ExtendedScalars.Date);
builder.scalar(ExtendedScalars.Json);
builder.scalar(ExtendedScalars.Object);
builder.scalar(ExtendedScalars.Locale);
builder.type(TYPE_QUERY , typeWiring-> typeWiring.dataFetcher("hello" , new StaticDataFetcher("world")));
//builder.type(TYPE_QUERY , typeWiring-> typeWiring.dataFetcher("user" , UserDetailsFetcher.detailFetcher));
//
// //系统设置加载..
// systemCtlFetchersLoader.LoadFetchers(builder);
// //用户fetchers加载
// userFetchersLoaderl.LoadFetchers(builder);
// //学生fetchers加载
// studentFetchersLoader.LoadFetchers(builder);
// //教师fetchers加载
// teacherFetchersLoader.LoadFetchers(builder);
// //baseinfo fetchers load
// baseInfoFetcherLoader.LoadFetchers(builder);
// //base fetchers 加载
// baseFetchersLoader.LoadFetchers(builder);
//material fetcher 加载
materialFetchersLoader.LoadFetchers(builder);
return builder.build();
}
}
package com.orhon.smartcampus.material.basicComponents.service;
import java.sql.Timestamp;
import java.util.Date;
public class DateService {
public static Date convertDbDate(Object dbDate){
if (dbDate == null){
return null;
}
try {
Date date = new Date(Long.parseLong(dbDate.toString()));
return date;
} catch (Exception e) {
Timestamp t = Timestamp.valueOf(dbDate.toString());
return new Date(t.getTime());
}
}
}
package com.orhon.smartcampus.material.basicComponents.service;
//import com.orhon.smartcampus.modules.base.dao.DictionaryDao;
//import com.orhon.smartcampus.modules.base.dao.RegionsDao;
//import com.orhon.smartcampus.modules.base.entity.Dictionary;
//import com.orhon.smartcampus.modules.base.entity.Regions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Service
public class GQLRunService implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
}
// @Autowired
// private DictionaryDao dictionaryDao;
// @Autowired
// private RegionsDao regionsDao;
//
//
// private static HashMap<String, Object> DictionaryMap = new HashMap<String, Object>();
//
// private static HashMap<String, Object> RegionMap = new HashMap<String, Object>();
//
//
//
// @Override
// public void run(ApplicationArguments args) throws Exception {
// ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// service.scheduleAtFixedRate(runnable, 1, 60*10, TimeUnit.SECONDS);
// }
//
// Runnable runnable = new Runnable() {
// public void run() {
// String hql = "from Dictionary";
// List<Dictionary> list = dictionaryDao.find(hql,null,0,0);
// for (Dictionary dictionary : list) {
// DictionaryMap.put(dictionary.getDictionaryValue(), dictionary);
// }
// String hql1 = "from Regions ";
// List<Regions> list1 = regionsDao.find(hql1,null,0,0);
// for (Regions regions : list1) {
// if(regions.getId()!=null && regions.getRegionName()!=null) {
// RegionMap.put(regions.getId().toString(),regions);
// }
// }
// }
// };
//
// public static HashMap<String, Object> DictionaryMap() {
// return DictionaryMap;
// }
//
// public static HashMap<String, Object> RegionMap() {
// return RegionMap;
// }
}
package com.orhon.smartcampus.material.basicComponents.service;
import com.google.common.base.Optional;
//import com.orhon.smartcampus.basicComponents.GQLLang;
//import com.orhon.smartcampus.modules.base.gqlModel.GQLDictionary;
//import com.orhon.smartcampus.modules.base.gqlModel.GQLRegion;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Component
public class GQLUtil {
//
// @Autowired
// private SessionFactory sessionFactory;
// private static SessionFactory statisSessionFactory;
//
// @Autowired
// private HibernateTemplate hibernateTemplate;
// private static HibernateTemplate statichibernateTemplate;
//
// @PostConstruct
// public void init(){
// statisSessionFactory = sessionFactory;
// statichibernateTemplate = hibernateTemplate;
// }
// public static GQLRegion Region (HashMap<String,Object> item) {
// GQLRegion gqlregion = new GQLRegion();
// if(item!=null&&item.size()>0) {
// gqlregion.setId(Long.valueOf(item.get("id").toString()));
// gqlregion.setSlug((String)item.get("region_slug"));
// gqlregion.setLevel((Integer)item.get("level"));
// gqlregion.setOrder((Integer)item.get("region_order"));
// gqlregion.setCreated_at(DateService.convertDbDate(item.get("created_at")));
// gqlregion.setUpdated_at(DateService.convertDbDate(item.get("created_at")));
// gqlregion.setDeleted_at(DateService.convertDbDate(item.get("created_at")));
// gqlregion.setName(Lang(item.get("region_name").toString()));
// }
// return gqlregion;
// }
// /**
// * 数据字典
// */
//
// public static GQLDictionary getDictionary(HashMap<String, Object> item){
// GQLDictionary dictionary = new GQLDictionary();
// if(item!=null) {
// dictionary.setId(Long.parseLong(item.get("id").toString()));
// dictionary.setParent_id(Long.parseLong(item.get("parent_id").toString()));
// dictionary.setAlias((String)item.get("alias"));
// dictionary.setType((String)item.get("type"));
// dictionary.setName(Lang(item.get("dictionary_name").toString()));
// dictionary.setDescription(Lang(item.get("dictionary_description").toString()));
// //dictionary.setStatus(item.get("status"));
// dictionary.setMeta(Lang(item.get("meta")));
// dictionary.setValue((String)item.get("dictionary_value"));
// }
// return dictionary;
// }
//
// @Transactional
// public static List findPage(final String hql ,final int page ,final int pageSize){
// List list = (List)statichibernateTemplate.execute(new HibernateCallback(){public Object doInHibernate(Session session)
// throws HibernateException {
// String hql1 = "from "+hql;
// Query query = session.createQuery(hql1);
// if(pageSize==0) {
// return query.list();
// }else {
// int begin = (page-1)*pageSize;
// query.setFirstResult(begin);
// query.setMaxResults(pageSize);
// return query.list();
// }
// }});
// return list;
// }
// @Transactional
// public static List findIds(final String hql,String ids){
// List list = (List)statichibernateTemplate.execute(new HibernateCallback(){public Object doInHibernate(Session session)
// throws HibernateException {
// String hql1 = "from "+hql;
// Query query = session.createQuery(hql1);
// query.setParameter("id", ids);
// return query.list();
//
// }});
// return list;
// }
// @Transactional
// public static Object findObject(final String hql){
// Object obj = statichibernateTemplate.execute(new HibernateCallback(){
// public Object doInHibernate(Session session)
// throws HibernateException {
// String hql1 = "from "+hql;
// Query query = session.createQuery(hql1);
// List list = query.list();
// if(list.size()>0&&list!=null) {
// return list.get(0);
// }else {
// return null;
// }
// }});
// return obj;
// }
//
// @Transactional
// public static int total(final String hql){
// //利用HibernateTemplate.execute()方法,以回调方式使用,不需要关闭session
// String total = (String)statichibernateTemplate.execute(new HibernateCallback(){
// public Object doInHibernate(Session session)
// throws HibernateException {
// String hql1 = "select count(*) from "+hql;
// Query query = session.createQuery(hql1);
// return query.list().get(0).toString();
// }});
// return Integer.parseInt(total);
// }
//
// public static GQLLang Lang(Object item) {
// if(item ==null || item.equals(null)) {
// return null;
// }
// Optional<String> a = Optional.of(((String)item) );
// GQLLang b = new GQLLang(a.or("{}"));
// return b;
//
// }
//
// public static List StringToList(String ids) {
// if(ids==null) {
// return null;
// }
// String substring = ids.substring(1, ids.length()-1);
// if(substring.split(",").length >0 || !substring.equals(null)) {
// ArrayList list = new ArrayList();
// String[] id = substring.split(",");
// for (String string : id) {
// try {
// int i = Integer.parseInt(string);
// list.add(string);
// } catch (Exception e) {
// String string2 = string.substring(1, string.length()-1);
// list.add(string2);
// }
// }
// return list;
// }
// return null;
//
//
// }
}
package com.orhon.smartcampus.material.basicComponents.service;
public class GqlService extends GraphqlService {
}
package com.orhon.smartcampus.material.basicComponents.service;
public abstract class GraphqlService {
protected final static String TYPE_QUERY = "Query";
protected final static String TYPE_MUTATION = "Mutation";
}
package com.orhon.smartcampus.material.config;//package com.orhon.smartcampus.config;
//
//
//import org.activiti.engine.*;
//import org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration;
//import org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration;
//import org.activiti.engine.impl.interceptor.SessionFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import com.orhon.smartcampus.modules.activiti.CustomGroupEntityManager;
//import com.orhon.smartcampus.modules.activiti.CustomGroupEntityManagerFactory;
//import com.orhon.smartcampus.modules.activiti.CustomUserEntityManager;
//import com.orhon.smartcampus.modules.activiti.CustomUserEntityManagerFactory;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import javax.sql.DataSource;
//
//@Configuration
//public class ActivitiConfig {
//
// @Autowired
// private DataSource dataSource;
//
// @Autowired
// private CustomGroupEntityManagerFactory customGroupEntityManagerFactory;
//
// @Autowired
// private CustomUserEntityManagerFactory customUserEntityManagerFactory;
//
//
// @Bean
// public StandaloneProcessEngineConfiguration processEngineConfiguration(){
// StandaloneProcessEngineConfiguration configuration = new StandaloneInMemProcessEngineConfiguration();
// configuration.setDataSource(this.dataSource);
// configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
// configuration.setAsyncExecutorActivate(false);
// List<SessionFactory> factory = new ArrayList<SessionFactory>();
// factory.add(customGroupEntityManagerFactory);
// factory.add(customUserEntityManagerFactory);
// configuration.setCustomSessionFactories(factory);
// return configuration;
// }
//
//
// @Bean
// public ProcessEngine processEngine(){
// return processEngineConfiguration().buildProcessEngine();
// }
//
//
// @Bean
// public RepositoryService repositoryService(){
// return processEngine().getRepositoryService();
// }
//
// @Bean
// public RuntimeService runtimeService(){
// return processEngine().getRuntimeService();
// }
//
// @Bean
// public TaskService taskService(){
// return processEngine().getTaskService();
// }
//
// @Bean
// public HistoryService historyService(){
// return processEngine().getHistoryService();
// }
//
//
//
//
//
//
//}
package com.orhon.smartcampus.material.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins("*")
// .allowCredentials(true)
// .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
// .maxAge(3600);
// }
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders(HttpHeaders.SET_COOKIE)
// .exposedHeaders("access-control-allow-headers",
// "access-control-allow-methods",
// "access-control-allow-origin",
// "access-control-max-age",
// "X-Frame-Options")
.maxAge(3600);
}
};
}
}
\ No newline at end of file
package com.orhon.smartcampus.material.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DynamicDataSourceConfig {
@Bean
public ServletRegistrationBean statViewServlet(){
//创建servlet注册实体
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//设置ip白名单
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
//设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
servletRegistrationBean.addInitParameter("deny","192.168.0.19");
//设置控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername","druid");
servletRegistrationBean.addInitParameter("loginPassword","123456");
//是否可以重置数据
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean statFilter(){
//创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns("/*");
//忽略过滤的形式
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
package com.orhon.smartcampus.material.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GQLObjectMapper {
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
/*
mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
{
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException
{
jsonGenerator.writeString("空数字~~");
}
});
*/
return mapper;
}
}
package com.orhon.smartcampus.material.config;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EntityScan(basePackages = "com.orhon.smartcampus.material")
public class HibernateConfig {
@Autowired
private DataSource dataSource;
@Bean
public Object testBean(PlatformTransactionManager platformTransactionManager){
System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());
return new Object();
}
@Bean
public LocalSessionFactoryBean factoryBean(){
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPackagesToScan(
new String[] {
"com.orhon.smartcampus.material.modules"
});
factoryBean.setHibernateProperties(hibernateProperties());
SessionFactory object = factoryBean.getObject();
return factoryBean;
}
//如果没有这个函数……
//PlatformTransactionManager将会是org.springframework.jdbc.datasource.DataSourceTransactionManager
//如果这个函数存在
///PlatformTransactionManager将会是org.springframework.orm.hibernate4.HibernateTransactionManager
@Bean
public HibernateTransactionManager transactionManager(){
HibernateTransactionManager manager = new HibernateTransactionManager();
manager.setDataSource(this.dataSource);
manager.setSessionFactory(factoryBean().getObject());
return manager;
}
@Bean
public HibernateTemplate hibernateTemplate(){
HibernateTemplate hibernateTemplate = new HibernateTemplate();
hibernateTemplate.setSessionFactory(factoryBean().getObject());
return hibernateTemplate;
}
// @Bean
// public OpenEntityManagerInViewFilter openEntityManagerInViewFilter() {
// return new OpenEntityManagerInViewFilter();
// }
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", "none");
setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
setProperty("hibernate.globally_quoted_identifiers","false");
setProperty("hibernate.show_sql" , "true");
setProperty("hibernate.current_session_context_class" , "org.springframework.orm.hibernate4.SpringSessionContext");
setProperty("ENABLE_LAZY_LOAD_NO_TRANS" , "true");
setProperty("hibernate.enable_lazy_load_no_trans" , "true");
}
};
}
}
package com.orhon.smartcampus.material.config;
/**
* redis配置<br>
* 集群下启动session共享,需打开@EnableRedisHttpSession<br>
* 单机下不需要
*
* @author caodw
*
*
*/
//@EnableRedisHttpSession
//@Configuration
public class RedisConfig {
/*
public String host = "39.104.181.104";
public Integer port = 6379;
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean("redisTemplate")
public RedisTemplate redisTemplate(@Lazy RedisConnectionFactory connectionFactory) {
RedisTemplate redis = new RedisTemplate();
GenericToStringSerializer<String> keySerializer = new GenericToStringSerializer<String>(String.class);
redis.setKeySerializer(keySerializer);
redis.setHashKeySerializer(keySerializer);
GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
StringRedisSerializer serializer = new StringRedisSerializer(Charset.forName("UTF-8"));
redis.setValueSerializer(valueSerializer);
redis.setHashValueSerializer(serializer);
redis.setConnectionFactory(connectionFactory);
return redis;
}
@Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//最大连接数
jedisPoolConfig.setMaxTotal(100);
//最小空闲连接数
jedisPoolConfig.setMinIdle(20);
//当池内没有可用连接时,最大等待时间
jedisPoolConfig.setMaxWaitMillis(10000);
//其他属性可以自行添加
return jedisPoolConfig;
}
@Bean
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
//设置redis服务器的host或者ip地址
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
//获得默认的连接池构造
//这里需要注意的是,edisConnectionFactoryJ对于Standalone模式的没有(RedisStandaloneConfiguration,JedisPoolConfig)的构造函数,对此
//我们用JedisClientConfiguration接口的builder方法实例化一个构造器,还得类型转换
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
//修改我们的连接池配置
jpcf.poolConfig(jedisPoolConfig);
//通过构造器来构造jedis客户端配置
JedisClientConfiguration jedisClientConfiguration = jpcf.build();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
*/
}
package com.orhon.smartcampus.material.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//
@Configuration
public class StaticResHandler extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/mappers/**").addResourceLocations("classpath:/mappers/");
registry.addResourceHandler("/static/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/static/img/**").addResourceLocations("classpath:/static/img/");
registry.addResourceHandler("/static/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/static/activiti/**").addResourceLocations("classpath:/static/activiti/");
super.addResourceHandlers(registry);
}
}
package com.orhon.smartcampus.material.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.orhon.smartcampus.material.gql.scalars;
import com.orhon.smartcampus.material.gql.scalars.alias.AliasedScalar;
import com.orhon.smartcampus.material.gql.scalars.datetime.DateScalar;
import com.orhon.smartcampus.material.gql.scalars.datetime.DateTimeScalar;
import com.orhon.smartcampus.material.gql.scalars.datetime.TimeScalar;
import com.orhon.smartcampus.material.gql.scalars.locale.LocaleScalar;
import com.orhon.smartcampus.material.gql.scalars.numeric.*;
import com.orhon.smartcampus.material.gql.scalars.object.JsonScalar;
import com.orhon.smartcampus.material.gql.scalars.object.ObjectScalar;
import com.orhon.smartcampus.material.gql.scalars.regex.RegexScalar;
import graphql.PublicApi;
import graphql.schema.GraphQLScalarType;
/**
* This is the API entry point for all the extended scalars
*/
@PublicApi
public class ExtendedScalars {
/**
* An RFC-3339 compliant date time scalar that accepts string values like `1996-12-19T16:39:57-08:00` and produces
* `java.time.OffsetDateTime` objects at runtime.
* <p>
* Its {@link graphql.schema.Coercing#serialize(java.lang.Object)} and {@link graphql.schema.Coercing#parseValue(java.lang.Object)} methods
* accept OffsetDateTime, ZoneDateTime and formatted Strings as valid objects.
* <p>
* See the <a href="https://www.ietf.org/rfc/rfc3339.txt">rfc3339 spec</a> for more details on the format.
*
* @see java.time.OffsetDateTime
* @see java.time.ZonedDateTime
*/
public static GraphQLScalarType DateTime = new DateTimeScalar();
/**
* An RFC-3339 compliant date scalar that accepts string values like `1996-12-19` and produces
* `java.time.LocalDate` objects at runtime.
* <p>
* Its {@link graphql.schema.Coercing#serialize(java.lang.Object)} and {@link graphql.schema.Coercing#parseValue(java.lang.Object)} methods
* accept date {@link java.time.temporal.TemporalAccessor}s and formatted Strings as valid objects.
* <p>
* See the <a href="https://www.ietf.org/rfc/rfc3339.txt">rfc3339 spec</a> for more details on the format.
*
* @see java.time.LocalDate
*/
public static GraphQLScalarType Date = new DateScalar();
/**
* An RFC-3339 compliant time scalar that accepts string values like `6:39:57-08:00` and produces
* `java.time.OffsetTime` objects at runtime.
* <p>
* Its {@link graphql.schema.Coercing#serialize(java.lang.Object)} and {@link graphql.schema.Coercing#parseValue(java.lang.Object)} methods
* accept time {@link java.time.temporal.TemporalAccessor}s and formatted Strings as valid objects.
* <p>
* See the <a href="https://www.ietf.org/rfc/rfc3339.txt">rfc3339 spec</a> for more details on the format.
*
* @see java.time.OffsetTime
*/
public static GraphQLScalarType Time = new TimeScalar();
/**
* An object scalar allows you to have a multi level data value without defining it in the graphql schema.
* <p>
* It might be useful when you have opaque data coming from a backend system that you want to pass on
* but cant provide the actual graphql schema definition for.
* <p>
* <b>Use this with caution</b> since is breaks one of the key benefits
* of graphql, which is that a schema describes the shape of the data that can be queried.
*
* <p>
* This can be declared as follows :
* <pre>
* {@code
*
* type Customer {
* name : String
* backendDetails : Object
* }
* }
* </pre>
*
* @see #Json
*/
public static GraphQLScalarType Object = new ObjectScalar();
/**
* A synonym class for the {@link #Object} scalar, since some people prefer their SDL to look like the following :
*
* <pre>
* {@code
*
* type Customer {
* name : String
* backendDetails : JSON
* }
* }
* </pre>
*
* @see static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Object
*/
public static GraphQLScalarType Json = new JsonScalar();
/**
* A URL scalar that accepts URL strings and produces {@link java.net.URL} objects at runtime
*/
//public static GraphQLScalarType Url = new UrlScalar();
/**
* A Locale scalar that accepts a IETF BCP 47 language tag string and produces {@link
* java.util.Locale} objects at runtime.
*/
public static GraphQLScalarType Locale = new LocaleScalar();
/**
* An `Int` scalar that MUST be greater than zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLInt
*/
public static GraphQLScalarType PositiveInt = new PositiveIntScalar();
/**
* An `Int` scalar that MUST be less than zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLInt
*/
public static GraphQLScalarType NegativeInt = new NegativeIntScalar();
/**
* An `Int` scalar that MUST be less than or equal to zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLInt
*/
public static GraphQLScalarType NonPositiveInt = new NonPositiveIntScalar();
/**
* An `Int` scalar that MUST be greater than or equal to zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLInt
*/
public static GraphQLScalarType NonNegativeInt = new NonNegativeIntScalar();
/**
* An `Float` scalar that MUST be greater than zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLFloat
*/
public static GraphQLScalarType PositiveFloat = new PositiveFloatScalar();
/**
* An `Float` scalar that MUST be less than zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLFloat
*/
public static GraphQLScalarType NegativeFloat = new NegativeFloatScalar();
/**
* An `Float` scalar that MUST be less than or equal to zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLFloat
*/
public static GraphQLScalarType NonPositiveFloat = new NonPositiveFloatScalar();
/**
* An `Float` scalar that MUST be greater than or equal to zero
*
* @see static com.orhon.smartcampus.modules.gql.scalars#GraphQLFloat
*/
public static GraphQLScalarType NonNegativeFloat = new NonNegativeFloatScalar();
/**
* A builder of a scalar that uses one or more regular expression {@link java.util.regex.Pattern}s to control
* the acceptable values for that scalar.
* <p>
* The scalar converts any passed in objects to Strings first and them matches it against the provided
* scalars to ensure its an acceptable value.
*
* @return a builder of a regex scalar
*/
public static RegexScalar.Builder newRegexScalar(String name) {
return new RegexScalar.Builder().name(name);
}
/**
* This allows an existing scalar to be wrapped and aliased with a new name.
* <p>
* For example you may take a `String` scalar and alias it as `SocialMediaLink` if that helps introduce
* more semantic meaning to your type system.
* <p>
* <pre>
* {@code
*
* type Customer {
* name : String
* socialMediaLink : SocialMediaLink
* }
* }
* </pre>
* <p>
* A future version of the graphql specification may add this capability but in the meantime you can use this facility.
*
* @return a builder of a aliased scalar
*/
public static AliasedScalar.Builder newAliasedScalar(String name) {
return new AliasedScalar.Builder().name(name);
}
}
package com.orhon.smartcampus.material.gql.scalars.alias;
import graphql.Assert;
import graphql.Internal;
import graphql.schema.*;
import java.util.Map;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#newAliasedScalar(String)}
*/
@Internal
public class AliasedScalar extends GraphQLScalarType {
/**
* A builder for {@link static com.orhon.smartcampus.modules.gql.scalars.alias.AliasedScalar}
*/
public static class Builder {
private String name;
private String description;
private GraphQLScalarType aliasedScalar;
/**
* Sets the name of the aliased scalar
*
* @param name the name of the aliased scalar
*
* @return this builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Sets the description of the aliased scalar
*
* @param description the description of the aliased scalar
*
* @return this builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Sets the scalar that is to be aliased
*
* @param aliasedScalar the scalar that is to be aliased
*
* @return this builder
*/
public Builder aliasedScalar(GraphQLScalarType aliasedScalar) {
this.aliasedScalar = aliasedScalar;
return this;
}
/**
* @return the built {@link AliasedScalar}
*/
public AliasedScalar build() {
Assert.assertNotNull(name);
return aliasedScalarImpl(name, description, aliasedScalar);
}
}
private AliasedScalar(String name, String description, Coercing coercing) {
super(name, description, coercing);
}
private static AliasedScalar aliasedScalarImpl(String name, String description, GraphQLScalarType aliasedScalar) {
Assert.assertNotNull(aliasedScalar);
return new AliasedScalar(name, description, new Coercing<Object, Object>() {
@Override
public Object serialize(Object input) throws CoercingSerializeException {
return aliasedScalar.getCoercing().serialize(input);
}
@Override
public Object parseValue(Object input) throws CoercingParseValueException {
return aliasedScalar.getCoercing().parseValue(input);
}
@Override
public Object parseLiteral(Object input) throws CoercingParseLiteralException {
return aliasedScalar.getCoercing().parseLiteral(input);
}
@Override
public Object parseLiteral(Object input, Map<String, Object> variables) throws CoercingParseLiteralException {
return aliasedScalar.getCoercing().parseLiteral(input, variables);
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.datetime;
import graphql.Internal;
import graphql.language.StringValue;
import graphql.schema.*;
import java.sql.Timestamp;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.function.Function;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Date}
*/
@Internal
public class DateScalar extends GraphQLScalarType {
private final static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public DateScalar() {
super("Date", "An RFC-3339 compliant Full Date Scalar", new Coercing<LocalDate, String>() {
@Override
public String serialize(Object input) throws CoercingSerializeException {
TemporalAccessor temporalAccessor;
if (input instanceof TemporalAccessor) {
temporalAccessor = (TemporalAccessor) input;
} else if (input instanceof String) {
temporalAccessor = parseLocalDate(input.toString(), CoercingSerializeException::new);
}
else if ( input instanceof Timestamp){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date fDate = formatter.parse(input.toString(), pos);
temporalAccessor = fDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
else {
throw new CoercingSerializeException(
"Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was '" + typeName(input) + "'."
);
}
try {
return dateFormatter.format(temporalAccessor);
} catch (DateTimeException e) {
throw new CoercingSerializeException(
"Unable to turn TemporalAccessor into full date because of : '" + e.getMessage() + "'."
);
}
}
@Override
public LocalDate parseValue(Object input) throws CoercingParseValueException {
TemporalAccessor temporalAccessor;
if (input instanceof TemporalAccessor) {
temporalAccessor = (TemporalAccessor) input;
} else if (input instanceof String) {
temporalAccessor = parseLocalDate(input.toString(), CoercingParseValueException::new);
} else {
throw new CoercingParseValueException(
"Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was '" + typeName(input) + "'."
);
}
try {
return LocalDate.from(temporalAccessor);
} catch (DateTimeException e) {
throw new CoercingParseValueException(
"Unable to turn TemporalAccessor into full date because of : '" + e.getMessage() + "'."
);
}
}
@Override
public LocalDate parseLiteral(Object input) throws CoercingParseLiteralException {
if (!(input instanceof StringValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + typeName(input) + "'."
);
}
return parseLocalDate(((StringValue) input).getValue(), CoercingParseLiteralException::new);
}
private LocalDate parseLocalDate(String s, Function<String, RuntimeException> exceptionMaker) {
try {
TemporalAccessor temporalAccessor = dateFormatter.parse(s);
return LocalDate.from(temporalAccessor);
} catch (DateTimeParseException e) {
throw exceptionMaker.apply("Invalid RFC3339 full date value : '" + s + "'. because of : '" + e.getMessage() + "'");
}
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.datetime;
import graphql.Internal;
import graphql.language.StringValue;
import graphql.schema.*;
import java.time.DateTimeException;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.function.Function;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* Access this via {@link com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#DateTime}
*/
@Internal
public class DateTimeScalar extends GraphQLScalarType {
public DateTimeScalar() {
super("DateTime", "An RFC-3339 compliant DateTime Scalar", new Coercing<OffsetDateTime, String>() {
@Override
public String serialize(Object input) throws CoercingSerializeException {
OffsetDateTime offsetDateTime;
if (input instanceof OffsetDateTime) {
offsetDateTime = (OffsetDateTime) input;
} else if (input instanceof ZonedDateTime) {
offsetDateTime = ((ZonedDateTime) input).toOffsetDateTime();
} else if (input instanceof String) {
offsetDateTime = parseOffsetDateTime(input.toString(), CoercingSerializeException::new);
} else {
throw new CoercingSerializeException(
"Expected something we can convert to 'java.time.OffsetDateTime' but was '" + typeName(input) + "'."
);
}
try {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime);
} catch (DateTimeException e) {
throw new CoercingSerializeException(
"Unable to turn TemporalAccessor into OffsetDateTime because of : '" + e.getMessage() + "'."
);
}
}
@Override
public OffsetDateTime parseValue(Object input) throws CoercingParseValueException {
OffsetDateTime offsetDateTime;
if (input instanceof OffsetDateTime) {
offsetDateTime = (OffsetDateTime) input;
} else if (input instanceof ZonedDateTime) {
offsetDateTime = ((ZonedDateTime) input).toOffsetDateTime();
} else if (input instanceof String) {
offsetDateTime = parseOffsetDateTime(input.toString(), CoercingParseValueException::new);
} else {
throw new CoercingParseValueException(
"Expected a 'String' but was '" + typeName(input) + "'."
);
}
return offsetDateTime;
}
@Override
public OffsetDateTime parseLiteral(Object input) throws CoercingParseLiteralException {
if (!(input instanceof StringValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + typeName(input) + "'."
);
}
return parseOffsetDateTime(((StringValue) input).getValue(), CoercingParseLiteralException::new);
}
private OffsetDateTime parseOffsetDateTime(String s, Function<String, RuntimeException> exceptionMaker) {
try {
return OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} catch (DateTimeParseException e) {
throw exceptionMaker.apply("Invalid RFC3339 value : '" + s + "'. because of : '" + e.getMessage() + "'");
}
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.datetime;
import graphql.Internal;
import graphql.language.StringValue;
import graphql.schema.*;
import java.time.DateTimeException;
import java.time.OffsetTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.function.Function;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Time}
*/
@Internal
public class TimeScalar extends GraphQLScalarType {
private final static DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_OFFSET_TIME;
public TimeScalar() {
super("Time", "An RFC-3339 compliant Full Time Scalar", new Coercing<OffsetTime, String>() {
@Override
public String serialize(Object input) throws CoercingSerializeException {
TemporalAccessor temporalAccessor;
if (input instanceof TemporalAccessor) {
temporalAccessor = (TemporalAccessor) input;
} else if (input instanceof String) {
temporalAccessor = parseOffsetTime(input.toString(), CoercingSerializeException::new);
} else {
throw new CoercingSerializeException(
"Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was '" + typeName(input) + "'."
);
}
try {
return dateFormatter.format(temporalAccessor);
} catch (DateTimeException e) {
throw new CoercingSerializeException(
"Unable to turn TemporalAccessor into full time because of : '" + e.getMessage() + "'."
);
}
}
@Override
public OffsetTime parseValue(Object input) throws CoercingParseValueException {
TemporalAccessor temporalAccessor;
if (input instanceof TemporalAccessor) {
temporalAccessor = (TemporalAccessor) input;
} else if (input instanceof String) {
temporalAccessor = parseOffsetTime(input.toString(), CoercingParseValueException::new);
} else {
throw new CoercingParseValueException(
"Expected a 'String' or 'java.time.temporal.TemporalAccessor' but was '" + typeName(input) + "'."
);
}
try {
return OffsetTime.from(temporalAccessor);
} catch (DateTimeException e) {
throw new CoercingParseValueException(
"Unable to turn TemporalAccessor into full time because of : '" + e.getMessage() + "'."
);
}
}
@Override
public OffsetTime parseLiteral(Object input) throws CoercingParseLiteralException {
if (!(input instanceof StringValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + typeName(input) + "'."
);
}
return parseOffsetTime(((StringValue) input).getValue(), CoercingParseLiteralException::new);
}
private OffsetTime parseOffsetTime(String s, Function<String, RuntimeException> exceptionMaker) {
try {
TemporalAccessor temporalAccessor = dateFormatter.parse(s);
return OffsetTime.from(temporalAccessor);
} catch (DateTimeParseException e) {
throw exceptionMaker.apply("Invalid RFC3339 full time value : '" + s + "'. because of : '" + e.getMessage() + "'");
}
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.locale;
import graphql.Internal;
import graphql.language.StringValue;
import graphql.schema.*;
import java.util.Locale;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Locale}
*/
@Internal
public class LocaleScalar extends GraphQLScalarType {
public LocaleScalar() {
super("Locale", "A IETF BCP 47 language tag", new Coercing<Locale, String>() {
@Override
public String serialize(Object input) throws CoercingSerializeException {
if (input instanceof String) {
try {
return Locale.forLanguageTag((String) input).toLanguageTag();
} catch (Exception e) {
throw new CoercingSerializeException(
"Expected a valid language tag string but was but was " + typeName(input));
}
}
if (input instanceof Locale) {
return ((Locale) input).toLanguageTag();
} else {
throw new CoercingSerializeException(
"Expected a 'java.util.Locale' object but was " + typeName(input));
}
}
@Override
public Locale parseValue(Object input) throws CoercingParseValueException {
if (input instanceof String) {
try {
return Locale.forLanguageTag(input.toString());
} catch (Exception e) {
throw new CoercingParseValueException(
"Unable to parse value to 'java.util.Locale' because of: " + e.getMessage());
}
} else {
throw new CoercingParseValueException(
"Expected a 'java.lang.String' object but was " + typeName(input));
}
}
@Override
public Locale parseLiteral(Object input) throws CoercingParseLiteralException {
if (input instanceof StringValue) {
return Locale.forLanguageTag(((StringValue) input).getValue());
} else {
throw new CoercingParseLiteralException(
"Expected a 'java.lang.String' object but was " + typeName(input));
}
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import java.util.function.Function;
import static graphql.Scalars.GraphQLFloat;
@Internal
abstract class FloatCoercing implements Coercing<Double, Double> {
abstract protected Double check(Double d, Function<String, RuntimeException> exceptionMaker);
@Override
public Double serialize(Object input) throws CoercingSerializeException {
Double d = (Double) GraphQLFloat.getCoercing().serialize(input);
return check(d, CoercingSerializeException::new);
}
@Override
public Double parseValue(Object input) throws CoercingParseValueException {
Double d = (Double) GraphQLFloat.getCoercing().parseValue(input);
return check(d, CoercingParseValueException::new);
}
@Override
public Double parseLiteral(Object input) throws CoercingParseLiteralException {
Double d = (Double) GraphQLFloat.getCoercing().parseLiteral(input);
return check(d, CoercingParseLiteralException::new);
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import java.util.function.Function;
import static graphql.Scalars.GraphQLInt;
@Internal
abstract class IntCoercing implements Coercing<Integer, Integer> {
abstract protected Integer check(Integer i, Function<String, RuntimeException> exceptionMaker);
@Override
public Integer serialize(Object input) throws CoercingSerializeException {
Integer i = (Integer) GraphQLInt.getCoercing().serialize(input);
return check(i, CoercingSerializeException::new);
}
@Override
public Integer parseValue(Object input) throws CoercingParseValueException {
Integer i = (Integer) GraphQLInt.getCoercing().parseValue(input);
return check(i, CoercingParseValueException::new);
}
@Override
public Integer parseLiteral(Object input) throws CoercingParseLiteralException {
Integer i = (Integer) GraphQLInt.getCoercing().parseLiteral(input);
return check(i, CoercingParseLiteralException::new);
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NegativeFloat}
*/
@Internal
public class NegativeFloatScalar extends GraphQLScalarType {
public NegativeFloatScalar() {
super("NegativeFloat", "An Float scalar that must be a negative value", new FloatCoercing() {
@Override
protected Double check(Double d, Function<String, RuntimeException> exceptionMaker) {
if (!(d < 0)) {
throw exceptionMaker.apply("The value must be a negative value");
}
return d;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NegativeInt}
*/
@Internal
public class NegativeIntScalar extends GraphQLScalarType {
public NegativeIntScalar() {
super("NegativeInt", "An Int scalar that must be a negative value", new IntCoercing() {
@Override
protected Integer check(Integer i, Function<String, RuntimeException> exceptionMaker) {
if (!(i < 0)) {
throw exceptionMaker.apply("The value must be a negative integer");
}
return i;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NonNegativeFloat}
*/
@Internal
public class NonNegativeFloatScalar extends GraphQLScalarType {
public NonNegativeFloatScalar() {
super("NonNegativeFloat", "An Float scalar that must be greater than or equal to zero", new FloatCoercing() {
@Override
protected Double check(Double d, Function<String, RuntimeException> exceptionMaker) {
if (!(d >= 0)) {
throw exceptionMaker.apply("The value must be greater than or equal to zero");
}
return d;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NonNegativeInt}
*/
@Internal
public class NonNegativeIntScalar extends GraphQLScalarType {
public NonNegativeIntScalar() {
super("NonNegativeInt", "An Int scalar that must be greater than or equal to zero", new IntCoercing() {
@Override
protected Integer check(Integer i, Function<String, RuntimeException> exceptionMaker) {
if (!(i >= 0)) {
throw exceptionMaker.apply("The value must be greater than or equal to zero");
}
return i;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NonPositiveInt}
*/
@Internal
public class NonPositiveFloatScalar extends GraphQLScalarType {
public NonPositiveFloatScalar() {
super("NonPositiveFloat", "An Float scalar that must be less than or equal to zero", new FloatCoercing() {
@Override
protected Double check(Double d, Function<String, RuntimeException> exceptionMaker) {
if (!(d <= 0)) {
throw exceptionMaker.apply("The value must be less than or equal to zero");
}
return d;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#NonPositiveInt}
*/
@Internal
public class NonPositiveIntScalar extends GraphQLScalarType {
public NonPositiveIntScalar() {
super("NonPositiveInt", "An Int scalar that must be less than or equal to zero", new com.orhon.smartcampus.material.gql.scalars.numeric.IntCoercing() {
@Override
protected Integer check(Integer i, Function<String, RuntimeException> exceptionMaker) {
if (!(i <= 0)) {
throw exceptionMaker.apply("The value must be less than or equal to zero");
}
return i;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#PositiveFloat}
*/
@Internal
public class PositiveFloatScalar extends GraphQLScalarType {
public PositiveFloatScalar() {
super("PositiveFloat", "An Float scalar that must be a positive value", new FloatCoercing() {
@Override
protected Double check(Double d, Function<String, RuntimeException> exceptionMaker) {
if (!(d > 0)) {
throw exceptionMaker.apply("The value must be a positive value");
}
return d;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.numeric;
import graphql.Internal;
import graphql.schema.GraphQLScalarType;
import java.util.function.Function;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#PositiveInt}
*/
@Internal
public class PositiveIntScalar extends GraphQLScalarType {
public PositiveIntScalar() {
super("PositiveInt", "An Int scalar that must be a positive value", new IntCoercing() {
@Override
protected Integer check(Integer i, Function<String, RuntimeException> exceptionMaker) {
if (!(i > 0)) {
throw exceptionMaker.apply("The value must be a positive integer");
}
return i;
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.object;
import graphql.Internal;
/**
* A synonym class for {@link static com.orhon.smartcampus.modules.gql.scalars.object.ObjectScalar}
*
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Json}
*/
@Internal
public class JsonScalar extends ObjectScalar {
public JsonScalar() {
super("JSON", "A JSON scalar");
}
}
package com.orhon.smartcampus.material.gql.scalars.object;
import graphql.Assert;
import graphql.Internal;
import graphql.language.*;
import graphql.schema.*;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* Access this via {@link static com.orhon.smartcampus.modules.gql.scalars.ExtendedScalars#Object}
*/
@Internal
public class ObjectScalar extends GraphQLScalarType {
public ObjectScalar() {
this("Object", "An object scalar");
}
ObjectScalar(String name, String description) {
super(name, description, new Coercing<Object, Object>() {
@Override
public Object serialize(Object input) throws CoercingSerializeException {
return input;
}
@Override
public Object parseValue(Object input) throws CoercingParseValueException {
return input;
}
@Override
public Object parseLiteral(Object input) throws CoercingParseLiteralException {
return parseLiteral(input, Collections.emptyMap());
}
@Override
public Object parseLiteral(Object input, Map<String, Object> variables) throws CoercingParseLiteralException {
if (!(input instanceof Value)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + typeName(input) + "'."
);
}
if (input instanceof NullValue) {
return null;
}
if (input instanceof FloatValue) {
return ((FloatValue) input).getValue();
}
if (input instanceof StringValue) {
return ((StringValue) input).getValue();
}
if (input instanceof IntValue) {
return ((IntValue) input).getValue();
}
if (input instanceof BooleanValue) {
return ((BooleanValue) input).isValue();
}
if (input instanceof EnumValue) {
return ((EnumValue) input).getName();
}
if (input instanceof VariableReference) {
String varName = ((VariableReference) input).getName();
return variables.get(varName);
}
if (input instanceof ArrayValue) {
List<Value> values = ((ArrayValue) input).getValues();
return values.stream()
.map(v -> parseLiteral(v, variables))
.collect(Collectors.toList());
}
if (input instanceof ObjectValue) {
List<ObjectField> values = ((ObjectValue) input).getObjectFields();
Map<String, Object> parsedValues = new LinkedHashMap<>();
values.forEach(fld -> {
Object parsedValue = parseLiteral(fld.getValue(), variables);
parsedValues.put(fld.getName(), parsedValue);
});
return parsedValues;
}
return Assert.assertShouldNeverHappen("We have covered all Value types");
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.regex;
import graphql.Assert;
import graphql.PublicApi;
import graphql.language.StringValue;
import graphql.schema.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.orhon.smartcampus.material.gql.scalars.util.Kit.typeName;
/**
* This is really a scalar factory for creating new scalar String types that are based on a value matching
* a regular expression.
*/
@PublicApi
public class RegexScalar extends GraphQLScalarType {
/**
* A builder for {@link com.orhon.smartcampus.modules.gql.scalars.regex.RegexScalar}
*/
public static class Builder {
private String name;
private String description;
private List<Pattern> patterns = new ArrayList<>();
/**
* Sets the name of the regex scalar
*
* @param name the name of the regex scalar
*
* @return this builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Sets the description of the regex scalar
*
* @param description the description of the regex scalar
*
* @return this builder
*/
public Builder description(String description) {
this.description = description;
return this;
}
/**
* Adds a {@link Pattern} that controls the acceptable value for this scalar
*
* @param pattern the regex pattern
*
* @return this builder
*/
public Builder addPattern(Pattern pattern) {
this.patterns.add(pattern);
return this;
}
/**
* Adds a {@link Pattern} that controls the acceptable value for this scalar
*
* @param patterns one of more regex patterns
*
* @return this builder
*/
public Builder addPatterns(Pattern... patterns) {
Collections.addAll(this.patterns, patterns);
return this;
}
/**
* @return the built {@link com.orhon.smartcampus.modules.gql.scalars.regex.RegexScalar}
*/
public RegexScalar build() {
Assert.assertNotNull(name);
return regexScalarImpl(name, description, patterns);
}
}
private RegexScalar(String name, String description, Coercing coercing) {
super(name, description, coercing);
}
private static RegexScalar regexScalarImpl(String name, String description, List<Pattern> patterns) {
Assert.assertNotNull(patterns);
return new RegexScalar(name, description, new Coercing<String, String>() {
@Override
public String serialize(Object input) throws CoercingSerializeException {
String value = String.valueOf(input);
return matches(value, CoercingSerializeException::new);
}
@Override
public String parseValue(Object input) throws CoercingParseValueException {
String value = String.valueOf(input);
return matches(value, CoercingParseValueException::new);
}
@Override
public String parseLiteral(Object input) throws CoercingParseLiteralException {
if (!(input instanceof StringValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + typeName(input) + "'."
);
}
String value = ((StringValue) input).getValue();
return matches(value, CoercingParseLiteralException::new);
}
private String matches(String value, Function<String, RuntimeException> exceptionMaker) {
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(value);
if (matcher.matches()) {
return value;
}
}
throw exceptionMaker.apply("Unable to accept a value into the '" + name + "' scalar. It does not match the regular expressions.");
}
});
}
}
package com.orhon.smartcampus.material.gql.scalars.url;//package com.orhon.smartcampus.modules.gql.scalars.url;
//
//import graphql.Internal;
//import graphql.language.StringValue;
//import graphql.schema.Coercing;
//import graphql.schema.CoercingParseLiteralException;
//import graphql.schema.CoercingParseValueException;
//import graphql.schema.CoercingSerializeException;
//import graphql.schema.GraphQLScalarType;
//import okhttp3.HttpUrl;
//
//import java.io.File;
//import java.net.MalformedURLException;
//import java.net.URI;
//import java.net.URL;
//import java.util.Optional;
//import java.util.function.Function;
//
//import static com.orhon.smartcampus.modules.gql.scalars.util.Kit.typeName;
//
//@Internal
//public class UrlScalar extends GraphQLScalarType {
//
// public UrlScalar() {
// super("Url", "A Url scalar", new Coercing<URL, URL>() {
// @Override
// public URL serialize(Object input) throws CoercingSerializeException {
// Optional<URL> url;
// if (input instanceof String) {
// url = Optional.of(parseURL(input.toString(), CoercingSerializeException::new));
// } else {
// url = toURL(input);
// }
// if (url.isPresent()) {
// return url.get();
// }
// throw new CoercingSerializeException(
// "Expected a 'URL' like object but was '" + typeName(input) + "'."
// );
// }
//
// @Override
// public URL parseValue(Object input) throws CoercingParseValueException {
// String urlStr;
// if (input instanceof String) {
// urlStr = String.valueOf(input);
// } else {
// Optional<URL> url = toURL(input);
// if (!url.isPresent()) {
// throw new CoercingParseValueException(
// "Expected a 'URL' like object but was '" + typeName(input) + "'."
// );
// }
// return url.get();
// }
// return parseURL(urlStr, CoercingParseValueException::new);
// }
//
// @Override
// public URL parseLiteral(Object input) throws CoercingParseLiteralException {
// if (!(input instanceof StringValue)) {
// throw new CoercingParseLiteralException(
// "Expected AST type 'StringValue' but was '" + typeName(input) + "'."
// );
// }
// return parseURL(((StringValue) input).getValue(), CoercingParseLiteralException::new);
// }
//
// private URL parseURL(String input, Function<String, RuntimeException> exceptionMaker) {
// HttpUrl httpUrl = HttpUrl.parse(input);
// if (httpUrl == null) {
// throw exceptionMaker.apply("Invalid URL value : '" + input + "'.");
// }
// return httpUrl.url();
// }
// });
// }
//
// private static Optional<URL> toURL(Object input) {
// if (input instanceof URL) {
// return Optional.of((URL) input);
// } else if (input instanceof URI) {
// try {
// return Optional.of(((URI) input).toURL());
// } catch (MalformedURLException ignored) {
// }
// } else if (input instanceof File) {
// try {
// return Optional.of(((File) input).toURI().toURL());
// } catch (MalformedURLException ignored) {
// }
// }
// return Optional.empty();
// }
//
//}
package com.orhon.smartcampus.material.gql.scalars.util;
public class Kit {
public static String typeName(Object input) {
if (input == null) {
return "null";
}
return input.getClass().getSimpleName();
}
}
package com.orhon.smartcampus.material.modules.base.gqlModel;
import lombok.Data;
@Data
public class GQLPageParam {
private Integer page;
private Integer limit;
public Integer getPage() {
if(page==null) {
return 0;
}
return page;
}
public Integer getLimit() {
if(limit==null) {
return 0;
}
return limit;
}
}
package com.orhon.smartcampus.material.modules.base.mm;
import com.orhon.smartcampus.material.modules.base.gqlModel.GQLPageParam;
import graphql.schema.DataFetchingEnvironment;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface EnvArgsMapper {
EnvArgsMapper MAPPER = Mappers.getMapper(EnvArgsMapper.class);
/**
*
* 手写转化器
* @param env
* @return
*/
default GQLPageParam fromArgs(DataFetchingEnvironment env){
GQLPageParam p = new GQLPageParam();
if (env.containsArgument("page")){
p.setPage(env.getArgument("page"));
}
else{
p.setPage(1);
}
if (env.containsArgument("limit")){
p.setLimit(env.getArgument("limit"));
}
else{
p.setLimit(10);
}
return p;
}
}
package com.orhon.smartcampus.material.modules.management.dao;
import com.orhon.smartcampus.material.basicComponents.baseDao.BaseDaoImpl;
import com.orhon.smartcampus.material.modules.management.entity.GoodsClassify;
import org.springframework.stereotype.Component;
@Component
public class GoodsClassifyDao extends BaseDaoImpl<GoodsClassify> {
}
package com.orhon.smartcampus.material.modules.management.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
@Setter
@Getter
@EqualsAndHashCode
@Entity
@Table(name = "material_classify", schema = "material", catalog = "")
public class GoodsClassify {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "classify_name", nullable = false)
private String classify_name;
@Column(name = "classify_status", nullable = false)
private Integer classify_status;
@Column(name = "classify_campus_id", nullable = false)
private String classify_campus_id;
@Column(name = "classify_userid", nullable = false)
private String classify_userid;
@Column(name = "created_at", nullable = false)
private Date created_at;
@Column(name = "updated_at", nullable = false)
private Date updated_at;
// @ManyToOne
// @JoinColumn(name = "unit_id", referencedColumnName = "id")
// @Where(clause = "ISNULL(deleted_at)")
// @NotFound(action= NotFoundAction.IGNORE)
// private Unit materialUnitByUnitId;
//
// @ManyToOne
// @JoinColumn(name = "school_id", referencedColumnName = "id")
// @Where(clause = "ISNULL(deleted_at)")
// @NotFound(action=NotFoundAction.IGNORE)
// private Schools baseSchoolsBySchoolId;
}
package com.orhon.smartcampus.material.modules.management.fetcher;
import com.orhon.smartcampus.material.basicComponents.Result;
import com.orhon.smartcampus.material.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.material.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.material.modules.management.dao.GoodsClassifyDao;
import com.orhon.smartcampus.material.modules.management.entity.GoodsClassify;
import com.orhon.smartcampus.material.modules.management.gqlModel.GQLGoodsClassify;
import com.orhon.smartcampus.material.modules.management.mm.GoodsClassifyMapper;
import com.orhon.smartcampus.material.utils.ObjectToMap;
import com.orhon.smartcampus.material.utils.Util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Component
public class GoodsClassifyFetcher implements DataFetcher {
@Autowired
GoodsClassifyDao goodsClassifyDao;
@Override
public Object get(DataFetchingEnvironment env) throws Exception {
// + schoolId
String hql = "from GoodsClassify";
GoodsClassify item = goodsClassifyDao.findId(hql, null);
if(item!=null) {
GQLGoodsClassify goodsClassify = GoodsClassifyMapper.MAPPER.toGoodsClassify(item);
return goodsClassify;
}
return null;
}
}
package com.orhon.smartcampus.material.modules.management.fetcher;
import com.orhon.smartcampus.material.basicComponents.Result;
import com.orhon.smartcampus.material.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.material.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.material.modules.management.dao.GoodsClassifyDao;
import com.orhon.smartcampus.material.modules.management.entity.GoodsClassify;
import com.orhon.smartcampus.material.modules.management.gqlModel.GQLGoodsClassify;
import com.orhon.smartcampus.material.modules.management.mm.GoodsClassifyMapper;
import com.orhon.smartcampus.material.utils.ObjectToMap;
import com.orhon.smartcampus.material.utils.Util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Component
public class GoodsClassifyListFetcher implements DataFetcher {
@Autowired
GoodsClassifyDao goodsClassifyDao;
@Override
public Object get(DataFetchingEnvironment env) throws Exception {
// + schoolId
String hql = "from GoodsClassify";
GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
if(env.containsArgument("condition")) {
HashMap<String,Object> map = ObjectToMap.to(env.getArgument("condition"));
if(map.get("id")!=null) {
hql += "and id " + Util.decide(map.get("id"));
}
if(map.get("classify_name")!=null) {
hql += "and classify_name " + Util.decide(map.get("classify_name"));
}
if(map.get("classify_status")!=null) {
hql += "and classify_status " + Util.decide(map.get("classify_status"));
}
}
List<GoodsClassify> list = goodsClassifyDao.find(hql,null,page.getPage(),page.getLimit());
// GQLGoodsClassify gqlGoodsClassify = null;
// if (env.getSelectionSet().contains("data/classify")){
// GoodsClassify goodsClassify = item.getBaseSchoolsBySchoolId();
// GgqlSchool = SchoolMapper.MAPPER.toSchool(schools);
// }
//
// GQLUnit gqlUnit=null;
// if (env.getSelectionSet().contains("data/unit")){
// Unit unit = item.getMaterialUnitByUnitId();
// gqlUnit = UnitMapper.MAPPER.toUnit(unit);
// }
//
// GQL floor = FloorMapper.MAPPER.toFloor(item);
// floor.setSchool(GgqlSchool);
// floor.setUnit(gqlUnit);
// GQLFloor.add(floor);
// List<GQLGoodsClassify> GQLFloor = new ArrayList<>();
//
// for (GQLGoodsClassify item : list) {
// // GQLGoodsClassify gqlGoodsClassify = GoodsClassifyMapper.MAPPER.toGoodsClassifyList(item);
// // GQLFloor.add(gqlGoodsClassify);
// }
List<GQLGoodsClassify> gqlGoodsClassifies = GoodsClassifyMapper.MAPPER.toGoodsClassifyList(list);
Long total = 0L;
if (env.getSelectionSet().contains("total")){
total = goodsClassifyDao.getTotalCount(hql);
}
return Result.ok().put("data", gqlGoodsClassifies).put("total", total);
}
}
package com.orhon.smartcampus.material.modules.management.fetcher;
import com.orhon.smartcampus.material.modules.management.mutation.AddGoodsClassifyMutation;
import graphql.schema.idl.RuntimeWiring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MaterialFetchersLoader {
@Autowired
AddGoodsClassifyMutation addGoodsClassifyMutation;
@Autowired
GoodsClassifyListFetcher goodsClassifyListFetcher;
@Autowired
GoodsClassifyFetcher goodsClassifyFetcher;
//
// @Autowired
// AddRoomMutation addRoomMutation;
//
// @Autowired
// DeleteRoomMutation deleteRoomMutation;
//
// @Autowired
// AddFloorMutation addFloorMutation;
//
// @Autowired
// DeleteFloorMutation deleteFloorMutation;
//
// @Autowired
// AddUnitMutation addUnitMutation;
//
// @Autowired
// DeleteUnitMutation deleteUnitMutation;
//
//
// @Autowired
// AddBuildingMutation addBuildingMutation;
//
// @Autowired
// DeleteBuildingMutation deleteBuildingMutation;
//
// @Autowired
// AddSiteMutation addSiteMutation;
//
// @Autowired
// DeleteSiteMutation deleteSiteMutation;
//
// @Autowired
// AddCampusMutation addCampusMutation;
//
// @Autowired
// DeleteCampusMutation deleteCampusMutation;
//
//
// @Autowired
// BuildingFetcher buildingFetcher;
// @Autowired
// BuildingListFetcher buildingListFetcher;
//
// @Autowired
// CampusFetcher campusFetcher;
// @Autowired
// CampusListFetcher campusListFetcher;
//
// @Autowired
// FloorFetcher floorFetcher;
// @Autowired
// FloorListFetcher floorListFetcher;
//
// @Autowired
// RoomFetcher roomFetcher;
// @Autowired
// RoomListFetcher roomListFetcher;
//
// @Autowired
// SiteFetcher siteFetcher;
// @Autowired
// SiteListFetcher siteListFetcher;
//
// @Autowired
// UnitFetcher unitFetcher;
// @Autowired
// UnitListFetcher unitListFetcher;
public void LoadFetchers(RuntimeWiring.Builder builder){
builder.type("Query" , t->t.dataFetcher("GoodsClassify" , goodsClassifyFetcher));
builder.type("Query" , t->t.dataFetcher("GoodsClassifys" , goodsClassifyListFetcher));
// builder.type("Query" , t->t.dataFetcher("Buildings" , buildingListFetcher));
// builder.type("Query" , t->t.dataFetcher("Building" , buildingFetcher));
// builder.type("Query" , t->t.dataFetcher("Campuses" , campusListFetcher));
// builder.type("Query" , t->t.dataFetcher("Campus" , campusFetcher));
// builder.type("Query" , t->t.dataFetcher("Floors" , floorListFetcher));
// builder.type("Query" , t->t.dataFetcher("Rooms" , roomListFetcher));
// builder.type("Query" , t->t.dataFetcher("Room" , roomFetcher));
// builder.type("Query" , t->t.dataFetcher("Sites" , siteListFetcher));
// builder.type("Query" , t->t.dataFetcher("Site" , siteFetcher));
// builder.type("Query" , t->t.dataFetcher("Units" , unitListFetcher));
// builder.type("Query" , t->t.dataFetcher("Unit" , unitFetcher));
// builder.type("Mutation" , t->t.dataFetcher("addRoom" , addRoomMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteRoom" , deleteRoomMutation));
builder.type("Mutation" , t->t.dataFetcher("addGoodsClassify" , addGoodsClassifyMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteFloor" , deleteFloorMutation));
// builder.type("Mutation" , t->t.dataFetcher("addUnit" , addUnitMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteUnit" , deleteUnitMutation));
// builder.type("Mutation" , t->t.dataFetcher("addBuilding" , addBuildingMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteBuilding" , deleteBuildingMutation));
// builder.type("Mutation" , t->t.dataFetcher("addSite" , addSiteMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteSite" , deleteSiteMutation));
// builder.type("Mutation" , t->t.dataFetcher("addCampus" , addCampusMutation));
// builder.type("Mutation" , t->t.dataFetcher("deleteCampus" , deleteCampusMutation));
}
}
package com.orhon.smartcampus.material.modules.management.gqlInputModel;
import lombok.Data;
@Data
public class GQLGoodsClassifyInput {
private Long id;
private String classify_name;
private Integer classify_status;
private String classify_campus_id;
private String classify_userid;
}
package com.orhon.smartcampus.material.modules.management.gqlModel;
import lombok.Data;
import java.util.Date;
@Data
public class GQLGoodsClassify {
private Long id;
private String classify_name;
private Integer classify_status;
private String classify_campus_id;
private String classify_userid;
private Date created_at;
private Date updated_at;
}
package com.orhon.smartcampus.material.modules.management.inputMapper;
import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.material.basicComponents.ConvertHelper;
import com.orhon.smartcampus.material.modules.management.gqlInputModel.GQLGoodsClassifyInput;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.Map;
@Mapper(uses = {
ConvertHelper.class
})
public interface GoodsClassifyInputMapper {
GoodsClassifyInputMapper MAPPER = Mappers.getMapper(GoodsClassifyInputMapper.class);
default GQLGoodsClassifyInput mapInput(final Map map){
String json = JSON.toJSONString(map);
GQLGoodsClassifyInput input = JSON.parseObject(json , GQLGoodsClassifyInput.class);
return input;
}
}
package com.orhon.smartcampus.material.modules.management.mm;
import com.orhon.smartcampus.material.basicComponents.ConvertHelper;
import com.orhon.smartcampus.material.modules.management.entity.GoodsClassify;
import com.orhon.smartcampus.material.modules.management.gqlModel.GQLGoodsClassify;
import org.mapstruct.InheritConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper(
uses = {
ConvertHelper.class
}
)
public interface GoodsClassifyMapper {
GoodsClassifyMapper MAPPER = Mappers.getMapper(GoodsClassifyMapper.class);
@Mapping(source = "id" , target = "id")
@Mapping(source = "classify_name" , target = "classify_name")
@Mapping(source = "classify_status" , target = "classify_status")
@Mapping(source = "classify_campus_id" , target = "classify_campus_id")
@Mapping(source = "classify_userid" , target = "classify_userid")
@Mapping(source = "created_at" , target = "created_at")
@Mapping(source = "updated_at" , target = "updated_at")
GQLGoodsClassify toGoodsClassify(GoodsClassify entity);
@InheritConfiguration(name = "toGoodsClassify")
List<GQLGoodsClassify> toGoodsClassifyList(List<GoodsClassify> entities);
}
package com.orhon.smartcampus.material.modules.management.mutation;
import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.material.basicComponents.Result;
import com.orhon.smartcampus.material.modules.management.dao.GoodsClassifyDao;
import com.orhon.smartcampus.material.modules.management.entity.GoodsClassify;
import com.orhon.smartcampus.material.modules.management.gqlInputModel.GQLGoodsClassifyInput;
import com.orhon.smartcampus.material.modules.management.inputMapper.GoodsClassifyInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class AddGoodsClassifyMutation implements DataFetcher {
@Autowired
GoodsClassifyDao goodsClassifyDao;
/**
* 楼层管理
* editor : ths
*/
@Override
public Object get(DataFetchingEnvironment environment) throws Exception {
//String token = (String) SecurityUtils.getSubject().getPrincipal();
GQLGoodsClassifyInput input = GoodsClassifyInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));
GoodsClassify goodsClassify = null;
if (input.getId() != null) {
goodsClassify = goodsClassifyDao.get(GoodsClassify.class, input.getId());
goodsClassify.setUpdated_at(new Date());
} else {
goodsClassify = new GoodsClassify();
goodsClassify.setCreated_at(new Date());
}
if(input.getClassify_name() != null){
goodsClassify.setClassify_name(input.getClassify_name());
}
if(input.getClassify_campus_id() != null){
goodsClassify.setClassify_campus_id(input.getClassify_campus_id());
}
if(input.getClassify_status() != null){
goodsClassify.setClassify_status(input.getClassify_status());
}
if(input.getClassify_userid() != null){
goodsClassify.setClassify_userid(JSON.toJSONString(input.getClassify_userid()));
}
try {
goodsClassifyDao.saveOrUpdate(goodsClassify);
} catch (Exception e) {
return Result.error(500, "" + e);
}
return Result.ok();
}
}
package com.orhon.smartcampus.material.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
public class ObjectToMap {
public static HashMap<String, Object> to(Object obj){
HashMap hashMap = JSONObject.parseObject(JSON.toJSONString(obj),HashMap.class);
return hashMap;
}
}
package com.orhon.smartcampus.material.utils;
public class Util {
public static String decide(Object obj){
try {
int i = Integer.parseInt(obj.toString());
return " = "+ i;
} catch (Exception e) {
String[] split = obj.toString().split("_");
String string = split[0];
if(string.equals("like")) {
return " like '%"+split[1]+"%'";//模糊查询
}else {
return " = '" + obj.toString() +"'";
//return " = '"+split[0]+"'";
}
}
}
}
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
#url: jdbc:mysql://39.104.181.104:3311/smartcloud?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=true
url: jdbc:mysql://localhost:3306/material?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: weixuanhe2233
type: com.alibaba.druid.pool.DruidDataSource
#最大活跃数
maxActive: 20
#初始化数量
initialSize: 1
#最大连接等待超时时间
maxWait: 60000
#打开PSCache,并且指定每个连接PSCache的大小ull
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
#通过connectionProperties属性来打开mergeSql功能;慢SQL记录
#connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
filters: stat, wall, log4j
#日志
#logging:
# config: classpath:logback-boot.xml
# level:
# com.orhon.smartcampus.modules.*.mapper: DEBUG
debug: false
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 8011
connection-timeout: 5000
spring:
application:
name: material-base
# cloud:
# nacos:
# discovery:
# server-addr: 39.104.181.104:8848
profiles:
active: dev
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
enabled: true
# mvc:
# throw-exception-if-no-handler-found: true
# static-path-pattern: /static/**
resources:
add-mappings: false
static-locations: /static/
main:
allow-bean-definition-overriding: true
graphql:
servlet:
mapping: /graphql
enabled: true
corsEnabled: true
exception-handlers-enabled: true
contextSetting: PER_REQUEST_WITH_INSTRUMENTATION
maxQueryDepth: 13
graphiql:
mapping: /graphiql
endpoint:
graphql: /graphql
subscriptions: /subscriptions
static:
basePath: /
enabled: true
pageTitle: GraphiQL
cdn:
enabled: false
version: 0.11.11
props:
resources:
query: testquery.query
defaultQuery: testquery.query
variables:
editorTheme: "solarized light"
headers:
token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY2hvb2xfaWQiOjEsImV4cCI6MTU2OTM0OTQyOSwidXNlcmlkIjoxLCJ1c2VybmFtZSI6InRlYWNoZXIifQ.zewl-qR-i-pz5VnqUE2SXsoijV4JdUk5f6GbyRuawCk"
altair:
mapping: /altair
endpoint:
graphql: /graphql
subscriptions: /subscriptions
subscriptions:
timeout: 30
reconnect: false
static:
basePath: /
enabled: true
pageTitle: Altair
cdn:
enabled: false
version: 2.1.7
props:
resources:
#defaultQuery: defaultQuery.graphql
#variables: variables.graphql
headers:
Authorization: "Bearer <your-token>"
"日期标量"
scalar Date
scalar DateTime
scalar Time
scalar JSON
scalar Object
#"json数据"
#scalar JSON
"""
普通返回信息
"""
type NormalResponse{
code:Int
msg:String
}
#"""
#分页标准
#"""
#type Pagenation {
# total:Int
# current:Int
# limit:Int
#}
enum SubjectType{
"single普通学科"
single
"complex 综合学科"
complex
}
"楼层"
type GoodsClassify {
id:Long
"单元"
classify_name:String
"楼层电话"
classify_status:Int
"楼层负责人"
classify_campus_id:String
"楼层名"
classify_userid:String
}
input GoodsClassifyInput {
id:Int
classify_name:String
classify_status:Int
classify_campus_id:String
classify_userid:String
}
input GoodsClassifyCondition {
id:Int
classify_name:String
classify_status:Int
code:String
classify_campus_id:String
classify_userid:String
}
type GoodsClassifyResponse {
code:Int
msg:String
data:[GoodsClassify]
total:Int
}
\ No newline at end of file
type Query {
query:Query
hello(a:SubjectType):String
GoodsClassifys(page:Int,limit:Int,condition: GoodsClassifyCondition):GoodsClassifyResponse
GoodsClassify(id:Long!):GoodsClassify
}
input MessageInput{
hello:String
}
type Mutation {
addGoodsClassify(inputData:GoodsClassifyInput): GoodsClassifyResponse
}
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
<configuration>
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->
<!-- appender是configuration的子节点,是负责写日志的组件。 -->
<!-- ConsoleAppender:把日志输出到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
<!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->
<!-- 2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
<appender name="syslog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>logs/sys.log</File>
<!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
<!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
<!-- 文件名:log/sys.2017-12-05.0.log -->
<fileNamePattern>logs/sys.%d.%i.log</fileNamePattern>
<!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
<maxHistory>30</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
<maxFileSize>1KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<!-- pattern节点,用来设置日志的输入格式 -->
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<!-- 记录日志的编码 -->
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<!-- 控制台输出日志级别 -->
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
<!-- com.appley为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
<!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
<logger name="com.orhon" level="TRACE">
<appender-ref ref="syslog" />
</logger>
</configuration>
\ No newline at end of file
package com.orhon.smartcampus.material;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MaterialApplicationTests {
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment