Compare commits

..

No commits in common. 'main' and 'main' have entirely different histories.
main ... main

@ -1,16 +1,2 @@
# manage01
台春阳:
wcp-webhighstock.1.1前4000行
超过3500行
邓李辉:
farm-core
wcp-api
wcp-authority
wcp-doc
wcp-doc-so
超过3000行
孙云乐:
wcp-parameter
wcp-quartz
wcp-tag
超过3500行

@ -1,75 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="4d6ebe9b-a7d1-4051-b51b-6dbbab6486b0" name="更改" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../.." />
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="localRepository" value="D:\maven项目\项目" />
<option name="userSettingsFile" value="C:\Users\Administrator\.m2\settings.xml" />
</MavenGeneralSettings>
</option>
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 2
}</component>
<component name="ProjectId" id="2uJ77sfrfWgrpLWRI6ORnLsrjvl" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Maven.farm-core [clean,install].executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;master&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;project.structure.last.edited&quot;: &quot;模块&quot;,
&quot;project.structure.proportion&quot;: &quot;0.15&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.2&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;MavenSettings&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-9f38398b9061-39b83d9b5494-intellij.indexing.shared.core-IU-241.17011.79" />
<option value="bundled-js-predefined-1d06a55b98c1-0b3e54e931b4-JavaScript-IU-241.17011.79" />
</set>
</attachedChunks>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="应用程序级" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="默认任务">
<changelist id="4d6ebe9b-a7d1-4051-b51b-6dbbab6486b0" name="更改" comment="" />
<created>1741954660473</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1741954660473</updated>
<workItem from="1741954664978" duration="571000" />
<workItem from="1741956860321" duration="120000" />
<workItem from="1742282371383" duration="656000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>

@ -1,135 +0,0 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.farm</groupId>
<artifactId>farm-core</artifactId>
<packaging>jar</packaging>
<version>${wcp.version}</version>
<name>核心包</name>
<properties>
<wcp.version>3.2.0</wcp.version>
<spring.version>4.1.6.RELEASE</spring.version>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.sun.commons</groupId>
<artifactId>beanutils</artifactId>
<version>1.6.1-20070314</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,92 +0,0 @@
package com.farm.core;
import java.util.List;
import java.util.Set;
import com.farm.core.auth.domain.AuthKey;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.auth.exception.LoginUserNoExistException;
/**
*
*
* @author wangdong
* @version 2014-12
*
*/
public interface AuthorityService {
/**
*
*
* @param loginName
*
* @param password
*
* @return
*/
public boolean isLegality(String loginName, String password)
throws LoginUserNoExistException;
/**
*
*
* @param loginName
* @return
*/
public LoginUser getUserByLoginName(String loginName);
/**KEY
* @param userId
* @return
*/
public List<String> getUserPostKeys(String userId);
/**KEY
* @param userId
* @return
*/
public String getUserOrgKey(String userId);
/**
*
*
* @param userId
* @return
*/
public LoginUser getUserById(String userId);
/**
*
*
* @param userId
* @return
*/
public Set<String> getUserAuthKeys(String userId);
/**
* key(key)
*
* @param key
* @return
*/
public AuthKey getAuthKey(String key);
/**
*
*
* @param userId
* @return
*/
public List<WebMenu> getUserMenu(String userId);
/**
*
*
* @param userId
*/
public void loginHandle(String userId);
}

@ -1,7 +0,0 @@
package com.farm.core;
public class Context {
public static String MK;
public static String FK;
public static boolean FLAG;
}

@ -1,96 +0,0 @@
package com.farm.core;
import com.farm.core.auth.util.AuthenticateInter;
import com.farm.core.auth.util.AuthenticateProvider;
import com.farm.core.config.PropertiesUtils;
import com.farm.core.time.TimeTool;
import com.farm.util.validate.ValidUtils;
import com.farm.util.web.FarmFormatUnits;
import com.farm.util.web.FarmproHotnum;
import com.farm.util.web.WebHotCase;
import com.farm.util.web.WebVisitBuff;
/**
*
*
* @author wangdong
*
*/
public class FarmUtils {
/**
* @return
*/
public static ValidUtils getValidUtils() {
return new ValidUtils();
}
/**
*
*
* @return
*/
public static AuthenticateInter getAuthUtils() {
return AuthenticateProvider.getInstance();
}
/**
* Properties
*
* @param fileName
* jdbc.properties
* @return
*/
public static PropertiesUtils getPropertiesUtils(String fileName) {
return new PropertiesUtils(fileName);
}
/**
*
*
* @return
*/
public static TimeTool getTimeTools() {
return new TimeTool();
}
/**
*
*
* @return
*/
public static FarmFormatUnits getFormatUtils() {
return new FarmFormatUnits();
}
/**
* 访
*
* @return
*/
public static FarmproHotnum getHotUtils() {
return new FarmproHotnum();
}
/**
*
*
* @return
*/
public static WebHotCase getHotWordUtils() {
return new WebHotCase();
}
/**
* 访KEY访
*
* @param domain
*
* @param maxNum
* key
* @return
*/
public static WebVisitBuff getWebVisitBuff(String domain, int maxNum) {
return WebVisitBuff.getInstance(domain, maxNum);
}
}

@ -1,31 +0,0 @@
package com.farm.core;
/**
*
*
* @author wangdong
* @version 2014-12
*
*/
public interface LogService {
/**
*
*
* @param message
*
* @param loginUserId
* id
* @param level
*
* @param methodName
*
* @param className
*
* @param ip
* IP
*/
public void log(String info, String loginUserId, String level,
String methodName, String className, String ip);
}

@ -1,55 +0,0 @@
package com.farm.core;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
*
*
* @author wangdong
* @version 2014-12
*
*/
public interface ParameterService {
/**
* (:properties)
*
* @return
*/
public String getParameter(String key);
/**
* (:properties)
*
* @return
*/
public String getParameter(String key, String userId);
/**
*
*
* @param index
* @return
*/
public List<Entry<String, String>> getDictionaryList(String index);
/**
*
*
* @param key
* @return
*/
public Map<String, String> getDictionary(String key);
public int getParameterInt(String string);
/**
* (:properties)
*
* @param string
* @return
*/
public boolean getParameterBoolean(String key);
}

@ -1,113 +0,0 @@
package com.farm.core;
import java.net.NetworkInterface;
import java.util.Enumeration;
import com.farm.core.auth.util.MD5;
/**
*
*
* @author
*/
public class SequenceService {
/**
* StringMD5
*
* @param message
* String
* @return MD5
*/
protected static String getMD5(String message) {
String md5 = new MD5().getMD5ofStr(message);
return getSplitString(md5);
}
public static String InitKey() {
return getMD5(getSigarSequence());
}
/**
* 便
*
* @param str
* @return
*/
protected static String getSplitString(String str) {
return getSplitString(str.substring(0, 16), "-", 4);
}
/**
* 便 71F5DA7F495E7F706D47F3E63DC6349A
* -4 71F5-DA7F-495E-7F70-6D47-F3E6-3DC6-349A
*
* @param str
*
* @param split
*
* @param length
*
* @return
*/
protected static String getSplitString(String str, String split, int length) {
int len = str.length();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < len; i++) {
if (i % length == 0 && i > 0) {
temp.append(split);
}
temp.append(str.charAt(i));
}
String[] attrs = temp.toString().split(split);
StringBuilder finalMachineCode = new StringBuilder();
for (String attr : attrs) {
if (attr.length() == length) {
finalMachineCode.append(attr).append(split);
}
}
String result = finalMachineCode.toString().substring(0, finalMachineCode.toString().length() - 1);
return result;
}
/**
* sigarCPU ID
*
* @param osName
*
* @return
*/
protected static String getSigarSequence() {
return "asdf";
}
/**
* "XX-XX-XX-XX-XX-XX"MAC
* @return
* @throws Exception
*/
public static String getMacAddress() throws Exception{
Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
while(ni.hasMoreElements()){
NetworkInterface netI = ni.nextElement();
byte[] bytes = netI.getHardwareAddress();
if(netI.isUp() && netI != null && bytes != null && bytes.length == 6){
StringBuffer sb = new StringBuffer();
for(byte b:bytes){
//与11110000作按位与运算以便读取当前字节高4位
sb.append(Integer.toHexString((b&240)>>4));
//与00001111作按位与运算以便读取当前字节低4位
sb.append(Integer.toHexString(b&15));
sb.append("-");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString().toUpperCase();
}
}
return null;
}
public static void main(String[] args) {
System.out.println(SequenceService.InitKey());
}
}

@ -1,31 +0,0 @@
package com.farm.core.auth.domain;
public interface AuthKey {
/**
* 使
*
* @return
*/
public boolean isLogin();
/**
*
*
* @return
*/
public boolean isCheck();
/**
*
*
* @return
*/
public boolean isUseAble();
/**
*
*
* @return
*/
public String getTitle();
}

@ -1,11 +0,0 @@
package com.farm.core.auth.domain;
public interface LoginUser {
public String getId();
public String getName();
public String getLoginname();
}

@ -1,15 +0,0 @@
package com.farm.core.auth.domain;
public interface WebMenu {
public String getParams();
public String getIcon();
public String getUrl();
public String getName();
public String getParentid();
public String getId();
}

@ -1,12 +0,0 @@
package com.farm.core.auth.exception;
public class LoginUserNoExistException extends Exception {
public LoginUserNoExistException(String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = 6482296763929242398L;
}

@ -1,145 +0,0 @@
package com.farm.core.auth.impl; // 定义包名,表示该类位于 com.farm.core.auth.impl 包中
import java.util.ArrayList; // 导入 ArrayList 类
import java.util.HashSet; // 导入 HashSet 类
import java.util.List; // 导入 List 接口
import java.util.Set; // 导入 Set 接口
import org.springframework.stereotype.Service; // 导入 Spring 的 @Service 注解
import com.farm.core.AuthorityService; // 导入 AuthorityService 接口
import com.farm.core.auth.domain.AuthKey; // 导入 AuthKey 类
import com.farm.core.auth.domain.LoginUser; // 导入 LoginUser 类
import com.farm.core.auth.domain.WebMenu; // 导入 WebMenu 类
import com.farm.core.auth.exception.LoginUserNoExistException; // 导入 LoginUserNoExistException 异常类
package com.example.versionmanagement;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
//启动类
package com.example.versionmanagement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class VersionManagementApplication {
public static void main(String[] args) {
SpringApplication.run(VersionManagementApplication.class, args);
}
}
@Service // 标注该类为 Spring 的服务组件
public class AuthTestImpl implements AuthorityService { // 定义 AuthTestImpl 类,实现 AuthorityService 接口
@Override // 重写 AuthorityService 接口中的 loginHandle 方法
public void loginHandle(String userId) {
System.out.println("登录成功"); // 打印登录成功信息
}
@Override // 重写 AuthorityService 接口中的 getUserAuthKeys 方法
public Set<String> getUserAuthKeys(String userId) {
Set<String> map = new HashSet<String>(); // 创建一个 HashSet 对象
map.add("AUTHKEY"); // 向集合中添加一个权限键
return map; // 返回包含权限键的集合
}
@Override // 重写 AuthorityService 接口中的 getUserById 方法
public LoginUser getUserById(String userId) {
// 创建一个匿名内部类实现 LoginUser 接口
LoginUser user = new LoginUser() {
@Override // 重写 getName 方法
public String getName() {
return "userName"; // 返回用户名
}
@Override // 重写 getLoginname 方法
public String getLoginname() {
return "loginName"; // 返回登录名
}
@Override // 重写 getId 方法
public String getId() {
return "userId"; // 返回用户ID
}
};
return user; // 返回创建的 LoginUser 对象
}
@Override // 重写 AuthorityService 接口中的 getUserByLoginName 方法
public LoginUser getUserByLoginName(String loginName) {
// 创建一个匿名内部类实现 LoginUser 接口
LoginUser user = new LoginUser() {
@Override // 重写 getName 方法
public String getName() {
return "userName"; // 返回用户名
}
@Override // 重写 getLoginname 方法
public String getLoginname() {
return "loginName"; // 返回登录名
}
@Override // 重写 getId 方法
public String getId() {
return "userId"; // 返回用户ID
}
};
return user; // 返回创建的 LoginUser 对象
}
@Override // 重写 AuthorityService 接口中的 getUserMenu 方法
public List<WebMenu> getUserMenu(String userId) {
List<WebMenu> list = new ArrayList<WebMenu>(); // 创建一个 ArrayList 对象
return list; // 返回用户菜单列表
}
@Override // 重写 AuthorityService 接口中的 isLegality 方法
public boolean isLegality(String loginName, String password)
throws LoginUserNoExistException {
return true; // 返回 true表示用户名和密码合法
}
@Override // 重写 AuthorityService 接口中的 getAuthKey 方法
public AuthKey getAuthKey(String key) {
// 创建一个匿名内部类实现 AuthKey 接口
return new AuthKey() {
@Override // 重写 isLogin 方法
public boolean isLogin() {
return false; // 返回 false表示未登录
}
@Override // 重写 isCheck 方法
public boolean isCheck() {
return false; // 返回 false表示未检查
}
@Override // 重写 isUseAble 方法
public boolean isUseAble() {
return true; // 返回 true表示可用
}
@Override // 重写 getTitle 方法
public String getTitle() {
return "权限名称(测试)"; // 返回权限标题
}
};
}
@Override // 重写 AuthorityService 接口中的 getUserPostKeys 方法
public List<String> getUserPostKeys(String userId) {
List<String> list = new ArrayList<String>(); // 创建一个 ArrayList 对象
list.add("POSTID"); // 向列表中添加一个岗位ID
return list; // 返回用户岗位键列表
}
@Override // 重写 AuthorityService 接口中的 getUserOrgKey 方法
public String getUserOrgKey(String userId) {
return "ORGID"; // 返回用户组织键
}
} // AuthTestImpl 类结束

@ -1,29 +0,0 @@
package com.example.versionmanagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* HTTP
*/
@RestController
public class VersionController {
/**
*
*/
@Autowired
private VersionInfo versionInfo;
/**
* GET
* 访"/version"
*
* @return VersionInfo
*/
@GetMapping("/version")
public VersionInfo getVersionInfo() {
return versionInfo;
}
}

@ -1,33 +0,0 @@
//创建一个类来存储版本信息
@Configuration
@ConfigurationProperties(prefix = "app.version")
public class VersionInfo {
private String name;
private String version;
private String description;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

@ -1,38 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

@ -1,8 +0,0 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="@localhost" uuid="08824a93-b251-4762-b303-aa8270a2043e">
<driver-ref>mysql_aurora_aws</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>software.aws.rds.jdbc.mysql.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql:aws://localhost:3306</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/resources/UserMapper.xml" dialect="MySQL" />
</component>
</project>

@ -1,124 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

@ -1,67 +0,0 @@
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maven_javaprogram</groupId>
<artifactId>mybatis_demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>mybatis_demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version> <!-- 使用适合你的版本 -->
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>mybatis_demo</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<!-- 根据需要添加其他文件类型 -->
</includes>
<!-- 如果需要排除某些文件,可以使用<excludes>标签 -->
<!-- <excludes> -->
<!-- <exclude>**/*.excluded</exclude> -->
<!-- </excludes> -->
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<!-- 其他构建配置 -->
</build>
</project>

@ -1,17 +0,0 @@
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
import java.util.Map;
public interface UseMapper {
List<User> getUserList();
int addUser(User user);
User selectId(int a);
int updateUser();
int deleteUser(int i);
int insertUserByMap(Map map);
List<User> likeSelectUser(String a);
}

@ -1,28 +0,0 @@
package com.kuang.mybatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class mybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
String resource = "mybatis-config.xml";
InputStream inputStream;
{
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}

@ -1,46 +0,0 @@
package com.kuang.pojo;
import org.apache.ibatis.type.Alias;
@Alias("user")
public class User {
private int id;
private String name;
private int numId;
public User(int id, String name, int numId) {
this.id = id;
this.name = name;
this.numId = numId;
}
public int getNumId() {
return numId;
}
public void setNumId(int numId) {
this.numId = numId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "com.kuang.pojo.User{" +
"id=" + id +
", name='" + name+", " +"numId"+numId+
'}';
}
}

@ -1,100 +0,0 @@
package com.kuang.test;
import com.kuang.dao.UseMapper;
import com.kuang.mybatisUtils.mybatisUtils;
import com.kuang.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
public class mybatisDemo {
@Test
public void test() {
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test1(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
int i = mapper.addUser(new User(5,"quqiCake",5));
if(i>0){
System.out.println("参数加入成功");
sqlSession.commit();
}else{
System.out.println("加入失败");
}
sqlSession.close();
}
@Test
public void test2(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
User user = mapper.selectId(1);
System.out.println(user);
}
@Test
public void test3(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
int a = mapper.updateUser();
if(a>0){
System.out.println("提交成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void test4(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
int a = mapper.deleteUser(5);
if(a>0){
System.out.println("删除成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void test5(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("id",5);
map.put("name","quqiCake");
map.put("numId",5);
int a = mapper.insertUserByMap(map);
if(a>0){
System.out.println("添加成功");
sqlSession.commit();
}
}
@Test
public void test6(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
//获得sql
UseMapper mapper = sqlSession.getMapper(UseMapper.class);
List<User> users = mapper.likeSelectUser("h%");
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test7(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
//获得sql 参数是一个映射的语句
String s="com.kuang.dao.UseMapper.selectId";
List<User> objects = sqlSession.selectList(s);
System.out.println(objects);
}
}

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UseMapper">
<resultMap id="UserMapper" type="User">
<!-- 把字段名和属性名不一样的改一下-->
<result column="name" property="CakeName"/>
</resultMap>
<select id="selectId" parameterType="int" resultMap="UserMapper">
select * from cakeinfo.cakeinfo where id=#{id};
</select>
<select id="getUserList" resultType="User">
select * from cakeinfo.cakeinfo;
</select>
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into cakeinfo.cakeinfo(id, name, numId) value (#{id},#{name},#{numId});
</insert>
<update id="updateUser" parameterType="com.kuang.pojo.User">
update cakeinfo.cakeinfo set name='xiaoqiqu' where id=5;
</update>
<delete id="deleteUser" parameterType="int">
delete from cakeinfo.cakeinfo where id=#{id};
</delete>
<insert id="insertUserByMap" parameterType="map" >
insert into cakeinfo.cakeinfo (id, name, numId)
values (#{id},#{name},#{numId});
</insert>
<select id="likeSelectUser" parameterType="String" resultType="User">
select * from cakeinfo.cakeinfo where name like #{name};
</select>
</mapper>

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
<!-- <typeAliases>-->
<!-- <package name="com.kuang.pojo"/>-->
<!-- </typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/cakeinfo?useUnicode=true&amp;characterEncoding=UTF-8&amp;userSSL=false&amp;serverTimezone=GMT%2B8"/>
<property name="username" value="denglihui"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>

@ -1,7 +0,0 @@
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>

@ -1,54 +0,0 @@
package com.farm.core.auth.util;
/**
*
*
* @author
*
*/
public interface AuthenticateInter {
/**
*
*
* @param password
*
* @return
*/
public String encodeMacpro(String password);
/**
*
*
* @param password
*
* @return
* @throws Exception
*
*/
public String decodeMacpro(String password) throws Exception;
/**
* md5
*
* @param password
*
* @return
*/
public String encodeMd5(String password);
/**
* MD5
*
* @param password
* @return
*/
public boolean isMd5code(String password);
/**
* MD5(password+loginname)
*
* @param password
* @return
*/
public String encodeLoginPasswordOnMd5(String password, String loginName);
}

@ -1,50 +0,0 @@
package com.farm.core.auth.util; // 定义包名,表示该类位于 com.farm.core.auth.util 包中
import org.apache.commons.codec.binary.Base64; // 导入 Apache Commons Codec 库的 Base64 类用于编码和解码
public class AuthenticateProvider implements AuthenticateInter { // 定义 AuthenticateProvider 类,实现 AuthenticateInter 接口
private AuthenticateProvider() { // 私有构造函数,防止外部直接创建实例
}
public static AuthenticateInter getInstance() { // 提供一个公有的静态方法获取实例,实现单例模式
return new AuthenticateProvider();
}
public String decodeMacpro(String password) throws Exception { // 解码 Macpro 密码
byte[] fpass = Base64.decodeBase64(password.getBytes()); // 使用 Base64 解码密码字符串
String str = new String(fpass); // 将解码后的字节数组转换为字符串
return str; // 返回解码后的字符串
}
public String encodeMacpro(String password) { // 编码 Macpro 密码
byte[] cpass = Base64.encodeBase64(password.getBytes()); // 使用 Base64 编码密码字符串
String temp = new String(cpass); // 将编码后的字节数组转换为字符串
return temp; // 返回编码后的字符串
}
@Override // 重写接口中的 encodeMd5 方法
public String encodeMd5(String password) { // 对密码进行 MD5 编码
if (this.isMd5code(password)) { // 如果密码已经是 MD5 编码,直接返回
return password;
} else { // 否则,使用 MD5 算法对密码进行编码
return new MD5().getMD5ofStr(password);
}
}
@Override // 重写接口中的 isMd5code 方法
public boolean isMd5code(String password) { // 检查字符串是否为 MD5 编码
if (password.trim().length() == 32) // MD5 编码的长度为 32 位
return true; // 如果长度为 32认为是 MD5 编码
else
return false; // 否则,不是 MD5 编码
}
@Override // 重写接口中的 encodeLoginPasswordOnMd5 方法
public String encodeLoginPasswordOnMd5(String password, String loginName) { // 根据密码和登录名生成 MD5 编码的登录密码
return encodeMd5(password + loginName); // 将密码和登录名拼接后进行 MD5 编码
}
} // AuthenticateProvider 类结束
// 注意:代码中的 MD5 类没有在当前代码片段中定义,应该是在其他地方定义的。此外,单例模式的实现方式较为简单,没有考虑线程安全问题。

@ -1,22 +0,0 @@
package com.farm.core.auth.util; // 定义包名,表示该类位于 com.farm.core.auth.util 包中
public class KeyUtil { // 定义 KeyUtil 类,用于处理与密钥相关的工具方法
@SuppressWarnings("unused") // 抑制未使用变量的警告
private static String errorkey = "ERROR"; // 定义一个静态变量,用于表示错误密钥,但目前未使用
@SuppressWarnings("unused") // 抑制未使用变量的警告
private static String CODE_C = "SADFSEV"; // 定义一个静态变量,可能用于编码或加密的常量,但目前未使用
public static String getFkey(String mkey) { // 定义一个公共静态方法,用于获取某种密钥
return "NONE"; // 目前该方法直接返回 "NONE",表示没有有效的密钥
}
public static String getMKey() { // 定义一个公共静态方法,用于获取主密钥
return "NONE"; // 目前该方法直接返回 "NONE",表示没有有效的主密钥
}
} // KeyUtil 类结束
// 注意:这个类中的方法目前只是返回了 "NONE",这可能是一个占位符或者表示某种默认行为。实际应用中,这些方法应该被实现为返回有效的密钥值。同时,类中定义了两个未使用的静态变量,可能是在未来版本中会使用到。

@ -1,358 +0,0 @@
package com.farm.core.auth.util;
/*************************************************
md5 RSA Data Security, Inc.IETF
RFC1321MD5 message-digest
*************************************************/
public class MD5 {
/* S11-S444*4C#define
static final
Instance*/
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/* MD53C
MD5_CTX
*/
private long[] state = new long[4]; // state (ABCD)
private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb first)
private byte[] buffer = new byte[64]; // input buffer
/* digestHexStrMD5
  16ASCII.
*/
public String digestHexStr;
/* digest,2128bitMD5.
*/
private byte[] digest = new byte[16];
/*
getMD5ofStrMD5MD5
digestHexStr
*/
public String getMD5ofStr(String inbuf) {
md5Init();
md5Update(inbuf.getBytes(), inbuf.length());
md5Final();
digestHexStr = "";
for (int i = 0; i < 16; i++) {
digestHexStr += byteHEX(digest[i]);
}
return digestHexStr;
}
// 这是MD5这个类的标准构造函数JavaBean要求有一个public的并且没有参数的构造函数
public MD5() {
md5Init();
return;
}
/* md5Init是一个初始化函数初始化核心变量装入标准的幻数 */
private void md5Init() {
count[0] = 0L;
count[1] = 0L;
///* Load magic initialization constants.
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
return;
}
/* F, G, H ,I 4MD5MD5C
java
  privateC */
private long F(long x, long y, long z) {
return (x & y) | ((~x) & z);
}
private long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private long H(long x, long y, long z) {
return x ^ y ^ z;
}
private long I(long x, long y, long z) {
return y ^ (x | (~z));
}
/*
FF,GG,HHIIF,G,H,I
FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
private long FF(long a, long b, long c, long d, long x, long s,
long ac) {
a += F (b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long GG(long a, long b, long c, long d, long x, long s,
long ac) {
a += G (b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long HH(long a, long b, long c, long d, long x, long s,
long ac) {
a += H (b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long II(long a, long b, long c, long d, long x, long s,
long ac) {
a += I (b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
/*
md5UpdateMD5inbufinputlen
getMD5ofStrmd5initprivate
*/
private void md5Update(byte[] inbuf, int inputLen) {
int i, index, partLen;
byte[] block = new byte[64];
index = (int)(count[0] >>> 3) & 0x3F;
// /* Update number of bits */
if ((count[0] += (inputLen << 3)) < (inputLen << 3))
count[1]++;
count[1] += (inputLen >>> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (inputLen >= partLen) {
md5Memcpy(buffer, inbuf, index, 0, partLen);
md5Transform(buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
md5Memcpy(block, inbuf, 0, i, 64);
md5Transform (block);
}
index = 0;
} else
i = 0;
///* Buffer remaining input */
md5Memcpy(buffer, inbuf, index, i, inputLen - i);
}
/*
md5Final
*/
private void md5Final () {
byte[] bits = new byte[8];
int index, padLen;
///* Save number of bits */
Encode (bits, count, 8);
///* Pad out to 56 mod 64.
index = (int)(count[0] >>> 3) & 0x3f;
padLen = (index < 56) ? (56 - index) : (120 - index);
md5Update (PADDING, padLen);
///* Append length (before padding) */
md5Update(bits, 8);
///* Store state in digest */
Encode (digest, state, 16);
}
/* md5Memcpy使byteinputinposlen
      outputoutpos
*/
private void md5Memcpy (byte[] output, byte[] input,
int outpos, int inpos, int len)
{
int i;
for (i = 0; i < len; i++)
output[outpos + i] = input[inpos + i];
}
/*
md5TransformMD5md5Updateblock
*/
private void md5Transform (byte block[]) {
long a = state[0], b = state[1], c = state[2], d = state[3];
long[] x = new long[16];
Decode (x, block, 64);
/* Round 1 */
a = FF (a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
d = FF (d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
c = FF (c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
b = FF (b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
a = FF (a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
d = FF (d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
c = FF (c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
b = FF (b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
a = FF (a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
d = FF (d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
c = FF (c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
b = FF (b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
a = FF (a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
d = FF (d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
c = FF (c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
b = FF (b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
/* Round 2 */
a = GG (a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
d = GG (d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
c = GG (c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
b = GG (b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG (a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
d = GG (d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
c = GG (c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
b = GG (b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG (a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
d = GG (d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
c = GG (c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
b = GG (b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
a = GG (a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
d = GG (d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
c = GG (c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
b = GG (b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
/* Round 3 */
a = HH (a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
d = HH (d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
c = HH (c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
b = HH (b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
a = HH (a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
d = HH (d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
c = HH (c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
b = HH (b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
a = HH (a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
d = HH (d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
c = HH (c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
b = HH (b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
a = HH (a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
d = HH (d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
c = HH (c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
b = HH (b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
/* Round 4 */
a = II (a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
d = II (d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
c = II (c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
b = II (b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
a = II (a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
d = II (d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
c = II (c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
b = II (b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
a = II (a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
d = II (d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
c = II (c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
b = II (b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
a = II (a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
d = II (d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
c = II (c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
b = II (b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
/*Encodelongbytejavalong64bit
32bitC
*/
private void Encode (byte[] output, long[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (byte)(input[i] & 0xffL);
output[j + 1] = (byte)((input[i] >>> 8) & 0xffL);
output[j + 2] = (byte)((input[i] >>> 16) & 0xffL);
output[j + 3] = (byte)((input[i] >>> 24) & 0xffL);
}
}
/*Decodebytelongjavalong64bit
32bit32bitC
*/
private void Decode (long[] output, byte[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = b2iu(input[j]) |
(b2iu(input[j + 1]) << 8) |
(b2iu(input[j + 2]) << 16) |
(b2iu(input[j + 3]) << 24);
return;
}
/*
b2iubytejavaunsigned
*/
public static long b2iu(byte b) {
return b < 0 ? b & 0x7F + 128 : b;
}
/*byteHEX()byteASCII
 javabytetoStringC
sprintf(outbuf,"%02X",ib)
*/
public static String byteHEX(byte ib) {
char[] Digit = { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F' };
char [] ob = new char[2];
ob[0] = Digit[(ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
}

@ -1,192 +0,0 @@
package com.farm.core.auth.util; // 定义包名,表示该类位于 com.farm.core.auth.util 包中
import java.util.Map; // 导入 Map 接口
import java.util.Map.Entry; // 导入 Map.Entry 接口,用于遍历 Map 中的键值对
import java.util.Set; // 导入 Set 接口
import javax.servlet.http.HttpServletRequest; // 导入 HttpServletRequest 接口,用于处理 HTTP 请求
/**
*
*
* @author WangDong
* @date Mar 14, 2010
*
*/
public class Urls {
/**
*
*
* @param actionMap
* @param useraction
* @param url URL
* @return
*/
@SuppressWarnings("unused") // 抑制未使用变量的警告
private boolean checkpopedom(Map<String, Object> actionMap, Map<String, Map<String, String>> useraction,
String url) {
// 查看是否是受控权限
if (actionMap == null) {
return false; // 如果全部监控权限为空则返回false
}
if (actionMap.get(url) != null) {
// 是受检权限,看用户是否拥有该权限
if (useraction == null) {
return false; // 如果用户拥有权限为空则返回false
}
if (useraction.get(url) != null) {
return true; // 如果用户拥有该URL的权限则返回true
} else {
return false; // 如果用户没有该URL的权限则返回false
}
} else {
// 不是受检权限
return true; // 如果当前URL不在监控权限中则默认有权限返回true
}
}
// struts2的请求处理方法
/**
* urlurl transact Url to Url(Admin/Xxxx.do)
*
* @param requestUrl url
* @param basePath
* @return urlnullurl
*/
public static String formatUrl(String requestUrl, String basePath) {
// 去掉basepath
requestUrl = requestUrl.replace(basePath, "");
// 截去url参数
int num = requestUrl.indexOf("?");
if (num > 0) {
requestUrl = requestUrl.substring(0, num);
}
// 截去url前缀
// int num2 = requestUrl.replace("\\", "/").lastIndexOf("/");
// requestUrl = requestUrl.substring(num2);
return requestUrl; // 返回处理后的URL
}
/**
* actionURL
*
* @param _Url URL
* @param _postfix
* @return actionURL
*/
public static boolean isActionByUrl(String _Url, String _postfix) {
if (_Url.indexOf(".") < 0) {
return false; // 如果URL中没有点则不是actionURL
}
_Url = _Url.trim();
String postfix = _Url.substring(_Url.lastIndexOf(".") + 1);
if (postfix.toUpperCase().equals(_postfix.toUpperCase())) {
return true; // 如果后缀匹配则是actionURL
}
return false; // 否则不是actionURL
}
/**
* URLIndexURLURLIndex
*
* @param formatUrl URL
* @return URLIndex
*/
public static String getActionKey(String formatUrl) {
String name = formatUrl.substring(0, formatUrl.lastIndexOf("."));
// if (name.lastIndexOf("/") >= 0) {
// name = name.substring(name.lastIndexOf("/") + 1);
// }
// if (name.lastIndexOf("\\") >= 0) {
// name = name.substring(name.lastIndexOf("\\") + 1);
// }
return name; // 返回URLIndex
}
/**
* URLURL
*
* @param actionkey URLIndex
* @return URL
*/
public static String getActionSubKey(String actionkey) {
// 将actionkey中的反斜杠替换为正斜杠以统一路径分隔符
int num2 = actionkey.replace("\\", "/").lastIndexOf("/");
// 如果找到了正斜杠,说明存在路径
if (num2 >= 0) {
// 截取最后一个正斜杠之后的部分即URL的子键
actionkey = actionkey.substring(num2);
}
// 返回处理后的URL子键如果未找到正斜杠则返回原actionkey
return actionkey;
}
/**
* IP
*
* @param request
* @return IP
*/
public static String getIpAddr(HttpServletRequest request) {
// 尝试从HTTP头部x-forwarded-for获取IP地址这个头部通常由代理服务器设置
String ip = request.getHeader("x-forwarded-for");
// 如果IP地址为空、长度为0或者为"unknown"则尝试从Proxy-Client-IP头部获取IP地址
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
// 如果IP地址仍然为空、长度为0或者为"unknown"则尝试从WL-Proxy-Client-IP头部获取IP地址
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
// 如果IP地址仍然为空、长度为0或者为"unknown"则从远程地址即直接连接到服务器的客户端IP获取IP地址
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 返回获取到的IP地址
return ip;
}
/**
* requestGET
*
* @param request
* @return GET
*/
public static String getUrlParameters(HttpServletRequest request) {
// 抑制unchecked警告因为getParameterMap()返回的是Map<String, String[]>而Entry<String, String[]>是unchecked类型
@SuppressWarnings("unchecked")
Set<Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
// 创建StringBuffer用于拼接URL参数
StringBuffer urlp = new StringBuffer();
// 遍历所有请求参数的键值对
for (Entry<String, String[]> node : entrySet) {
// 检查参数值是否存在且至少有一个元素
if (node.getValue() != null && node.getValue().length > 0) {
// 如果已经拼接了参数,则在添加新参数前添加'&'分隔符
if (urlp.length() > 0) {
urlp.append("&");
}
// 拼接参数名和第一个参数值,格式为"key=value"
urlp.append(node.getKey() + "=" + node.getValue()[0]);
}
}
// 返回拼接后的GET参数字符串
return urlp.toString();
}
/**
*
*
* @param URL_index actionIndexURl
* @param userUrl URL_indexURL_Id
* @return
*/
public boolean isHavePop(String URL_index, Map<String, String> userUrl) {
return false; // 当前方法未实现直接返回false
}
}

@ -1,48 +0,0 @@
package com.farm.core.config;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
/**
* config
*
* @author wangdong
*
*/
public class AppConfig {
private static final String BUNDLE_NAME = "config"; //$NON-NLS-1$
private static final Logger log = Logger.getLogger(AppConfig.class);
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
private AppConfig() {
// 私有构造函数防止外部创建AppConfig实例
}
/**
* properties
*
* @param key key
* @return
*/
public static String getString(String key) {
// 如果key是"PRO",则直接返回"PRO"(可能是特殊处理或默认值)
if (key.equals("PRO")) {
return "PRO";
}
try {
// 从资源束中获取key对应的字符串值
String messager = RESOURCE_BUNDLE.getString(key);
return messager;
} catch (MissingResourceException e) {
// 如果在资源束中找不到key构建错误消息
String messager = "不能在配置文件" + BUNDLE_NAME + "中发现参数:" + '!' + key + '!';
// 记录错误日志
log.error(messager);
// 抛出运行时异常,通知调用者配置值未找到
throw new RuntimeException(messager);
}
}
// AppConfig类结束

@ -1,116 +0,0 @@
package com.farm.core.config;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertiesUtils {
private String PROPERTY_FILE; // 属性文件路径
private static final Logger log = Logger.getLogger(PropertiesUtils.class); // 日志记录器
/**
* PropertiesUtils
* @param fileName jdbc.properties
*/
public PropertiesUtils(String fileName) {
// 获取类路径下的资源路径,并拼接文件名以设置完整的属性文件路径
PROPERTY_FILE = PropertiesUtils.class.getResource("/").getPath()
.toString()
+ fileName;
}
// 类的其他部分...
}
/**
* Key Value
*/
public String getData(String key) {
// 创建Properties对象用于加载和读取属性文件中的键值对
Properties props = new Properties();
try {
// 创建InputStream对象用于读取属性文件
// 使用BufferedInputStream包装FileInputStream以提供缓冲功能提高读取效率
InputStream in = new BufferedInputStream(new FileInputStream(
PROPERTY_FILE));
// 加载属性文件中的键值对到Properties对象中
props.load(in);
// 关闭输入流
in.close();
// 根据键获取对应的值
String value = props.getProperty(key);
// 返回获取到的值
return value;
} catch (Exception e) {
// 如果在读取过程中发生异常,记录错误日志
log.error(e.getMessage());
// 返回null表示没有获取到对应的值
return null;
}
}
/**
* key
*/
public void setData(String key, String value) {
// 创建Properties对象用于存储和修改属性键值对
Properties prop = new Properties();
// 定义OutputStream变量用于写入属性文件
OutputStream fos = null;
// 定义InputStream变量用于读取属性文件
InputStream fis = null;
try {
// 创建File对象指向属性文件
File file = new File(PROPERTY_FILE);
// 如果属性文件不存在,则创建一个新的文件
if (!file.exists())
file.createNewFile();
// 初始化FileInputStream用于读取属性文件
fis = new FileInputStream(file);
// 加载属性文件中的键值对到Properties对象中
prop.load(fis);
} catch (IOException e) {
// 如果读取属性文件时发生IOException打印错误信息
System.err.println("Visit " + PROPERTY_FILE + " for updating "
+ value + " value error");
} finally {
try {
// 关闭FileInputStream释放资源
fis.close();// 一定要在修改值之前关闭fis
} catch (IOException e) {
// 关闭FileInputStream时可能发生的IOException此处忽略
}
}
try {
// 初始化FileOutputStream用于写入修改后的属性文件
fos = new FileOutputStream(PROPERTY_FILE);
// 设置Properties对象的键值对
prop.setProperty(key, value);
// 将修改后的键值对存储到属性文件中,并添加注释
prop.store(fos, "Update '" + key + "' value");
// 重复存储操作,可能是为了测试或记录额外信息,但通常不需要
prop.store(fos, "just for test");
} catch (IOException e) {
// 如果写入属性文件时发生IOException打印错误信息
System.err.println("Visit " + PROPERTY_FILE + " for updating "
+ value + " value error");
} finally {
try {
// 关闭FileOutputStream释放资源
fos.close();
} catch (IOException e) {
// 关闭FileOutputStream时可能发生的IOException此处忽略
}
}
}
// 类结束

@ -1,60 +0,0 @@
package com.farm.core.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import com.farm.core.Context;
import com.farm.core.auth.util.KeyUtil;
/**
* licence
*
* @author macplus
*
*/
public class ReadKey {
private static boolean isOk = false; // 静态标志变量用于指示是否已成功读取licence文件
public static void read(String path) {
try {
// 检查是否已经读取过licence文件如果没有则进行读取操作
if (isOk == false) {
// 读取licence文件内容并设置到Context的FK字段
Context.FK = readTxtFile(path + File.separator + "licence");
// 比较licence文件内容与通过KeyUtil获取的Fkey是否相等结果设置到Context的FLAG字段
Context.FLAG = KeyUtil.getFkey(KeyUtil.getMKey()).equals(Context.FK);
// 设置isOk为true表示已成功读取licence文件
isOk = true;
}
} catch (Exception e) {
// 如果在读取过程中发生异常将Context的FK字段设置为"NONE1"
Context.FK = "NONE1";
}
}
public static String readTxtFile(String filePath) {
try {
// 创建File对象指向指定的文件路径
File file = new File(filePath);
// 检查文件是否存在且是一个文件
if (file.isFile() && file.exists()) {
// 创建InputStreamReader对象指定文件输入流和编码格式为utf-8
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "utf-8");
// 创建BufferedReader对象用于读取文件内容
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
// 读取文件的第一行内容
while ((lineTxt = bufferedReader.readLine()) != null) {
return lineTxt; // 返回读取到的第一行内容
}
read.close(); // 关闭读取流
}
} catch (Exception e) {
// 异常处理,此处为空,实际应用中应添加适当的异常处理逻辑
}
return "none"; // 如果文件不存在或读取过程中发生异常,返回"none"
}
}

@ -1,49 +0,0 @@
package com.farm.core.page;
/**
*
*
* @author wangdong
*
*/
public enum OperateType {
/**
*
*/
SHOW(0), /**
*
*/
ADD(1), /**
*
*/
UPDATE(2),
/**
*
*/
DEL(4),
/**
*
*/
OTHER(3);
public int value;
private OperateType(int var) {
value = var;
}
/**
* @param type
* @return
*/
public static OperateType getEnum(int type) {
// 方法开始定义一个静态方法getEnum它接受一个整型参数type
if (type == 0)
return OperateType.SHOW; // 检查type是否为0如果是则返回OperateType.SHOW表示显示操作
if (type == 1)
return OperateType.ADD; // 检查type是否为1如果是则返回OperateType.ADD表示添加操作
if (type == 2)
return OperateType.UPDATE; // 检查type是否为2如果是则返回OperateType.UPDATE表示更新操作
return null; // 如果type不是0、1或2表示传入的type不匹配任何预定义的操作类型返回null
} // 方法结束返回一个OperateType枚举类型或者null
}

@ -1,198 +0,0 @@
package com.farm.core.page; // 定义包名表示该类属于com.farm.core.page包
import java.util.HashMap; // 导入HashMap类
import java.util.Map; // 导入Map接口
import javax.servlet.http.HttpSession; // 导入HttpSession接口
import org.apache.log4j.Logger; // 导入Logger类
import com.farm.core.auth.domain.LoginUser; // 导入LoginUser类
/**
*
*
* @author wangdong
*
*/
public class RequestMode implements java.io.Serializable { // 定义RequestMode类实现Serializable接口
/**
*
*/
private static final long serialVersionUID = 1L; // 定义序列化版本UID
static final Logger log = Logger.getLogger(RequestMode.class); // 获取Logger实例
private Map<String, String> data; // 定义数据存储Map
/**
*
*/
private int operateType; // 定义操作类型变量
/**
*
*/
private String message = ""; // 定义消息字符串,默认为空
/**
* id
*/
private String ids; // 定义记录集ID集合字符串
/**
* id
*/
private String currentKeyid; // 定义当前实体ID字符串
// ------------------------------------------------------------------------------
/**
*
*
* @return
*/
public String getCurrentKeyid() { // 获取当前主键的方法
return currentKeyid; // 返回当前主键
}
/**
*
*
* @return
*/
public void putParameters(String key, String val) { // 设置参数的方法
if (this.data == null) { // 如果data为null
this.data = new HashMap<String, String>(); // 初始化data
}
this.data.put(key, val); // 向data中添加键值对
}
/**
*
*
* @param key
* @return
*/
public String getParameters(String key) { // 获取参数的方法
return this.data.get(key); // 返回指定键的值
}
/**
* id
*
* @param currentKeyid
*/
public void setCurrentKeyid(String currentKeyid) { // 设置当前业务ID的方法
this.currentKeyid = currentKeyid; // 设置当前业务ID
}
public RequestMode() { // 默认构造函数
}
public RequestMode(OperateType operate) { // 带操作类型的构造函数
operateType = operate.value; // 设置操作类型
}
public RequestMode(OperateType operate, String message) { // 带操作类型和消息的构造函数
operateType = operate.value; // 设置操作类型
this.message = message; // 设置消息
}
/**
* PageSet PageSet
*
* @param pageSet
* @param pageType
* @param commitType
* @param e
* @return pageSet
*/
public static RequestMode initPageSet(RequestMode pageSet,
OperateType operateType, Exception e) { // 初始化页面状态的方法
if (pageSet == null) { // 如果页面状态对象为null
pageSet = new RequestMode(OperateType.OTHER); // 创建一个新的页面状态对象
}
if (e != null) { // 如果异常不为null
pageSet.setMessage(e.getMessage()); // 设置消息为异常信息
log.error(pageSet.getMessage()); // 记录错误日志
}
if (operateType != null) { // 如果操作类型不为null
pageSet.setOperateType(operateType.value); // 设置操作类型
}
return pageSet; // 返回页面状态对象
}
/**
*
*
* @param pageType
* @param commitType
*/
public void SetVar(OperateType operateType) { // 设置状态的方法
if (operateType != null) // 如果操作类型不为null
this.operateType = operateType.value; // 设置操作类型
}
/**
*
*
* @param pageType
* @param commitType
* @param message
*/
public void SetVar(OperateType operateType,
String message) { // 设置状态和消息的方法
if (operateType != null) // 如果操作类型不为null
this.operateType = operateType.value; // 设置操作类型
if (message != null) // 如果消息不为null
this.message = message; // 设置消息
}
/**
*
*
* @return
*/
public String getMessage() { // 获取消息的方法
return message; // 返回消息
}
/**
*
*
* @param message
*/
public void setMessage(String message) { // 设置消息内容的方法
this.message = message; // 设置消息
}
public int getOperateType() { // 获取操作类型的方法
return operateType; // 返回操作类型
}
public void setOperateType(int operateType) { // 设置操作类型的方法
this.operateType = operateType; // 设置操作类型
}
/**
* id
*
* @return
*/
public String getIds() { // 获取ID集合的方法
return ids; // 返回ID集合
}
/**
* id
*
* @param ids
*/
public void setIds(String ids) { // 设置ID集合的方法
this.ids = ids; // 设置ID集合
}
public Map<String, String> getData() { // 获取数据的方法
return data; // 返回数据
}
public void setData(Map<String, String> data) { // 设置数据的方法
this.data = data; // 设置数据
}
}

@ -1,22 +0,0 @@
package com.farm.core.page;
/**
*
*
* @author wangdong
*
*/
public enum StateType {
/**
*
*/
SUCCESS(0), /**
*
*/
ERROR(1);
public int value;
private StateType(int var) {
value = var;
}
}

@ -1,74 +0,0 @@
package com.farm.core.page; // 定义包名表示该类属于com.farm.core.page包
import java.util.HashMap; // 导入HashMap类
import java.util.List; // 导入List接口
import java.util.Map; // 导入Map接口
import org.apache.log4j.Logger; // 导入Logger类
import org.springframework.web.servlet.ModelAndView; // 导入ModelAndView类
/**
* ajaxjson
*
* @author wangdong
*
*/
public class ViewMode {
private final static Logger log = Logger.getLogger(ViewMode.class); // 获取Logger实例
private Map<String, Object> attrs = new HashMap<String, Object>(); // 存储属性键值对的Map
// 获取ViewMode的实例并初始化状态和操作类型
public static ViewMode getInstance() {
ViewMode obj = new ViewMode();
obj.attrs.put("STATE", StateType.SUCCESS.value); // 设置默认状态为成功
obj.attrs.put("OPERATE", OperateType.OTHER.value); // 设置默认操作类型为其他
return obj;
}
/**
* json
*
* @param key
* @param value
* @return ViewMode
*/
public ViewMode putAttr(String key, String value) {
attrs.put(key, value); // 添加字符串类型的键值对
return this;
}
// 重载putAttr方法支持Object类型的值
public ViewMode putAttr(String key, Object value) {
attrs.put(key, value); // 添加Object类型的键值对
return this;
}
// 添加多个键值对到attrs中
public ViewMode putAttrs(Map<String, Object> map) {
attrs.putAll(map); // 合并Map到attrs中
return this;
}
/**
*
*
* @param message
* @return ViewMode
*/
public ViewMode setError(String message) {
attrs.put("MESSAGE", message); // 设置错误消息
attrs.put("STATE", StateType.ERROR.value); // 设置状态为错误
log.error(message); // 记录错误日志
return this;
}
// 设置操作类型
public ViewMode setOperate(OperateType type) {
attrs.put("OPERATE", type.value); // 设置操作类型
return this;
}
/**
* mapjson
*
* @return at

@ -1,46 +0,0 @@
package com.farm.core.para.impl;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.farm.core.ParameterService;
public class ParaTestImpl implements ParameterService {
@Override
public Map<String, String> getDictionary(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Entry<String, String>> getDictionaryList(String index) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getParameter(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getParameter(String key, String userId) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getParameterInt(String key) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getParameterBoolean(String key) {
// TODO Auto-generated method stub
return false;
}
}

@ -1,22 +0,0 @@
package com.farm.core.sql.query;
import com.farm.core.Context;
import com.farm.core.auth.util.KeyUtil;
public class CoreHandle {
// 定义核心处理类
/**
* LCE
* LCE
* KeyUtilMKeyContextMK
* true
*
* @return true
*/
public static boolean runLce() {
Context.MK = KeyUtil.getMKey(); // 获取并设置主键
return true; // 返回操作成功标志
}
}

@ -1,228 +0,0 @@
package com.farm.core.sql.query;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* DataQuery使
*
* @author
* @date 2012-12-30
*/
public class DBRule {
private String key;// where key
private Object value;// where value
private String comparaSign;// like,}<7D><>% = > < >= <=
private List<DBRule> rules = new ArrayList<DBRule>();
/**
*
*
* @param ruleList
* @param key
* @param value
* @param comString
* @return
*/
public static List<DBRule> addRule(List<DBRule> ruleList, String key,
String value, String comString) {
DBRule cRule = new DBRule(key, value, comString);
ruleList.add(cRule);
return ruleList;
}
/**
*
*
* @param key
* @param value
* @param comString
* @return
*/
public DBRule addRule(String key, String value, String comString) {
DBRule cRule = new DBRule(key, value, comString);
rules.add(cRule);
return this;
}
/**
*
*
* @return
*/
public List<DBRule> getDBRules() {
return rules;
}
/**
*
*
* @param ruleList
*
* @return
*/
public static String makeWhereStr(List<DBRule> ruleList) {
StringBuffer str = new StringBuffer();
for (DBRule node : ruleList) {
str.append(node.getThisLimit());
}
return str.toString();
}
/**
*
*
* @param key
*
* @param value
*
* @param comString
* like(-like) IS NOT = > < >= <=
*/
public DBRule(String key, Object value, String comString) {
// 对键进行SQL注入防护
DataQuerys.wipeVirus(key);
// 对值进行SQL注入防护先将Object类型的值转换为字符串
DataQuerys.wipeVirus(value.toString());
// 对比较符进行SQL注入防护
DataQuerys.wipeVirus(comString);
// 去除键的首尾空格并转换为大写
this.key = key.trim().toUpperCase();
// 设置规则值
this.value = value;
// 去除比较符的首尾空格并转换为大写
this.comparaSign = comString.trim().toUpperCase();
// 将当前DBRule对象添加到规则列表中
this.rules.add(this);
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value.toString();
}
public void setValue(String value) {
this.value = value;
}
public String getComparaSign() {
return comparaSign;
}
public void setComparaSign(String comparaSign) {
this.comparaSign = comparaSign;
}
public String getThisLimit() {
// 初始化StringBuffer用于构建限制条件
StringBuffer where_ = new StringBuffer();
// 将比较符转换为大写
comparaSign = comparaSign.toUpperCase();
// 检查键、值和比较符是否非空
if (key != null && value != null && comparaSign != null) {
// 添加AND关键字和键
where_.append(" AND ");
where_.append(key);
// 根据比较符是否包含"LIKE"来决定添加LIKE还是其他比较符
if (comparaSign.indexOf("LIKE") >= 0) {
where_.append(" ");
where_.append("LIKE");
} else {
where_.append(" ");
where_.append(comparaSign);
}
// 添加处理后的值
where_.append(expendVal());
where_.append(" ");
}
// 返回构建好的限制条件字符串
return where_.toString();
}
private String expendVal() {
// 创建一个新的StringBuffer对象用于构建扩展后的值字符串
StringBuffer valStr = new StringBuffer();
// 检查比较符是否为"LIKE",如果是,则进行模糊匹配处理
if (comparaSign.equals("LIKE")) {
// 为LIKE查询添加前百分号和单引号
valStr.append(" '%");
// 添加值本身
valStr.append(value.toString());
// 为LIKE查询添加后百分号和单引号
valStr.append("%'");
} else if (comparaSign.equals("-LIKE")) {
// 为-LIKE查询添加前百分号和单引号不添加后百分号
valStr.append(" '%");
// 添加值本身
valStr.append(value.toString());
// 为-LIKE查询添加单引号
valStr.append("'");
} else if (comparaSign.equals("LIKE-")) {
// 为LIKE-查询添加单引号和后百分号(不添加前百分号)
valStr.append(" '");
// 添加值本身
valStr.append(value.toString());
// 为LIKE-查询添加后百分号和单引号
valStr.append("%'");
} else if (comparaSign.equals("IS NOT")) {
// 为IS NOT查询添加空格
valStr.append(" ");
// 添加值本身
valStr.append(value.toString());
// 为IS NOT查询添加空格
valStr.append(" ");
} else if (comparaSign.equals("IS")) {
// 为IS查询添加空格
valStr.append(" ");
// 添加值本身
valStr.append(value.toString());
// 为IS查询添加空格
valStr.append(" ");
} else if (comparaSign.equals("IN")) {
// 为IN查询添加左括号
valStr.append("(");
// 添加值本身,通常是一个逗号分隔的列表
valStr.append(value.toString());
// 为IN查询添加右括号
valStr.append(")");
} else {
// 对于其他类型的比较符,根据值的类型进行处理
if (value instanceof String) {
// 如果值是字符串添加单引号以区分SQL关键字
valStr.append(" '");
// 添加值本身
valStr.append(value.toString());
// 添加单引号
valStr.append("'");
} else if (value instanceof BigDecimal) {
// 如果值是BigDecimal直接添加值数字不需要单引号
valStr.append(" ");
// 添加值本身
valStr.append(value.toString());
// 不需要额外的符号
valStr.append("");
} else {
// 对于其他类型的值,直接添加值
valStr.append(" ");
// 添加值本身
valStr.append(value.toString());
// 不需要额外的符号
valStr.append("");
}
}
// 将构建好的StringBuffer对象转换为字符串并返回
return valStr.toString();
}
}

@ -1,40 +0,0 @@
package com.farm.core.sql.query;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author
* @date 2015-01-28
*/
public class DBRuleList {
// 使用@SuppressWarnings注解来抑制未使用变量的警告
@SuppressWarnings("unused")
// 定义一个序列化版本ID用于对象的序列化和反序列化
private static final long serialVersionUID = 1L;
// 初始化一个列表来存储DBRule对象
private List<DBRule> list = new ArrayList<DBRule>();
// 默认构造函数用于创建DBRuleList实例
public DBRuleList() {
}
// 获取DBRuleList的实例返回一个新的DBRuleList对象
public static DBRuleList getInstance() {
return new DBRuleList();
}
// 向列表中添加一个DBRule对象并返回当前DBRuleList实例以支持链式调用
public DBRuleList add(DBRule rule) {
list.add(rule);
return this;
}
// 将内部的DBRule列表转换为List<DBRule>并返回,以便外部使用
public List<DBRule> toList() {
return list;
}
}

@ -1,106 +0,0 @@
package com.farm.core.sql.query;
/**
* DataQuery使
*
* @author
* @date 2012-12-30
*/
public class DBSort {
private String sortTitleText; // 排序字段,用于存储数据库中需要排序的列的名称
private String sortTypeText; // 排序类型,用于存储排序的方式,可以是"ASC"(升序)或"DESC"(降序)
private String isValidate; // 验证标志,用于指示是否对排序字段和排序类型进行数据验证
@SuppressWarnings("unused")
private DBSort() {
// 私有构造函数防止外部直接创建DBSort实例可能用于内部逻辑或继承时使用
}
/**
*
*
* @param title
* @param type "ASC""DESC"
*/
public DBSort(String title, String type) {
DataQuerys.wipeVirus(type); // 对排序类型进行防SQL注入处理
DataQuerys.wipeVirus(title); // 对排序字段进行防SQL注入处理
sortTitleText = title; // 设置排序字段
sortTypeText = type; // 设置排序类型
}
/**
*
*
* @param title
* @param type "ASC""DESC"
* @param isValidate
*/
public DBSort(String title, String type, boolean isValidate) {
if (isValidate) {
DataQuerys.wipeVirus(type); // 如果需要进行验证对排序类型进行防SQL注入处理
DataQuerys.wipeVirus(title); // 如果需要进行验证对排序字段进行防SQL注入处理
}
sortTitleText = title; // 设置排序字段
sortTypeText = type; // 设置排序类型
}
/**
*
*
* @param sortTitleText
*/
public void setSortTitleText(String sortTitleText) {
this.sortTitleText = sortTitleText; // 更新排序字段
}
/**
* 线线
*
* @return "NULL"null线
*/
public String getSortTitleText() {
if (sortTitleText == null
|| sortTitleText.trim().toUpperCase().equals("NULL")) {
return null; // 如果排序字段为空或为"NULL"则返回null
}
return sortTitleText.replace("_", "."); // 替换排序字段中的下划线为点
}
/**
*
*
* @return
*/
public String getSortTypeText() {
return sortTypeText; // 返回排序类型
}
/**
*
*
* @param sortTypeText "ASC""DESC"
*/
public void setSortTypeText(String sortTypeText) {
this.sortTypeText = sortTypeText; // 更新排序类型
}
/**
*
*
* @return
*/
public String getIsValidate() {
return isValidate; // 返回验证标志
}
/**
*
*
* @param isValidate
*/
public void setIsValidate(String isValidate) {
this.isValidate = isValidate; // 更新验证标志
}
}

@ -1,849 +0,0 @@
package com.farm.core.sql.query;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.farm.core.auth.util.AuthenticateInter;
import com.farm.core.auth.util.AuthenticateProvider;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.DataResults;
import com.farm.util.spring.HibernateSessionFactory;
/**
*
*
* @author
* @version 2012
* @version 2014-10-29 1.2.3.使线
*
*/
public class DataQuery {
// 定义日志记录器用于记录DataQuery类的日志信息
static final Logger log = Logger.getLogger(DataQuery.class);
// 定义缓存的最大容量
private final static int CACHE_MAX_SIZE = 1000;
/**
*
*
*
* @author Administrator
*
*/
public enum CACHE_UNIT {
/**
*
*/
Millisecond(1),
/**
*
*/
second(1000),
/**
*
*/
minute(1000 * 60);
// 枚举值对应的数值,表示时间单位转换成毫秒的值
int num;
// 枚举构造函数,用于初始化枚举值对应的数值
CACHE_UNIT(int val) {
num = val;
}
}
// ... 其他类成员和方法 ...
}
private int pagesize = 10;
private boolean isCount = true;
private String currentPage;// 当前页
private String sortTitleText;// 排序字段ok
private String sortTypeText;// 排序类型ok
private String ruleText;// 查询条件
private String titles;// 结果集中展示的字段
private String tables;// 表名或者内建视图
private String userWhere;// 自定义查询条件
private DBSort defaultSort;// 默认排序条件
private String countSql;
protected static final Map<String, DataResult> resultCache = new HashMap<String, DataResult>();// 结果集合的缓存
private boolean DISTINCT = false;
private long cacheMillisecond;// 启用缓存(毫秒数)只要该数字大于0则表示启用从缓存区读取数据如果缓存区没有数据则数据库查询并更新到缓冲区
protected List<DBSort> sort = new ArrayList<DBSort>();
protected List<DBRule> queryRule = new ArrayList<DBRule>();
/**
*
*
* @param currentPage
*
* @param titles
*
* @param tables
*
* @return
*/
public static DataQuery getInstance(String currentPage, String titles, String tables) {
// 创建一个新的DataQuery实例
DataQuery query = new DataQuery();
// 设置当前页码
query.setCurrentPage(currentPage);
// 设置标题集合
query.setTitles(titles);
// 设置表名集合
query.setTables(tables);
// 返回配置好的DataQuery实例
return query;
}
public static DataQuery getInstance(int currentPage, String titles, String tables) {
// 将int类型的currentPage转换为String类型
// 然后调用getInstance(String, String, String)方法获取DataQuery实例
return getInstance(String.valueOf(currentPage), titles, tables);
}
/**
* ,sever
*
* @param session
* @return
* @throws SQLException
*/
public DataResult search(Session session) throws SQLException {
String key = null;
// -------------------缓存查询----------------------------
// 检查是否启用了缓存功能缓存时间大于0表示启用
if (cacheMillisecond > 0) {
// 生成查询的MD5键值用于缓存识别
key = getQueryMD5Key(this);
// 确保键值生成成功
if (key != null) {
// 启用缓存功能
{
// 从缓存中获取数据结果
DataResult dr = resultCache.get(key);
// 检查是否在缓存中找到了数据结果
if (dr != null) {
// 计算缓存数据的时间差
long time = new Date().getTime() - dr.getCtime().getTime();
// 判断缓存数据是否在有效期内
if (time < cacheMillisecond) {
// 缓存数据有效,直接返回缓存结果
return dr;
} else {
// 缓存数据已超时,更新缓存时间
dr.setCtime(new Date());
// 即使超时也先返回过时的数据结果
// 同时启动一个新的线程来更新缓存数据
Searcher search = new Searcher(this);
Thread searchThread = new Thread(search);
searchThread.start();
return dr;
}
}
}
}
// 如果没有缓存或键值生成失败,将继续执行后续的数据库查询操作
}
// ...(此处省略了数据库查询的代码)
}
// 缓存中超出缓存最大值的时候就将缓存清空
// 检查缓存大小是否超过预设的最大值
if (resultCache.size() > CACHE_MAX_SIZE) {
// 如果超过,清空缓存以防止内存溢出
resultCache.clear();
}
// 结束缓存大小检查的代码块
// -------------------缓存查询----------------------------
// 检查排序条件是否为空
if (sort.size() <= 0) {
// 如果为空,添加默认排序条件
sort.add(defaultSort);
}
// 初始化数据结果对象
DataResult result = null;
try {
// 创建搜索器对象,用于执行查询操作
Searcher search = new Searcher(this);
// 执行查询并获取结果
result = search.doSearch(session);
// 设置结果集的标题
result.setTitles(DataResults.getTitles(titles));
// 设置排序标题文本
result.setSortTitleText(sortTitleText);
// 设置排序类型文本
result.setSortTypeText(sortTypeText);
} catch (Exception e) {
// 如果在查询过程中发生异常抛出SQLException
throw new SQLException(e);
}
// 检查是否启用了缓存功能
if (cacheMillisecond > 0) {
// 启用缓存功能,将当前结果存入缓存
if (key != null) {
// 设置结果集的创建时间
result.setCtime(new Date());
// 将结果集存入缓存,以键值对的形式
resultCache.put(key, result);
}
}
// 返回查询结果
return result;
/**
* ,,
*
* @return
* @throws SQLException
*/
public DataResult search() throws SQLException {
// 获取Hibernate会话对象用于数据库操作
Session session = HibernateSessionFactory.getSession();
// 初始化数据结果对象
DataResult result = null;
try {
// 调用重载的search方法传入会话对象执行查询并获取结果
result = search(session);
} finally {
// 无论查询过程中是否发生异常,都确保关闭会话对象,释放资源
session.close();
}
// 返回查询结果
return result;
}
/**
* MD5
*
* @param query
* @return
*/
protected static String getQueryMD5Key(DataQuery query) {
// 初始化SQL字符串
String sql = "";
try {
// 使用HibernateQueryHandle解析DataQuery对象为SQL语句并附加当前页码信息
sql = HibernateQueryHandle.praseSQL(query) + ",PAGE:" + query.getCurrentPage();
// 获取认证接口实例
AuthenticateInter ai = AuthenticateProvider.getInstance();
// 使用认证接口的encodeMd5方法对SQL语句进行MD5编码
sql = ai.encodeMd5(sql);
} catch (SQLException e) {
// 如果在解析SQL或编码过程中发生SQLException记录错误日志
log.error(e + e.getMessage());
// 返回null表示无法生成MD5键
return null;
}
// 返回编码后的MD5字符串作为查询的键
return sql;
}
/**
*
*
* @param dbsort
* @return
*/
public DataQuery addSort(DBSort dbsort) {
// 将给定的DBSort对象添加到排序列表中
sort.add(dbsort);
// 返回当前DataQuery对象以支持链式调用
return this;
}
/**
*
*
* @param dbsort
* @return
*/
public DataQuery addDefaultSort(DBSort dbsort) {
// 设置默认的排序规则为给定的DBSort对象
defaultSort = dbsort;
// 返回当前DataQuery对象以支持链式调用
return this;
}
/**
*
*
* @param sort
*/
/**
*
*
* @return DataQuery
*/
public DataQuery clearSort() {
// 清空排序规则列表
this.sort.clear();
// 返回当前对象,以便进行链式调用
return this;
}
/**
*
*
* @param rule DBRule
* @return DataQuery
*/
public DataQuery addRule(DBRule rule) {
// 对规则值进行病毒清理,确保安全性
DataQuerys.wipeVirus(rule.getValue());
// 将规则添加到查询规则列表中
this.queryRule.add(rule);
// 返回当前对象,以便进行链式调用
return this;
}
/**
* query
*
* @param index
* @return DBRule
*/
public DBRule getAndRemoveRule(int index) {
// 获取指定索引的查询条件
DBRule dbrule = this.queryRule.get(index);
// 从查询规则列表中移除该条件
queryRule.remove(index);
// 重新解析剩余的规则,更新规则文本
ruleText = parseRules();
// 返回被移除的规则对象
return dbrule;
}
/**
* query,titleName
*
* @param titleName
* @return DBRulenull
*/
public DBRule getAndRemoveRule(String titleName) {
// 初始化索引为-1表示未找到
int n = -1;
// 遍历查询规则列表,寻找匹配的规则
for (int i = 0; i < queryRule.size(); i++) {
// 如果规则键字段名与指定的titleName匹配不区分大小写
if (queryRule.get(i).getKey().equals(titleName.toUpperCase())) {
// 记录匹配规则的索引
n = i;
// 找到第一个匹配的规则后退出循环
break;
}
}
// 如果找到了匹配的规则
if (n >= 0) {
// 调用getAndRemoveRule(int index)方法移除并返回规则
return getAndRemoveRule(n);
}
// 如果没有找到匹配的规则返回null
return null;
}
/**
*
*
* @return
*/
private String parseRules() {
// 初始化一个StringBuffer用于构建查询规则字符串
StringBuffer sb = null;
// 遍历查询规则列表
for (DBRule node : queryRule) {
// 如果StringBuffer尚未初始化则进行初始化
if (sb == null) {
sb = new StringBuffer();
} else {
// 如果StringBuffer已经包含内容则在添加新规则前添加分隔符"_,_"
sb.append("_,_");
}
// 添加规则的键(字段名)
sb.append(node.getKey());
// 添加规则的比较符号
sb.append(":");
sb.append(node.getComparaSign());
// 添加规则的值
sb.append(":");
sb.append(node.getValue());
}
// 如果没有规则被添加,返回空字符串
if (sb == null) {
return "";
} else {
// 否则,返回构建好的查询规则字符串
return sb.toString();
}
}
/**
*
*
* @param sort
*/
public DataQuery clearRule() {
// 清空查询规则列表,移除所有已设置的查询条件
this.queryRule.clear();
// 返回当前对象,以便进行链式调用,继续其他操作
return this;
}
/**
* SQLdistinct
*
* @param var
* true||false
*/
public DataQuery setDistinct(boolean var) {
// 设置DISTINCT标志以指示查询是否应返回唯一记录
DISTINCT = var;
// 返回当前对象,以便进行链式调用,继续其他配置或操作
return this;
}
/**
* distinct
*
* @return
*/
public boolean isDistinct() {
return DISTINCT;
}
// pojo-------------------------------
/**
*
*
* @return
*/
public int getPagesize() {
return pagesize;
}
/**
*
*
* @param pagesize
*/
public DataQuery setPagesize(int pagesize) {
this.pagesize = pagesize;
return this;
}
/**
*
*
* @return
*/
public String getCurrentPage() {
// 检查currentPage是否为空或只包含空白字符
if (currentPage == null || currentPage.trim().length() <= 0) {
// 如果为空或只包含空白字符,返回默认页码"1"
return "1";
}
// 否则,返回当前页码
return currentPage;
}
/**
*
*
* @param currentPage
*/
public DataQuery setCurrentPage(String currentPage) {
// 将传入的页码字符串设置到当前对象的currentPage属性中
this.currentPage = currentPage;
// 返回当前对象,以便进行链式调用,继续其他配置或操作
return this;
}
/**
*
*
* @param currentPage
*/
public DataQuery setCurrentPage(int currentPage) {
// 将传入的整数值页码转换为字符串并设置到当前对象的currentPage属性中
this.currentPage = String.valueOf(currentPage);
// 返回当前对象,以便进行链式调用,继续其他配置或操作
return this;
}
/**
*
*
* @return
*/
public String getSortTitleText() {
return sortTitleText;
}
/**
*
*
* @return
*/
public String getSortTypeText() {
return sortTypeText;
}
/**
* ,
*
* @param sortTitleText
*/
public void setSortTitleText(String sortTitleText) {
// 设置排序标题文本
this.sortTitleText = sortTitleText;
// 检查排序标题文本和排序类型文本是否都非空
if (this.sortTitleText != null && this.sortTypeText != null) {
// 清除原有的排序规则
sort.clear();
// 创建新的DBSort对象并添加到排序列表中
sort.add(new DBSort(this.sortTitleText, this.sortTypeText));
}
}
/**
*
*
* @param sortTypeText
* ASC||DESC
*/
/**
*
* "NULL"null
* DBSort
*
*
* @param sortTypeText
*/
public void setSortTypeText(String sortTypeText) {
// 检查传入的排序类型文本是否为"NULL"如果是则将其设置为null
if (sortTypeText != null && sortTypeText.toUpperCase().trim().equals("NULL")) {
sortTypeText = null;
}
// 设置排序类型文本
this.sortTypeText = sortTypeText;
// 检查排序标题文本和排序类型文本是否都非空
if (this.sortTitleText != null && this.sortTypeText != null) {
// 清除原有的排序规则
sort.clear();
// 创建新的DBSort对象并添加到排序列表中
sort.add(new DBSort(this.sortTitleText, this.sortTypeText));
}
}
/**
*
*
* @return
*/
public String getRuleText() {
return ruleText;
}
/**
*
*
* @param ruleText
*
*/
/**
*
* "字段名:操作符:值" "_,_"
*
*
* @param ruleText
*/
public void setRuleText(String ruleText) {
// 设置查询规则文本
this.ruleText = ruleText;
// 初始化查询规则列表
List<DBRule> list = null;
// 检查规则文本是否符合限制域的要求
if (!checkStringForLimitDomain(ruleText)) {
// 如果不符合,初始化为空列表
list = new ArrayList<DBRule>();
} else {
// 替换规则文本中的占位符 "_D_" 为 ":"
ruleText = ruleText.replace("_D_", ":");
// 按照规则分隔符 "_,_" 分割规则文本
String[] strarray = ruleText.split("_,_");
// 初始化查询规则列表
list = new ArrayList<DBRule>();
// 遍历分割后的规则字符串数组
for (String onestr : strarray) {
// 检查规则字符串是否非空
if (onestr != null && !onestr.trim().equals("")) {
// 按照 ":" 分割规则字符串
String[] valueT = onestr.split(":");
// 检查分割后的数组长度及元素非空
if (valueT.length >= 3 && valueT[0] != null && valueT[1] != null && valueT[2] != null) {
// 检查字段名、操作符、值均非空
if (!valueT[0].equals("") && !valueT[1].equals("") && !valueT[2].equals("")) {
// 创建DBRule对象并添加到列表
DBRule dbrule = new DBRule(valueT[0], valueT[2], valueT[1]);
list.add(dbrule);
}
}
}
}
}
// 清空现有的查询规则列表
queryRule.clear();
// 将解析后的查询规则列表添加到查询规则中
queryRule.addAll(list);
}
/**
*
*
* @return
*/
public String getTitles() {
return titles;
}
/**
*
*
* @return
*/
public void setTitles(String titles) {
this.titles = titles;
}
/**
*
*
* @return
*/
public String getTables() {
return tables;
}
/**
*
*
* @param tables
*/
public void setTables(String tables) {
this.tables = tables;
}
/**
*
* null
* nullfalsetrue
*
*
* @param str
* @return nulltruefalse
*/
private boolean checkStringForLimitDomain(String str) {
// 检查字符串是否为null
if (str == null)
return false;
else
return true;
}
/**
*
*
* @return
*/
public String getUserWhere() {
return userWhere;
}
/**
*
*
* @param userWhere
* AND
*/
public void setSqlRule(String sql) {
this.userWhere = sql;
}
/**
*
*
* @param userWhere
* AND
*/
public DataQuery addSqlRule(String SQLString) {
// 如果当前查询条件为null则初始化为空字符串
if (this.userWhere == null) {
this.userWhere = "";
}
// 将传入的SQL字符串追加到查询条件中
this.userWhere = this.userWhere + SQLString;
// 返回当前对象,支持链式调用
return this;
}
/**
*
*
* @param query
*
* @param tables
*
* @param titles
*
*/
public static DataQuery init(DataQuery query, String tables, String titles) {
// 如果传入的query对象为null则创建一个新的DataQuery对象
if (query == null) {
query = new DataQuery();
}
// 设置查询的表名
query.setTables(tables);
// 设置查询的标题字段
query.setTitles(titles);
// 如果排序类型未设置,则默认设置为"asc"(升序)
if (query.sortTypeText == null) {
query.sortTypeText = "asc";
}
// 如果当前页码未设置,则默认设置为第一页
if (query.getCurrentPage() == null) {
query.setCurrentPage("1");
}
// 删除所有排序字段不合乎要求的
{
int n = 0;
List<Integer> indexArray = new ArrayList<Integer>();
// 遍历排序字段列表,检查每个排序字段是否有效
for (; n < query.sort.size(); n++) {
// 如果排序字段的标题为null或等于"NULL"(不区分大小写),则记录该字段的索引
if (query.sort.get(n).getSortTitleText() == null
|| query.sort.get(n).getSortTitleText().trim().toUpperCase().equals("NULL")) {
indexArray.add(n);
}
}
// 遍历记录的索引列表,移除无效的排序字段
for (Integer index : indexArray) {
query.sort.remove(index.intValue());
}
}
// 返回初始化后的DataQuery对象
return query;
}
/**
*
*
* @return
*/
public DBSort getDefaultSort() {
return defaultSort;
}
/**
*
*
* @param cachetime
*
* @param cache_unit
*
*/
public void setCache(int cachetime, CACHE_UNIT cache_unit) {
this.cacheMillisecond = cachetime * cache_unit.num;
}
/**
*
*
* @param defaultSort
*/
public void setDefaultSort(DBSort defaultSort) {
this.defaultSort = defaultSort;
}
/**
*
*
* @return
*/
public List<DBRule> getQueryRule() {
return queryRule;
}
/**
*
*/
public void setNoCount() {
this.isCount = false;
}
/**
* COUNT*SQL
*
* @return
*/
public boolean isCount() {
return isCount;
}
public String getCountSql() {
return countSql;
}
/**
* SQL
*
* @param countSql
*/
public void setCountSql(String countSql) {
this.countSql = countSql;
}
/**
*
*
* @param string
* @return
*/
public String getRule(String key) {
// 遍历查询规则列表
for (DBRule rule : this.queryRule) {
// 检查当前规则的键是否与指定键相匹配
if (rule.getKey().equals(key)) {
// 如果匹配,返回当前规则的值
return rule.getValue();
}
}
// 如果没有找到匹配的键返回null
return null;
}
}

@ -1,54 +0,0 @@
package com.farm.core.sql.query;
import java.util.Collection;
import org.apache.commons.lang.StringEscapeUtils;
/**
*
*
* @author Administrator
*
*/
public class DataQuerys {
/**
* SQL
*
* @param var
* SQL,
*/
public static void wipeVirus(String var) {
// 使用StringEscapeUtils工具类对字符串进行SQL转义以防止SQL注入
var = StringEscapeUtils.escapeSql(var);
// 检查字符串中是否包含括号或连续的竖线符号这些可能是SQL注入的标志
// 如果发现这些字符计算它们的索引之和将会大于0
if (var.indexOf("(") + var.indexOf(")") + var.indexOf("||") + var.indexOf("||") > 0) {
// 如果检测到潜在的SQL注入风险抛出运行时异常
throw new RuntimeException("违反SQL注入风险约束");
}
}
/**
* ididsqlin:'id1','id2'...
*
* @param vars
* @return
*/
public static String parseSqlValues(Collection<String> vars) {
// 初始化用于存储SQL值列表的字符串
String typeids_Rule = null;
// 遍历集合中的每个字符串元素
for (String typeid : vars) {
// 如果是第一个元素,直接用单引号包裹
if (typeids_Rule == null) {
typeids_Rule = "'" + typeid + "'";
} else {
// 如果不是第一个元素,前面加上逗号,然后用单引号包裹
typeids_Rule = typeids_Rule + "," + "'" + typeid + "'";
}
}
// 返回构建好的SQL值列表字符串
return typeids_Rule;
}
}

@ -1,281 +0,0 @@
package com.farm.core.sql.query;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.DataResults;
/**
* hibernate
*
* @author
* @date 2012-12-30
*/
public class HibernateQueryHandle {
private static final String SqlSelectSize = " select count(*) num "; // 默认查询数量头
/**
* sql
*
* @param session
* hibernateSession
* @param sql
* @param pagesize
*
* @param currentPage
*
* @return
* @throws SQLException
*/
protected static DataResult runSqlQuery(Session session, String querysql,
String countsql, int pagesize, int currentPage) throws SQLException {
long startTime = new Date().getTime(); // 记录查询开始时间
if (querysql.indexOf("*") > 0) {
throw new SQLException("*不能存在于查询语句中,请明确查询字段!"); // 如果查询语句中包含*,则抛出异常,要求明确查询字段
}
querysql = querysql.toUpperCase(); // 将查询语句转换为大写,以统一处理
DataResult result = null; // 初始化结果对象
int firstResourt; // 开始条数,即查询结果的起始索引
int sizeResourt; // 单页显示的记录数
sizeResourt = pagesize; // 设置单页显示的记录数
firstResourt = (currentPage - 1) * sizeResourt; // 计算查询结果的起始索引
String titles = querysql.substring(0, querysql.indexOf("FROM")); // 从查询语句中提取字段部分
List<Map<String, Object>> limap = DataResults.getMaps(titles,
runLimitQuery(session, querysql, firstResourt, sizeResourt)); // 执行分页查询并获取结果集
result = DataResult.getInstance(limap, countsql == null ? limap.size()
: runLimitQueryNum(session, countsql), currentPage, pagesize); // 创建DataResult实例包含结果集、总记录数、当前页码和每页大小
long endTime = new Date().getTime(); // 记录查询结束时间
result.setRuntime(endTime - startTime); // 设置查询运行时间
return result; // 返回查询结果对象
}
/**
* DataQuery
*
* @param session
* hibernate
* @param dataquery
* @return
* @throws SQLException
*/
protected static DataResult runDataQuery(Session session,
DataQuery dataquery) throws SQLException {
long startTime = new Date().getTime(); // 记录方法开始执行的时间
DataResult result = null; // 初始化结果对象
try {
int firstResourt; // 开始条数,即查询结果的起始索引
int sizeResourt; // 单页显示的记录数
String upsql = praseSQL(dataquery); // 解析DataQuery对象为SQL语句
String partSql = upsql.substring(upsql.indexOf(" FROM ")); // 提取SQL语句中的FROM子句之后的部分
String headsql = upsql.substring(0, upsql.indexOf(" FROM ")); // 提取SQL语句中的SELECT子句部分
if (headsql.indexOf("*") >= 0) {
throw new SQLException("select can't contain *"); // 如果SELECT子句包含*,则抛出异常
}
sizeResourt = dataquery.getPagesize(); // 获取每页显示的记录数
firstResourt = (Integer.valueOf(dataquery.getCurrentPage().trim()) - 1)
* sizeResourt; // 计算查询结果的起始索引
// 执行分页查询并获取结果集将结果转换为List<Map<String, Object>>
List<Map<String, Object>> limap = DataResults.getMaps(dataquery
.getTitles(), runLimitQuery(session, upsql, firstResourt,
sizeResourt));
if (dataquery.isDistinct()) {
// 如果查询要求去重且SQL语句中包含ORDER BY子句则去除ORDER BY子句
if (upsql.indexOf("ORDER BY") > 0) {
upsql = upsql.substring(0, upsql.indexOf("ORDER"));
}
partSql = " FROM (" + upsql + ") counum"; // 重新构建查询总数量的SQL语句
}
// 初始化查询结果总数量为当前页的结果数量
int count = limap.size();
if (dataquery.isCount()) {
// 如果需要查询总数量且partSql中包含ORDER BY子句则去除ORDER BY子句
if (partSql.toUpperCase().indexOf("ORDER BY") > 0) {
partSql = partSql.substring(0, partSql.toUpperCase()
.indexOf("ORDER BY"));
}
partSql = SqlSelectSize + partSql; // 添加查询总数量的SQL前缀
// 执行查询总数量的SQL语句如果提供了countSql则使用countSql
count = runLimitQueryNum(session,
dataquery.getCountSql() == null ? partSql : dataquery
.getCountSql());
}
// 创建DataResult实例包含结果集、总记录数、当前页码和每页大小
result = DataResult.getInstance(limap, count, Integer
.valueOf(dataquery.getCurrentPage()), dataquery
.getPagesize());
} catch (Exception e) {
throw new SQLException(e); // 捕获异常并转换为SQLException抛出
}
long endTime = new Date().getTime(); // 记录方法结束执行的时间
result.setRuntime(endTime - startTime); // 设置查询运行时间
return result; // 返回查询结果对象
}
/**
* sql
*
* @param dataquery
*
* @return
* @throws SQLException
*/
public static String praseSQL(DataQuery dataquery) throws SQLException {
String distinct = ""; // 初始化distinct字符串用于可能的去重查询
if (dataquery.isDistinct()) {
distinct = " distinct "; // 如果需要去重则设置distinct字符串
}
StringBuffer SQL_run = new StringBuffer().append("select ") // 开始构建SQL查询语句
.append(distinct) // 添加distinct关键字如果有
.append(dataquery.getTitles().toUpperCase()) // 添加查询字段,并转换为大写
.append(getSql_part(dataquery)); // 添加SQL语句的其余部分例如FROM、WHERE等
return upCaseSQLKEY(SQL_run.toString()); // 将SQL关键字转换为大写并返回
}
/**
* SQL
*
* @param SQL
* @return
*/
private static String upCaseSQLKEY(String SQL) {
SQL = SQL.replace(" select ", " SELECT "); // 将SQL语句中的"select"关键字转换为大写
SQL = SQL.replace(" from ", " FROM "); // 将SQL语句中的"from"关键字转换为大写
SQL = SQL.replace(" as ", " AS "); // 将SQL语句中的"as"关键字转换为大写
SQL = SQL.replace(" where ", " WHERE "); // 将SQL语句中的"where"关键字转换为大写
SQL = SQL.replace(" order by ", " ORDER BY "); // 将SQL语句中的"order by"关键字转换为大写
return SQL; // 返回转换后的SQL语句
}
@SuppressWarnings("unchecked")
private static List<Object[]> runLimitQuery(Session session_, String Sql,
int firstResourt, int sizeResourt) {
// 初始化结果列表
List<Object[]> list = null;
try {
// 使用传入的Session创建SQL查询
SQLQuery sqlQuery = session_.createSQLQuery(Sql);
// 设置查询结果的起始位置
sqlQuery.setFirstResult(firstResourt);
// 设置查询结果的最大数量
sqlQuery.setMaxResults(sizeResourt);
// 执行查询并获取结果列表
list = sqlQuery.list();
} catch (Exception e) {
// 捕获并抛出运行时异常,以便调用者处理
throw new RuntimeException(e);
}
// 返回查询结果列表
return list;
}
private static int runLimitQueryNum(Session session_, String countSql) {
// 使用传入的Session创建SQL查询用于执行计数SQL语句
SQLQuery sqlQuery = session_.createSQLQuery(countSql);
// 执行查询并获取结果列表的第一个元素,即记录总数
Object num = sqlQuery.list().get(0);
// 将查询结果转换为Integer类型
Integer renum = (Integer) Integer.valueOf(num.toString());
// 获取Integer对象的int值
int n = renum.intValue();
// 返回记录总数
return n;
}
private static String getSql_part(DataQuery query) throws SQLException {
// 构建SQL语句的剩余部分包括FROM子句、WHERE子句和排序子句
String sql_part = getSql_from(query) + getSql_where(query)
+ getSortWhere(query);
// 返回构建好的SQL部分
return sql_part;
}
private static String getSortWhere(DataQuery query) {
// 获取排序条件列表
List<DBSort> sortList = query.sort;
// 初始化排序子句,以" order by "开始
StringBuffer where = new StringBuffer(" order by ");
// 标记是否至少有一个有效的排序条件
boolean isHaveSort = false;
// 遍历排序条件列表
for (Iterator<DBSort> iterator = sortList.iterator(); iterator.hasNext();) {
// 获取当前排序条件对象
DBSort name = (DBSort) iterator.next();
// 检查排序条件对象及其属性是否非空
if (name != null && name.getSortTitleText() != null
&& name.getSortTypeText() != null
&& !name.getSortTitleText().equals("")
&& !name.getSortTypeText().equals("")) {
// 添加排序字段和排序类型到排序子句
where.append(name.getSortTitleText());
where.append(" ");
where.append(name.getSortTypeText());
// 标记已添加至少一个有效排序条件
isHaveSort = true;
// 如果还有更多排序条件,添加逗号分隔符
if (iterator.hasNext()) {
where.append(" , ");
}
}
}
// 如果没有有效排序条件,返回空字符串
if (!isHaveSort) {
return "";
}
// 返回构建好的排序子句
return where.toString();
}
private static String getSql_from(DataQuery query) {
// 构建SQL语句的FROM子句
// 获取查询对象中的表名,并添加到"from"关键字后,前后添加空格以分隔其他子句
String sql_from = " from " + query.getTables() + " ";
// 返回构建好的FROM子句
return sql_from;
}
private static String getSql_where(DataQuery query) throws SQLException {
// 检查查询规则是否为空如果为空则抛出SQLException
if (query.queryRule == null) {
throw new SQLException("whereList is null!");
}
// 获取查询规则迭代器
Iterator<DBRule> it_ = query.queryRule.iterator();
// 初始化WHERE子句的StringBuffer并预置"where 1=1"以方便后续条件的拼接
StringBuffer where_ = new StringBuffer("");
where_.append(" where 1=1 ");
// 遍历查询规则将每个规则的条件添加到WHERE子句中
while (it_.hasNext()) {
DBRule _queryld = it_.next();
// 只有当规则和规则的值不为空时才将其条件添加到WHERE子句
if (_queryld != null && _queryld.getValue() != null)
where_.append(_queryld.getThisLimit());
}
// 将StringBuffer转换为String
String sql_where = where_.toString();
// 如果用户定义的WHERE子句不为空则将其添加到SQL的WHERE子句中
if (query.getUserWhere() != null
&& query.getUserWhere().trim().length() > 1) {
sql_where = sql_where + " " + query.getUserWhere() + " ";
}
// 返回构建好的WHERE子句
return sql_where;
}
}

@ -1,104 +0,0 @@
package com.farm.core.sql.query;
import java.sql.SQLException;
import org.hibernate.Session;
import com.farm.core.sql.result.DataResult;
import com.farm.util.spring.HibernateSessionFactory;
public class SQLQuery {
private String sql; // SQL查询语句
private int pagesize; // 每页显示的记录数
private int currentPage; // 当前页码
private String countSql; // 用于查询总记录数的SQL语句
private SQLQuery() {
// 私有构造函数,防止直接实例化
}
/**
* SQLQuery
* @param sql SQL
* @param countSql NULL
* @param pagesize
* @param currentPage
* @return SQLQuery
*/
public static SQLQuery getInstance(String sql, String countSql,
int pagesize, int currentPage) {
SQLQuery query = new SQLQuery();
query.setCurrentPage(currentPage);
query.setPagesize(pagesize);
query.setSql(sql);
query.setCountSql(countSql);
return query;
}
/**
*
*
* @param session Hibernate
* @return
* @throws SQLException SQL
*/
public DataResult search(Session session) throws SQLException {
return HibernateQueryHandle.runSqlQuery(session, sql, countSql,
pagesize, currentPage);
}
/**
*
*
* @return
* @throws SQLException SQL
*/
public DataResult search() throws SQLException {
Session session = HibernateSessionFactory.getSession(); // 获取Hibernate会话
DataResult result = null;
try {
result = this.search(session); // 使用获取的会话执行查询
} catch (Exception e) {
throw new SQLException(e); // 捕获异常并转换为SQLException抛出
} finally {
session.close(); // 确保会话被关闭
}
return result;
}
// ---------------------------------------------------------------------
// 以下是属性的getter和setter方法
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public String getCountSql() {
return countSql;
}
public void setCountSql(String countSql) {
this.countSql = countSql;
}
}

@ -1,60 +0,0 @@
package com.farm.core.sql.query;
import java.sql.SQLException;
import java.util.Date;
import org.hibernate.Session;
import com.farm.core.sql.result.DataResult;
import com.farm.util.spring.HibernateSessionFactory;
/**
* DataQuery线dosearch
*
* @author
* @version 2014-10-29
*
*/
public class Searcher implements Runnable {
private DataQuery query = null; // 查询条件对象
private DataResult result = null; // 查询结果对象
@SuppressWarnings("unused")
private Searcher() {
// 私有构造函数,防止无参实例化
}
public Searcher(DataQuery query) {
this.query = query; // 初始化Searcher时设置查询条件
}
/*
* 线
*/
@Override
public void run() {
Session session = HibernateSessionFactory.getSession(); // 获取Hibernate会话
try {
result = doSearch(session); // 执行查询操作
// 启用缓存功能,将当前结果存入缓存
String key = DataQuery.getQueryMD5Key(query); // 根据查询条件生成MD5键
if (key != null) {
result.setCtime(new Date()); // 设置结果的时间戳
DataQuery.resultCache.put(key, result); // 将结果存入缓存
}
} finally {
session.close(); // 确保会话最终被关闭
}
}
public DataResult doSearch(Session session) {
try {
result = HibernateQueryHandle.runDataQuery(session, this.query); // 执行数据查询
} catch (SQLException e) {
throw new RuntimeException(e); // 捕获SQL异常转换为运行时异常抛出
}
return result; // 返回查询结果
}
}

@ -1,708 +0,0 @@
package com.farm.core.sql.result;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
/**
* ,
*
* @author 2010 2012-08-17
*/
public class DataResult {
private static final Logger log = Logger.getLogger(DataResult.class);
private long runtime;
/**
*
*/
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
/**
*
*/
private int pageSize = 10;
/**
*
*/
private int currentPage;
/**
*
*/
private int totalSize;
/**
*
*/
private int totalPage;
/**
*
*/
private List<Map<String, Object>> resultList;
/**
*
*/
private List<List<Object>> resultListArray;
/**
*
*/
private Date ctime;
/**
*
*/
private List<String> titles;
private String message;// 页面消息
// 排序字段
private String sortTitleText;
// 排序类型
private String sortTypeText;
// 开始页显示5页
private int startPage;
// 结束页显示5页
private int endPage;
/**
*
*/
private DataResult() {
}
public static DataResult getInstance() {
// 调用重载的getInstance方法传入默认参数返回一个默认的DataResult实例
return getInstance(new ArrayList(), 0, 1, 0);
}
/**
*
*
* @param data
* @param _totalSize
* @param _currentPage
* @param _PageSize
* @return
*/
public static DataResult getInstance(List<Map<String, Object>> data, int _totalSize, int _currentPage,
int _PageSize) {
// 创建DataResult实例
DataResult result = new DataResult();
// 设置记录集合
result.resultList = data;
// 设置总记录数
result.totalSize = _totalSize;
// 设置当前页
result.currentPage = _currentPage;
// 设置每页记录数
result.pageSize = _PageSize;
// 如果总记录数为0则设置总页数、起始页和结束页为0
if (result.totalSize == 0) {
result.totalPage = 0;
result.startPage = 0;
result.endPage = 0;
return result;
}
// 计算总页数
result.totalPage = result.totalSize / result.pageSize + 1;
// 如果总记录数能被每页记录数整除则总页数减1
if (result.totalSize % result.pageSize == 0) {
result.totalPage = result.totalPage - 1;
}
// 计算起始页
result.startPage = result.currentPage - 2;
// 计算结束页
result.endPage = result.currentPage + 2;
// 如果起始页小于1则调整起始页和结束页
if (result.startPage < 1) {
int cha = 1 - result.startPage; // 计算起始页与1的差值
result.startPage = 1; // 设置起始页为1
result.endPage = result.endPage + cha; // 调整结束页
}
// 如果结束页大于总页数,则设置结束页为总页数
if (result.endPage > result.totalPage) {
result.endPage = result.totalPage;
}
// 返回设置好的DataResult实例
return result;
}
/**
* resultListArray
*/
public void LoadListArray() {
resultListArray = new ArrayList<List<Object>>();
for (Map<String, Object> node : this.getResultList()) {
List<Object> list = new ArrayList<Object>();
for (String key : titles) {
list.add(node.get(key));
}
resultListArray.add(list);
}
}
/**
* titleKey + "ROWSPAN"CIDROWSPAN, 0
* n>0 titleKey
*
* @param titleKey
* @return
*/
public DataResult mergeCells(String titleKey) {
String key = titleKey + "ROWSPAN";
for (int i = 0; i < resultList.size(); i++) {
// System.out.println(list.get(i).get("CNAME"));
Object cellsVal = resultList.get(i).get(titleKey);// 合并内容
Object rowspan = resultList.get(i).get(key);// 合并行数
if (rowspan == null) {
// 合并信息放入rowspan中null代表未处理0代表已处理被合并 n>0代表已处理已经合并
int rowspanNum = 0;
for (int n = i; n < resultList.size(); n++) {
Object tempVal = resultList.get(n).get(titleKey);
if (tempVal != null && tempVal.equals(cellsVal)) {
rowspanNum++;
resultList.get(i).put(key, 0);
} else {
break;
}
}
// 设置合并数
resultList.get(i).put(key, rowspanNum);
} else {
continue;
}
}
return this;
}
/**
* resultListArray
*/
public void LoadListArray() {
// 初始化resultListArray为一个新的ArrayList用于存储转换后的列表数据
resultListArray = new ArrayList<List<Object>>();
// 遍历getResultList()返回的Map列表每个Map代表一条记录
for (Map<String, Object> node : this.getResultList()) {
// 为每条记录创建一个新的ArrayList用于存储该记录的值
List<Object> list = new ArrayList<Object>();
// 遍历titles数组titles包含了需要从记录中提取的键名
for (String key : titles) {
// 将每个键对应的值添加到list中
list.add(node.get(key));
}
// 将包含记录值的list添加到resultListArray中
resultListArray.add(list);
}
}
/**
*
*
* @param dataResult
*
* @param messager
*
* @return
*/
public static DataResult setMessager(DataResult dataResult, String messager) {
// 检查传入的dataResult是否为null
if (dataResult == null) {
// 如果为null则创建一个新的DataResult实例
dataResult = new DataResult();
// 并初始化其resultList属性为一个空的ArrayList用于存储查询结果
dataResult.resultList = new ArrayList<Map<String, Object>>();
}
// 设置DataResult的消息属性为传入的messager字符串
dataResult.setMessage(messager);
// 返回设置好消息的DataResult实例
return dataResult;
}
/**
*
*/
public void printDataInfo() {
// 打印调试信息的开始分隔符
System.out.println(
"############ debug开始 #############################################################");
// 调用DataResults类的静态方法printMaps打印当前对象的结果列表
DataResults.printMaps(this.getResultList());
// 打印当前页码
System.out.println("当前页:" + this.getCurrentPage());
// 打印总页数
System.out.println("全部页:" + this.gettotalPage());
// 打印总记录数
System.out.println("全部记录:" + this.getTotalSize());
// 打印每页的记录数
System.out.println("每页数:" + this.getPageSize());
// 打印消息内容
System.out.println("消息:" + this.message);
// 打印调试信息的结束分隔符
System.out.println(
"############ debug结束 #############################################################");
}
/**
*
*
* @param dictionary
* map
* @param title
* TYPE
*/
public DataResult runDictionary(Map<String, String> dictionary, String title) {
for (Map<String, Object> node : resultList) {
String key = String.valueOf(node.get(title));
Object value = dictionary.get(key);
if (value != null) {
node.put(title, value);
}
}
return this;
}
/**
*
*
* @param str
* "1:可用,2:禁用"
* @param title
* TYPE
*/
public DataResult runDictionary(Map<String, String> dictionary, String title) {
// 遍历结果列表中的每个节点
for (Map<String, Object> node : resultList) {
// 从节点中获取标题对应的键值,转换为字符串
String key = String.valueOf(node.get(title));
// 在字典中查找对应的值
Object value = dictionary.get(key);
// 如果在字典中找到了对应的值,则替换节点中的原值
if (value != null) {
node.put(title, value);
}
}
// 返回当前DataResult对象以便链式调用
return this;
}
/**
* yyyyMMddHHmmss
* 201208220408yyyyMMddHHmmss1412
*
* @param title
* TYPE
* @param yyyyMMddHHmmss
*
*/
public void runformatTime(String title, String yyyyMMddHHmmss) {
// 获取查询结果列表
List<Map<String, Object>> list = this.getResultList();
// 遍历结果列表中的每个节点
for (Map<String, Object> node : list) {
try {
String time = null;
// 检查节点中标题对应的值是否为java.sql.Date类型
if (node.get(title) instanceof java.sql.Date) {
// 将java.sql.Date转换为java.util.Date
java.util.Date d = new java.util.Date(((java.sql.Date) node.get(title)).getTime());
// 创建日期格式化对象,格式为"yyyyMMdd"
SimpleDateFormat ormat = new SimpleDateFormat("yyyyMMdd");
// 格式化日期
time = ormat.format(d);
} else {
// 如果不是java.sql.Date类型直接获取字符串值
time = (String) node.get(title);
}
// 如果时间为空或空白字符串,跳过当前循环
if (time == null || time.trim().length() <= 0) {
continue;
}
// 如果时间字符串长度为12表示只有日期和时间到分钟
if (12 == time.length()) {
// 创建原时间格式化对象,格式为"yyyyMMddHHmm"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
// 创建新时间格式化对象格式由参数yyyyMMddHHmmss指定
SimpleDateFormat newSdf = new SimpleDateFormat(yyyyMMddHHmmss);
// 解析原时间字符串为Date对象
Date date = sdf.parse(time);
// 格式化Date对象为新的时间字符串并更新节点中的值
node.put(title, newSdf.format(date));
} else {
// 如果时间字符串长度不为12尝试补全时间字符串到14位
try {
// 补全时间字符串
time = (time + "00000000000000").substring(0, 14);
// 创建原时间格式化对象,格式为"yyyyMMddHHmmss"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
// 创建新时间格式化对象格式由参数yyyyMMddHHmmss指定
SimpleDateFormat newSdf = new SimpleDateFormat(yyyyMMddHHmmss);
// 解析原时间字符串为Date对象
Date date = sdf.parse(time);
// 格式化Date对象为新的时间字符串并更新节点中的值
node.put(title, newSdf.format(date));
} catch (ParseException e) {
// 如果解析失败将节点中的值设置为null
node.put(title, null);
}
}
} catch (Exception e) {
// 捕获并记录异常
log.warn(e);
}
}
}
/**
* (id)
*
* @param result
*
* @param mapTitle
*
* @return
*/
public DataResult removeDataResult(DataResult result, String mapTitle) {
// 创建一个HashSet来存储所有不重复的键值
Set<String> keyset = new HashSet<String>();
// 遍历结果列表,收集所有已有的重复字段
for (Map<String, Object> node : result.getResultList()) {
keyset.add((String) node.get(mapTitle));
}
// 创建一个临时列表来存储需要删除的节点
List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>();
// 遍历当前对象的结果列表
for (Map<String, Object> node : resultList) {
// 获取节点中指定标题的键值
String key = (String) node.get(mapTitle);
// 检查键值是否非空
if (key != null && !"".equals(key)) {
// 尝试将键值添加到keyset中如果添加失败说明键值已存在即重复
if (!keyset.add(key)) {
// 将重复的节点添加到临时列表中
temp.add(node);
// 更新总大小
totalSize = totalSize - 1;
}
}
}
// 遍历临时列表,从结果列表中移除重复的节点
for (Map<String, Object> node : temp) {
resultList.remove(node);
}
// 返回修改后的DataResult对象
return result;
}
/**
*
*
* @param title
* TYPE
* @return
*/
public DataResult runDistinct(String title) {
// 获取当前DataResult对象的结果列表
List<Map<String, Object>> list = this.getResultList();
// 创建一个新的列表,用于存储去重后的结果
List<Map<String, Object>> listresult = new ArrayList<Map<String, Object>>();
// 创建一个HashSet用于存储不重复的键值
Set<String> keySet = new HashSet<String>();
// 遍历原始结果列表
for (Map<String, Object> node : list) {
// 获取每个节点中指定标题的键值,并转换为字符串
String key = node.get(title).toString();
// 尝试将键值添加到keySet中如果添加成功说明键值不重复
if (keySet.add(key)) {
// 将不重复的节点添加到新列表中
listresult.add(node);
}
}
// 将去重后的列表设置回DataResult对象
this.setResultList(listresult);
// 返回当前DataResult对象以便进行链式调用
return this;
}
/**
*
*
* @return
*/
public int getPageSize() {
return pageSize;
}
/**
*
*
* @return
*/
public int getCurrentPage() {
return currentPage;
}
/**
*
*
* @return
*/
public int gettotalPage() {
return totalPage;
}
/**
*
*
* @return
*/
public List<Map<String, Object>> getResultList() {
return resultList;
}
/**
*
*
* @return
*/
public String getMessage() {
return message;
}
/**
*
*
* @param message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
*
* @param resultList
*/
public void setResultList(List<Map<String, Object>> resultList) {
this.resultList = resultList;
}
/**
*
*
* @param titel
*
* @param value
*
*/
public void addTitle(String titel, String value) {
// 遍历结果列表中的每个节点
for (Map<String, Object> node : resultList) {
// 在每个节点中添加一个新的键值对键为titel值为value
node.put(titel, value);
}
// 注意此方法没有返回值它直接修改了当前对象中的resultList
}
/**
* LIst
*
* @return
*/
public List<List<Object>> getResultListArray() {
return resultListArray;
}
/**
* LIst
*
* @param resultListArray
*/
public void setResultListArray(List<List<Object>> resultListArray) {
this.resultListArray = resultListArray;
}
/**
*
*
* @return
*/
public int getTotalSize() {
return totalSize;
}
/**
*
*
* @return
*/
public int getTotalPage() {
return totalPage;
}
/**
*
*
* @return
*/
public List<String> getTitles() {
return titles;
}
/**
*
*
* @param titles
*/
public void setTitles(List<String> titles) {
this.titles = titles;
}
/**
*
*
* @return
*/
public String getSortTitleText() {
return sortTitleText;
}
public void setSortTitleText(String sortTitleText) {
this.sortTitleText = sortTitleText;
}
/**
*
*
* @return
*/
public Date getCtime() {
return ctime;
}
/**
*
*
* @return
*/
public void setCtime(Date ctime) {
this.ctime = ctime;
}
/**
*
*
* @return
*/
public String getSortTypeText() {
return sortTypeText;
}
/**
*
*
* @param sortTypeText
*/
public void setSortTypeText(String sortTypeText) {
this.sortTypeText = sortTypeText;
}
/**
*
*
* @param class1
* @return
*/
@SuppressWarnings("unchecked")
public <T> List<T> getObjectList(@SuppressWarnings("rawtypes") Class class1) {
// 创建一个泛型列表,用于存储转换后的对象
@SuppressWarnings("rawtypes")
List list = new ArrayList<Object>();
// 遍历getResultList()返回的列表每个元素是一个Map代表数据记录
for (Map<String, Object> node : getResultList()) {
Object obj = null;
try {
// 使用传入的class1实例化一个新的对象
obj = class1.newInstance();
// 遍历Map中的每个键值对键是字段名值是字段值
for (Entry<String, Object> field : node.entrySet()) {
// 使用BeanUtils将Map中的键值对设置到新对象的相应属性中
// 注意:这里将键转换为小写,以确保属性名匹配
BeanUtils.setProperty(obj, field.getKey().toLowerCase(), field.getValue());
}
} catch (Exception e) {
// 如果在实例化对象或设置属性时发生异常,抛出运行时异常
throw new RuntimeException(e);
}
// 将填充好的对象添加到列表中
list.add(obj);
}
// 返回包含所有转换对象的列表
return list;
}
public int getStartPage() {
// 返回分页查询的起始页码
return startPage;
}
public void setStartPage(int startPage) {
// 设置分页查询的起始页码
this.startPage = startPage;
}
public int getEndPage() {
// 返回分页查询的结束页码
return endPage;
}
public void setEndPage(int endPage) {
// 设置分页查询的结束页码
this.endPage = endPage;
}
public long getRuntime() {
// 返回查询操作的运行时间
return runtime;
}
public void setRuntime(long runtime) {
// 设置查询操作的运行时间
this.runtime = runtime;
}
public void runHandle(ResultsHandle handle) {
// 遍历结果列表,对每行数据执行处理
for (Map<String, Object> row : this.getResultList()) {
// 调用传入的处理接口,处理当前行数据
handle.handle(row);
}
}
}
}

@ -1,200 +0,0 @@
package com.farm.core.sql.result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
/**
*
*
* @author
*
*/
public class DataResults {
private static final Logger log = Logger.getLogger(DataResults.class);
/**
* setMessageDataResult
*
* @param message
* @return DataResult
*/
public static DataResult setException(DataResult result, Exception e) {
// 检查传入的DataResult对象是否为null如果是则创建一个新的实例
if (result == null) {
result = DataResult.getInstance(
new ArrayList<Map<String, Object>>(), 0, 1, 10);
}
// 检查传入的异常对象e是否为null如果不是则设置DataResult的消息为异常信息
if (e != null) {
// 将异常对象和异常消息拼接后设置为DataResult的消息
result.setMessage(e + e.getMessage());
// 记录错误日志,包括异常信息
log.error(result.getMessage());
}
// 返回设置好的DataResult对象
return result;
}
/**
* hibernaterList<Map<String, Object>>
*
* @param names
* a.id,a.subject,b.rname,a.visit,COUNT(a.id) AS num,
* @param resulresult
* List<Object[]>
* @return
*/
public static List<Map<String, Object>> getMaps(String names,
List<Object[]> t) {
// 检查输入参数names和t是否为null如果是则抛出IllegalArgumentException异常
if (names == null || t == null) {
throw new IllegalArgumentException("参数异常!");
}
// 将中文逗号替换为英文逗号,并将字符串转换为大写
names = names.replace("", ",").toUpperCase();
// 使用逗号分割names字符串得到字符串数组
String[] nameArray = names.split(",");
// 创建一个ArrayList来存储最终的Map列表
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// 获取t的迭代器用于遍历所有的Object数组
for (Iterator<Object[]> iterator = t.iterator(); iterator.hasNext();) {
// 获取下一个Object数组
Object[] objects = (Object[]) iterator.next();
// 创建一个HashMap来存储当前数组的键值对
Map<String, Object> mapresult = new HashMap<String, Object>();
// 获取结果记录字段值的数量
int valueLength = objects.length;
// 如果名称数组的长度小于字段值数量,则使用名称数组的长度
if (nameArray.length < valueLength) {
valueLength = nameArray.length;
}
try {
// 遍历字段值将其填充到Map中
for (int i = 0; i < valueLength; i++) {
// 获取当前字段值
Object value = objects[i];
// 初始化key变量
String key = null;
// 如果names为"*"则使用索引作为key
if (names.trim().equals("*")) {
key = String.valueOf(i);
} else {
// 否则从名称数组中获取key
try {
key = nameArray[i].trim();
// 如果key中包含" AS ",则提取" AS "之后的部分作为新的key
if (key.indexOf(" AS ") >= 0) {
key = key.substring(key.trim().indexOf(" AS ") + 3);
}
// 将key中的点号"."替换为下划线"_"
key = key.replace(".", "_").trim();
} catch (Exception e) {
// 如果在处理key时发生异常记录错误日志
log.error("参数填充错误key和value数量可能不匹配");
}
}
// 将key和value放入mapresult中
mapresult.put(key, value);
}
} catch (Exception e) {
// 如果在填充Map时发生异常记录错误日志
log.error("参数填充错误key和value数量可能不匹配");
}
// 将当前Map添加到列表中
list.add(mapresult);
}
// 返回包含所有Map的列表
return list;
}
/**
*
*
* @param names
* name,type,ctime
* @return
*/
public static List<String> getTitles(String names) {
// 创建一个ArrayList来存储处理后的标题
List<String> list = new ArrayList<String>();
// 检查传入的names是否为null如果是则抛出IllegalArgumentException异常
if (names == null) {
throw new IllegalArgumentException("参数异常!");
}
// 将中文逗号""替换为英文逗号",",并将所有字符转换为大写
names = names.replace("", ",").toUpperCase();
// 使用逗号分隔names字符串得到字符串数组
String[] nameArray = names.split(",");
// 遍历字符串数组
for (String name : nameArray) {
// 初始化key变量
String key = "";
// 去除name两端的空白字符
key = name.trim();
// 检查key中是否包含" AS ",如果包含,则提取" AS "之后的部分作为新的key
if (key.indexOf(" AS ") >= 0) {
key = key.substring(key.trim().indexOf(" AS ") + 3);
}
// 将key中的点号"."替换为下划线"_",并去除两端可能出现的空白字符
key = key.replace(".", "_").trim();
// 将处理后的key添加到列表中
list.add(key);
}
// 返回包含所有处理后的标题的列表
return list;
}
/**
* List<Map<String, Object>>key
*
* @param key
* a.asdf ass as name
* @return A_ASDFNAME
*/
public static String getMapKey(String key) {
// 去除key字符串两端的空白字符
key = key.trim();
// 检查key中是否包含" AS "字符串,如果包含,则提取" AS "之后的部分作为新的key
if (key.indexOf(" AS ") >= 0) {
key = key.substring(key.trim().indexOf(" AS ") + 3);
}
// 将key中的点号"."替换为下划线"_",并去除两端可能出现的空白字符
key = key.replace(".", "_").trim();
// 将key转换为大写字母
return key.toUpperCase();
}
/**
* Maplist
*
* @param listmap
*/
public static void printMaps(List<Map<String, Object>> listmap) {
// 获取listmap的迭代器用于遍历所有的Map对象
for (Iterator<Map<String, Object>> iterator = listmap.iterator(); iterator.hasNext();) {
// 获取下一个Map对象
Map<String, Object> name = (Map<String, Object>) iterator.next();
// 获取Map对象的键集合
Set<String> keyset = name.keySet();
// 获取键集合的迭代器,用于遍历所有的键
for (Iterator<String> iterator2 = keyset.iterator(); iterator2.hasNext();) {
// 获取下一个键
String name2 = (String) iterator2.next();
// 打印键和对应的值
System.out.println(name2 + ":" + name.get(name2));
}
// 打印分隔线用于区分不同的Map对象
System.out.println("------------------------------------------");
}
}

@ -1,18 +0,0 @@
package com.farm.core.sql.result;
import java.util.Map;
/**
*
*
* @author Administrator
*
*/
public interface ResultsHandle {
/**
*
*
* @param row
*/
public void handle(Map<String, Object> row);
}

@ -1,145 +0,0 @@
package com.farm.core.sql.utils;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.persister.entity.AbstractEntityPersister;
import com.farm.core.sql.query.DBRule;
public abstract class HibernateSQLTools<E> {
private AbstractEntityPersister classMetadata;
protected abstract Class<?> getTypeClass();
protected abstract SessionFactory getSessionFactory();
/**
*
*
* @param keyValses
* @return Address = 'Zhongshan 23', City = 'Nanjing'
*/
public static String getValusSqlStr(Map<String, Object> keyValses) {
boolean isFirst = true;
StringBuffer returnStr = new StringBuffer();
for (Entry<String, Object> node : keyValses.entrySet()) {
if (isFirst) {
isFirst = false;
} else {
returnStr.append(",");
}
returnStr.append(node.getKey());
returnStr.append(" = ");
returnStr.append("'");
returnStr.append(node.getValue());
returnStr.append("'");
}
return returnStr.toString();
}
/**
* sql
*
* @param session
* @param rules
*/
public void deleteSqlFromFunction(Session session, List<DBRule> rules) {
classMetadata = (AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass());
String whereStr;
if (rules == null || rules.size() <= 0) {
whereStr = "";
} else {
whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
}
SQLQuery sqlquery = session.createSQLQuery("DELETE FROM " + classMetadata.getTableName() + whereStr);
sqlquery.executeUpdate();
}
/**
* SQL
*
* @param session
* @param rules
* @return
*/
@SuppressWarnings("unchecked")
public List<E> selectSqlFromFunction(Session session, List<DBRule> rules) {
classMetadata = (AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass());
String whereStr;
if (rules == null || rules.size() <= 0) {
whereStr = "";
} else {
whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
}
Query sqlquery = session.createQuery("FROM " + getTypeClass().getName() + whereStr);
List<E> list = sqlquery.list();
return list;
}
@SuppressWarnings("unchecked")
public List<E> selectSqlFromFunction(Session session, List<DBRule> rules, int maxnum) {
classMetadata = (AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass());
String whereStr;
if (rules == null || rules.size() <= 0) {
whereStr = "";
} else {
whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
}
Query sqlquery = session.createQuery("FROM " + getTypeClass().getName() + whereStr);
sqlquery.setMaxResults(maxnum);
List<E> list = sqlquery.list();
return list;
}
/**
* SQL
*
* @param sessionFatory
* @param values
* @param rules
*/
public void updataSqlFromFunction(Session session, Map<String, Object> values, List<DBRule> rules) {
classMetadata = (AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass().getClass());
if (values == null || values.size() <= 0) {
return;
}
String whereStr;
if (rules == null || rules.size() <= 0) {
whereStr = "";
} else {
whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
}
SQLQuery sqlquery = session.createSQLQuery("UPDATE " + classMetadata.getTableName() + " SET "
+ HibernateSQLTools.getValusSqlStr(values) + whereStr);
sqlquery.executeUpdate();
}
/**
* SQL
*
* @param sessionFatory
* @param values
* @param rules
*/
@SuppressWarnings("unchecked")
public int countSqlFromFunction(Session session, List<DBRule> rules) {
classMetadata = (AbstractEntityPersister) getSessionFactory().getClassMetadata(getTypeClass());
String whereStr;
if (rules == null || rules.size() <= 0) {
whereStr = "";
} else {
whereStr = " WHERE 1=1" + DBRule.makeWhereStr(rules);
}
SQLQuery sqlquery = session
.createSQLQuery("select count(*) num FROM " + classMetadata.getTableName() + whereStr);
List<E> list = sqlquery.list();
return Integer.valueOf(list.get(0).toString());
}
}

@ -1,507 +0,0 @@
package com.farm.core.time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class TimeTool {
/**
* 12
*
* @return
*/
public static String getTimeDate12() {
// yyyyMMddhhmm
SimpleDateFormat _sdf = new SimpleDateFormat("yyyyMMddHHmm");
Date _date = new Date();
return _sdf.format(_date);
}
/**
*
*
* @param year
* 4
* @param month
* 2
* @return
*/
public static int getMonthMaxDay(String year, String month) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
if (month.trim().length() == 1) {
month = "0" + month;
}
try {
cal.setTime(sdf.parse(year + month));
} catch (ParseException e) {
throw new RuntimeException();
}
return cal.getActualMaximum(Calendar.DATE);
}
/**
* num
*
* @param num
*
* @return
*/
public static List<String[]> getFirstYearList(int num) {
String currentYear = getTimeDate12().substring(0, 4);
List<String[]> list = new ArrayList<String[]>();
Integer curentYearint = Integer.valueOf(currentYear);
for (int i = 0; i < num; i++) {
String[] yearNode = new String[2];
yearNode[0] = curentYearint.toString();
yearNode[1] = curentYearint.toString() + "年";
list.add(yearNode);
curentYearint--;
}
return list;
}
/**
*
*
* @return
*/
public static List<String[]> getQuarterList() {
List<String[]> list = new ArrayList<String[]>();
String[] node = new String[2];
node[0] = "1";
node[1] = "一季度";
list.add(node);
String[] node2 = new String[2];
node2[0] = "2";
node2[1] = "二季度";
list.add(node2);
String[] node3 = new String[2];
node3[0] = "3";
node3[1] = "三季度";
list.add(node3);
String[] node4 = new String[2];
node4[0] = "4";
node4[1] = "四季度";
list.add(node4);
return list;
}
/**
*
*
* @return
*/
public static List<String[]> getMonthList() {
List<String[]> list = new ArrayList<String[]>();
String[] node = new String[2];
node[0] = "1";
node[1] = "一月";
list.add(node);
String[] node2 = new String[2];
node2[0] = "2";
node2[1] = "二月";
list.add(node2);
String[] node3 = new String[2];
node3[0] = "3";
node3[1] = "三月";
list.add(node3);
String[] node4 = new String[2];
node4[0] = "4";
node4[1] = "四月";
list.add(node4);
String[] node5 = new String[2];
node5[0] = "5";
node5[1] = "五月";
list.add(node5);
String[] node6 = new String[2];
node6[0] = "6";
node6[1] = "六月";
list.add(node6);
String[] node7 = new String[2];
node7[0] = "7";
node7[1] = "七月";
list.add(node7);
String[] node8 = new String[2];
node8[0] = "8";
node8[1] = "八月";
list.add(node8);
String[] node9 = new String[2];
node9[0] = "9";
node9[1] = "九月";
list.add(node9);
String[] node10 = new String[2];
node10[0] = "10";
node10[1] = "十月";
list.add(node10);
String[] node11 = new String[2];
node11[0] = "11";
node11[1] = "十一月";
list.add(node11);
String[] node12 = new String[2];
node12[0] = "12";
node12[1] = "十二月";
list.add(node12);
return list;
}
/**
* 12
*
* @param addday
* + -
* @param currentTime12
* 12
* @return
*/
public static Date getTimeDate12ForDay(int addday, Date date) {
Date _date = null;
_date = date;
return getDateAfter(_date, addday);
}
/**
*
*
* @param frontMinute
* + -
* @return
*/
public static Date getTimeDate12ForMinute(int frontMinute, Date date) {
Date _date = null;
Calendar cal = Calendar.getInstance();// 使用默认时区和语言环境获得一个日历。
cal.setTime(date);
cal.add(Calendar.MINUTE, frontMinute);// 取当前日期的前一天.
_date = cal.getTime();
return _date;
}
/**
* 12
*
* @param timeDate12_14
*
* @param yyyyMMddHHmmss
*
* @return
*/
public static String getFormatTimeDate12(String timeDate12_14,
String yyyyMMddHHmmss) {
try {
if (timeDate12_14.length() > 14) {
timeDate12_14 = timeDate12_14.substring(0, 14);
}
if (12 == timeDate12_14.length()) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
SimpleDateFormat newSdf = new SimpleDateFormat(yyyyMMddHHmmss);
Date date;
date = sdf.parse(timeDate12_14);
return newSdf.format(date);
} else {
if (14 == timeDate12_14.length()) {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyyMMddHHmmss");
SimpleDateFormat newSdf = new SimpleDateFormat(
yyyyMMddHHmmss);
Date date = sdf.parse(timeDate12_14);
return newSdf.format(date);
} else {
return timeDate12_14;
}
}
} catch (ParseException e) {
return e.toString();
}
}
/**
* 14
*/
public static String getTimeDate14() {
/* yyyyMMddhhmmss */
SimpleDateFormat _sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date _date = new Date();
return _sdf.format(_date);
}
/**
* 18
*/
public static String getRandom18() {
// TODO Auto-generated method stub
String _random = UUID.randomUUID().toString();
return _random.substring(0, 18);
}
@SuppressWarnings("static-access")
/**
* 32
*/
public static String getOid() {
String _oid = new TimeTool().getTimeDate14()
+ new TimeTool().getRandom18();
return _oid;
}
/**
*
*
* @param date
*
* @param day
* +-
* @return
*/
private static Date getDateAfter(Date date, int day) {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
/**
*
*
* @return
*/
public static String getCurrentMonth() {
Calendar now = Calendar.getInstance();
now.setTime(new Date());
return String.valueOf(now.get(Calendar.MONTH) + 1);
}
/**
*
*
* @return
*/
public static String getCurrentQuarter() {
Calendar now = Calendar.getInstance();
now.setTime(new Date());
int month = now.get(Calendar.MONTH) + 1;
switch (month) {
case 1:
return "1";
case 2:
return "1";
case 3:
return "1";
case 4:
return "2";
case 5:
return "2";
case 6:
return "2";
case 7:
return "3";
case 8:
return "3";
case 9:
return "3";
case 10:
return "4";
case 11:
return "4";
case 12:
return "4";
default:
break;
}
return "-1";
}
/**
*
*
* @param rankingYear
*
* @param rankingMonth
*
* @return
*/
public static List<String> getDayListByMonth(String rankingYear,
String rankingMonth) {
List<String> list = new ArrayList<String>();
String[] dayStr = { "01", "02", "03", "04", "05", "06", "07", "08",
"09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24", "25", "26", "27", "28",
"29", "30", "31" };
// 如果是1月、3月、5月、7月、8月、10月、12月为31天
if ("1".equals(rankingMonth) || "3".equals(rankingMonth)
|| "5".equals(rankingMonth) || "7".equals(rankingMonth)
|| "8".equals(rankingMonth) || "10".equals(rankingMonth)
|| "12".equals(rankingMonth)) {
for (int i = 0; i < dayStr.length; i++) {
list.add(dayStr[i]);
}
// 如果是4月、6月、9月、11月为30天
} else if ("4".equals(rankingMonth) || "6".equals(rankingMonth)
|| "9".equals(rankingMonth) || "11".equals(rankingMonth)) {
for (int i = 0; i < dayStr.length - 1; i++) {
list.add(dayStr[i]);
}
} else {
int yearInt = Integer.parseInt(rankingYear);
// 判断是平年还是闰年平年2月28天闰年2月29天
if (yearInt % 4 == 0 && yearInt % 100 != 0 || yearInt % 400 == 0) {
for (int i = 0; i < dayStr.length - 2; i++) {
list.add(dayStr[i]);
}
} else {
for (int i = 0; i < dayStr.length - 3; i++) {
list.add(dayStr[i]);
}
}
}
return list;
}
/**
* Date
*
* @param dateBefore
*
* @param dateCurrent
*
* @return
*/
public static int countMinuteMinus(Date dateBefore, Date dateCurrent) {
// 当前时间
Date curentTime = dateCurrent;
// 当前时间
Calendar curentC = Calendar.getInstance();
curentC.setTime(curentTime);
// 上次访问时间
Calendar curentV = Calendar.getInstance();
curentV.setTime(dateBefore);
// 相差分钟数
long timeMillis = (curentC.getTimeInMillis() - curentV
.getTimeInMillis()) / (1000 * 60);
int time = (int) timeMillis;
return time;
}
/**
* Date
*
* @param dateBefore
*
* @param dateCurrent
*
* @return
*/
public static int countDayMinus(Date dateBefore, Date dateCurrent) {
// 当前时间
Date curentTime = dateCurrent;
// 当前时间
Calendar curentC = Calendar.getInstance();
curentC.setTime(curentTime);
// 上次访问时间
Calendar curentV = Calendar.getInstance();
curentV.setTime(dateBefore);
// 相差分钟数
long timeMillis = (curentC.getTimeInMillis() - curentV
.getTimeInMillis()) / (1000 * 60 * 60 * 24);
int time = (int) timeMillis;
return time;
}
/**
*
*
* @param sdate
* @param string
* @return
* @throws ParseException
*/
public static Date parseDate(String dateStr, String yyyyMMdd)
throws ParseException {
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance();
df.applyPattern(yyyyMMdd);
Date ddTest = df.parse(dateStr);
return ddTest;
}
/**
*
*
* @param date
* @param i
* @return
*/
public static Date nextDay(Date date, int i) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 1);
Date date1 = new Date(calendar.getTimeInMillis());
return date1;
}
/**
*
*
* @param date
* @param yyyyMMddHHmmss
* @return
*/
public static String format(Date date, String yyyyMMddHHmmss) {
SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMddHHmmss);
return sdf.format(date);
}
/**
* 0
*
* @param date
* @return
*/
public static int getWeekNum(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return w;
}
/**
*
*
* @param date
* @return
*/
public static int getDayNum(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_MONTH);
if (w < 0) {
w = 0;
}
return w;
}
}

@ -1,5 +0,0 @@
package com.farm.util.cache;
public interface FarmCacheGenerater{
public Object generateData();
}

@ -1,33 +0,0 @@
package com.farm.util.cache;
/**
*
*
* @author macpl
*
*/
public enum FarmCacheName {
//AI问答消息缓存
wcpAiMessages("wcp-ai-messages"),
//AI问答中的用户
wcpAiUserTalking("wcp-ai-talkuser")
;
/**
*
*/
private String permanentCacheName;
FarmCacheName(String permanentCacheName) {
this.permanentCacheName = permanentCacheName;
}
/**
*
*
* @return
*/
public String getPermanentCacheName() {
return permanentCacheName;
}
}

@ -1,44 +0,0 @@
package com.farm.util.cache;
/**
* ()
*
* @author macpl
*
*/
public enum FarmCacheNames {
;
/**
*
*/
private String permanentCacheName;
/**
*
*/
private String liveCacheName;
FarmCacheNames(String permanentCacheName) {
this.permanentCacheName = permanentCacheName;
this.liveCacheName = permanentCacheName + "-live";
}
/**
*
*
* @return
*/
public String getPermanentCacheName() {
return permanentCacheName;
}
/**
*
*
* @return
*/
public String getLiveCacheName() {
return liveCacheName;
}
}

@ -1,431 +0,0 @@
package com.farm.util.cache;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
*
*
* @author wangdong
*
*/
public class FarmCaches {
private static FarmCaches OBJ;
private CacheManager cacheManager;
static final Logger log = Logger.getLogger(FarmCaches.class);
synchronized public static FarmCaches getInstance() {
if (OBJ == null) {
OBJ = new FarmCaches();
OBJ.cacheManager = CacheManager.create(FarmCaches.class.getResource("/config/WcpCacheConfig.xml"));
}
// {// 测试时-屏蔽不需要测试的缓存
// Set<String> wnames = new HashSet<String>();
// wnames.add("app-all-types");
// wnames.add("app-all-typepops");
// wnames.add("app-all-metadocs");
// wnames.add("app-all-metaquestions");
// wnames.add("wcp-all-typenum");
// for (String name : OBJ.cacheManager.getCacheNames()) {
// if (!wnames.contains(name)) {
// OBJ.clearCache(name);
// }
// }
// }
return OBJ;
}
/**
* key
*
* @param currentUserId
* @return
*/
public static String getManyParaToKey(String... paras) {
String key = "";
for (String para : paras) {
if (StringUtils.isBlank(para)) {
para = "NONE";
}
if (StringUtils.isBlank(key)) {
key = para;
} else {
key = key + "-" + para;
}
}
return key;
}
/**
*
*
* @return
*/
public Map<String, Object> getCacheInfo() {
Map<String, Object> map = new HashMap<>();
String[] names = cacheManager.getCacheNames();
if (names != null) {
for (String name : names) {
Cache cache = cacheManager.getCache(name);
if (cache != null) {
map.put(name, cache.getSize());
}
}
}
return map;
}
/**
*
*/
public void clearAllCache() {
String[] names = cacheManager.getCacheNames();
if (names != null) {
for (String name : names) {
clearCache(name);
}
}
}
private void clearCache(String cacheName) {
Cache cache = cacheManager.getCache(cacheName);
if (cache != null) {
cache.removeAll();
}
}
/**
*
*
* @param cacheName
*/
public void clearCache(FarmCacheName farmCacheName) {
clearCache(farmCacheName.getPermanentCacheName());
}
/**
* cache
*
* @param cacheName
* @return
*/
public int getCacheSize(FarmCacheName farmCacheName) {
Cache cache = cacheManager.getCache(farmCacheName.getPermanentCacheName());
if (cache == null) {
throw new RuntimeException("the cache " + farmCacheName.getPermanentCacheName() + " is not exist!");
}
return cache.getSize();
}
/**
*
*
* @param permanentCacheName
* @param liveCacheName
*/
public void clearCache(FarmCacheNames farmCacheName) {
clearCache(farmCacheName.getLiveCacheName());
clearCache(farmCacheName.getPermanentCacheName());
}
/**
* live0
*
* @param farmCacheName
* @return
*/
public boolean isAble(FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0) {
return false;
} else {
return true;
}
}
/**
* live0
*
* @param farmCacheName
* @return
*/
public boolean isAble(FarmCacheNames farmCacheName) {
final Cache permanent = cacheManager.getCache(farmCacheName.getPermanentCacheName());
final Cache live = cacheManager.getCache(farmCacheName.getLiveCacheName());
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
long p_live_time = permanent.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0 || p_live_time == 0) {
return false;
} else {
return true;
}
}
/**
* ()
*
* @param key key
* @param generater
* @param permanentCacheName
* @param liveCacheName
* @return
*/
public Object getCacheData(final String key, final FarmCacheGenerater generater,
final FarmCacheNames farmCacheName) {
long startTime = new Date().getTime();
try {
synchronized (key + farmCacheName.getLiveCacheName()) {
final Cache permanent = cacheManager.getCache(farmCacheName.getPermanentCacheName());
final Cache live = cacheManager.getCache(farmCacheName.getLiveCacheName());
{
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
long p_live_time = permanent.getCacheConfiguration().getTimeToLiveSeconds();
log.debug(farmCacheName.getPermanentCacheName() + ":一级过期时间" + l_live_time);
log.debug(farmCacheName.getPermanentCacheName() + ":一级过期时间" + p_live_time);
if (l_live_time == 0 || p_live_time == 0) {
log.debug("--------------------FarmCache--禁用缓存" + farmCacheName.getPermanentCacheName()
+ " -------------------");
return generater.generateData();
}
}
// 是否是异步加载缓存
final boolean isAsynchronous = true;
// 先从二级里面取,
Element result = null;
result = live.get(key);
// 取到就返回,取不到就从一级里面取
if (result != null) {
log.debug("--------------------FarmCache--:返回(" + key + ")生存数据--------"
+ farmCacheName.getPermanentCacheName() + "/" + farmCacheName.getLiveCacheName()
+ "-------------------");
return result.getObjectValue();
} else {
result = permanent.get(key);
}
if (result != null) {
// ,取到就返回
{// 并且启动一个线程更新二级缓存和一级缓存,
Thread thread = new Thread(new Runnable() {
public void run() {
Object data = generater.generateData();
Element element = new Element(key, data);
permanent.put(element);
live.put(element);
if (isAsynchronous) {
log.debug("--------------------FarmCache--:异步填充(" + key + ")数据--------"
+ farmCacheName.getPermanentCacheName() + "/"
+ farmCacheName.getLiveCacheName() + "-------------------");
} else {
log.debug("--------------------FarmCache--:同步填充(" + key + ")数据--------"
+ farmCacheName.getPermanentCacheName() + "/"
+ farmCacheName.getLiveCacheName() + "-------------------");
}
}
});
if (isAsynchronous) {
thread.start();
} else {
thread.run();
}
}
log.debug("--------------------FarmCache--:返回(" + key + ")过期数据--------"
+ farmCacheName.getPermanentCacheName() + "/" + farmCacheName.getLiveCacheName()
+ "-------------------");
return result.getObjectValue();
} else {
// 取不到就直接更新二级缓存和一级缓存后再返回
Object data = generater.generateData();
Element element = new Element(key, data);
permanent.put(element);
live.put(element);
log.debug("--------------------FarmCache--:返回(" + key + ")实时数据--------"
+ farmCacheName.getPermanentCacheName() + "/" + farmCacheName.getLiveCacheName()
+ "-------------------");
return data;
}
}
} finally {
long endTime = new Date().getTime();
long executeTime = endTime - startTime;
if(executeTime>100) {
log.warn(
"FarmCaches generater runTime:--<" + executeTime + "ms>--" + "--[" + farmCacheName.name() + "] ");
}else {
log.info(
"FarmCaches generater runTime:--<" + executeTime + "ms>--" + "--[" + farmCacheName.name() + "] ");
}
}
}
/**
*
*
* @param key key
* @param generater
* @param CacheName
* @return
*/
public Object getCacheData(String key, FarmCacheGenerater generater, FarmCacheName farmCacheName) {
long startTime = new Date().getTime();
try {
synchronized (key + farmCacheName.getPermanentCacheName()) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
{
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0) {
log.debug("--------------------FarmCache--禁用缓存" + farmCacheName.getPermanentCacheName()
+ " -------------------");
return generater.generateData();
}
}
// 先从二级里面取,
Element result = null;
result = live.get(key);
// 取到就返回,取不到就从一级里面取
if (result != null) {
log.debug("--------------------FarmCache--:返回(" + key + ")生存数据--------"
+ farmCacheName.getPermanentCacheName() + "-------------------");
return result.getObjectValue();
} else {
// 取不到就直接更新二级缓存和一级缓存后再返回
Object data = generater.generateData();
Element element = new Element(key, data);
live.put(element);
log.debug("--------------------FarmCache--:返回(" + key + ")实时数据--------"
+ farmCacheName.getPermanentCacheName() + "-------------------");
return data;
}
}
} finally {
long endTime = new Date().getTime();
long executeTime = endTime - startTime;
if(executeTime>100) {
log.warn(
"FarmCaches generater runTime:--<" + executeTime + "ms>--" + "--[" + farmCacheName.name() + "] ");
}else {
log.info(
"FarmCaches generater runTime:--<" + executeTime + "ms>--" + "--[" + farmCacheName.name() + "] ");
}
}
}
/**
*
*
* @param key
* @param val
* @param CacheName
* @return
*/
public void putCacheData(String key, Object val, FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
{
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0) {
log.info("--------------------FarmCache--禁用缓存" + farmCacheName.getPermanentCacheName()
+ " -------------------");
return;
}
}
Element element = new Element(key, val);
live.put(element);
}
/**
*
*
* @param key
* @param CacheName
* @return
*/
public Object getCacheData(String key, FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
{
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0) {
log.info("--------------------FarmCache--禁用缓存" + farmCacheName.getPermanentCacheName()
+ " -------------------");
return null;
}
}
log.debug("--------------------FarmCache--:返回(" + key + ")生存数据--------" + farmCacheName.getPermanentCacheName()
+ "-------------------");
Element returnVal = live.get(key);
if (returnVal == null) {
return null;
} else {
return returnVal.getObjectValue();
}
}
/**
*
*
* @param key
* @param CacheName
*/
public void removeCacheData(String key, FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
live.remove(key);
}
public void removeCacheData(String key, FarmCacheNames farmCacheName) {
final Cache live1 = cacheManager.getCache(farmCacheName.getPermanentCacheName());
live1.remove(key);
final Cache live2 = cacheManager.getCache(farmCacheName.getLiveCacheName());
live2.remove(key);
}
/**
*
*
* @param sharelevel1cache
* @return
*/
public long getliveTime(FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
return l_live_time;
}
/**
*
*
* @param docId
* @param doctypecache
* @return
*/
public boolean isHaveVal(String key, FarmCacheName farmCacheName) {
final Cache live = cacheManager.getCache(farmCacheName.getPermanentCacheName());
{
// 如果任意缓存的存活时间时0则缓存不生效
long l_live_time = live.getCacheConfiguration().getTimeToLiveSeconds();
if (l_live_time == 0) {
log.info("--------------------FarmCache--禁用缓存" + farmCacheName.getPermanentCacheName()
+ " -------------------");
return false;
}
}
return live.get(key) != null;
}
}

@ -1,34 +0,0 @@
package com.farm.util.spring;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.farm.core.config.AppConfig;
//读取配置文件进行加载
public class BeanFactory {
private static ApplicationContext appContext;
public static Object getBean(String beanId) {
getContext();
return appContext.getBean(beanId);
}
public static ApplicationContext getContext() {
if (appContext == null) {
appContext = new ClassPathXmlApplicationContext(AppConfig
.getString("init.config.spring.configs").split(","));
}
return appContext;
}
public static Object getBean(String beanId, ServletContext servletContext) {
ApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
return ctx.getBean(beanId);
}
}

@ -1,27 +0,0 @@
package com.farm.util.spring;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
* spring hibernateSessionFactory
*
* @author
*
*/
public class HibernateSessionFactory {
private static final SessionFactory sessionf = (SessionFactory) BeanFactory
.getBean("sessionFactory");
public static void closeSession(Session session) {
session.close();
}
public static Session getSession() {
return sessionf.openSession();
}
public static SessionFactory getFactory() {
return sessionf;
}
}

@ -1,8 +0,0 @@
package com.farm.util.validate;
public class ValidUtils {
public static boolean isEmptyString(String str) {
return str == null || str.trim().length() <= 0;
}
}

@ -1,110 +0,0 @@
package com.farm.util.web;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*
* @author Administrator
*
*/
public class FarmFormatUnits {
/**
*
*
* @param fileLength
* b
* @return
*/
public static String getFileLengthAndUnit(int fileLength) {
String unit = "b";
Integer length = fileLength;
if ((Integer) fileLength / 1024 > 0) {
length = (Integer) fileLength / 1024;
unit = "kb";
}
if ((Integer) fileLength / 1024 / 1024 > 0) {
length = (Integer) fileLength / 1024 / 1024;
unit = "mb";
}
return length + unit;
}
/**
* '-'''''
*
* @param timeStr
* @return
*/
public static String getReFormateTime14(String timeStr) {
timeStr = timeStr.replaceAll("-", "").replaceAll(":", "").replaceAll(
" ", "")
+ "00000000000000";
return timeStr.substring(0, 14);
}
/**
*
*
* @param timeStr08_14
* yyyyMMddHHmmss
* @param isshowCurrentDay
*
* @return yyyy-MM-dd HH:mm:ss
*/
public static String getFormateTime(String timeStr08_14,
boolean isshowCurrentDay) {
if (timeStr08_14 == null || timeStr08_14.trim().length() <= 0) {
return null;
}
int tlength = timeStr08_14.length();
timeStr08_14 = timeStr08_14 + "00000000";
String yyyy = timeStr08_14.substring(0, 4);
String MM = timeStr08_14.substring(4, 6);
String dd = timeStr08_14.substring(6, 8);
String HH = timeStr08_14.substring(8, 10);
String mm = timeStr08_14.substring(10, 12);
String ss = timeStr08_14.substring(12, 14);
String returnData = null;
if (tlength == 8 && returnData == null) {
returnData = yyyy + "-" + MM + "-" + dd;
}
if (tlength == 10 && returnData == null) {
returnData = yyyy + "-" + MM + "-" + dd + " " + HH;
}
if (tlength == 12 && returnData == null) {
returnData = yyyy + "-" + MM + "-" + dd + " " + HH + ":" + mm;
}
if (returnData == null) {
returnData = yyyy + "-" + MM + "-" + dd + " " + HH + ":" + mm + ":"
+ ss;
}
SimpleDateFormat _sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentday = _sdf.format(new Date());
return isshowCurrentDay ? returnData.replace(currentday, "今天")
: returnData;
}
/**
*
*
* @param timeStr
* yyyy-MM-dd HH:mm:ss
* @param length
*
* @return yyyyMMddHHmmss
*/
public static String reFormateTime(String timeStr, int length) {
if (timeStr == null || timeStr.trim().length() <= 0) {
return null;
}
timeStr = timeStr.replace(":", "").replace("-", "").replace(" ", "");
if (timeStr.length() > length) {
timeStr = timeStr.substring(0, length);
}
return timeStr;
}
}

@ -1,155 +0,0 @@
package com.farm.util.web;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public class FarmHtmlUtils {
/**
* html
*
* @param input
* @return
*/
public static String escapeHtml(String input) {
input = input.replaceAll("&", "&amp;");
input = input.replaceAll("<", "&lt;");
input = input.replaceAll(">", "&gt;");
input = input.replaceAll("\"", "&quot;");
input = input.replaceAll("'", "&apos;");
return input;
}
/**
* Html
*
* @param inputString
* @return
*/
public static String HtmlRemoveTag(String html, String... tagNames) {
if (html == null) {
return null;
}
String htmlStr = html; // 含html标签的字符串
String textStr = "";
for (String tagName : tagNames) {
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
try {
// }
String regEx_html1 = "<" + tagName + "\\b[^>]*>"; // 定义HTML标签的正则表达式
String regEx_html2 = "</" + tagName + "\\b[^>]*>"; // 定义HTML标签的正则表达式
p_script = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = Pattern.compile(regEx_html2, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
textStr = htmlStr;
} catch (Exception e) {
// System.err.println("Html2Text: " + e.getMessage());
}
}
return textStr;// 返回文本字符串
}
/**
* Html
*
* @param inputString
* @return
*/
public static String HtmlRemoveTag(String html) {
if (html != null) {
// 段落间没有句号分隔的,自动添加句号,方便向量检索时划分段落
html = html.replace("</div>", "。");
html = html.replace("</p>", "。");
html = html.replaceAll("([!。!;]+)\\s*\\。", "$1");
html = html.replaceAll("\\s{2,}", " ");
html = html.replaceAll("<img", "[图片]<img");
}
if (html == null)
return null;
String htmlStr = html; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
// }
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
// }
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
textStr = htmlStr;
} catch (Exception e) {
// System.err.println("Html2Text: " + e.getMessage());
}
return textStr.replaceAll("\\s+", " ");// 返回文本字符串
}
/**
* stylemap
*
* @param style width:100.0%;height:auto;
* @return
*/
public static Map<String, String> parseStyleToMap(String style) {
Map<String, String> css = new HashMap<>();
for (String node : style.split(";")) {
String[] nodeArray = node.split(":");
if (nodeArray.length == 2) {
css.put(nodeArray[0].trim().toLowerCase(), nodeArray[1].trim());
}
}
return css;
}
/**
* stylemapstyle
*
* @param styles
* @return
*/
public static String joinStyleMap(Map<String, String> styles) {
String style = null;
for (Entry<String, String> node : styles.entrySet()) {
if (StringUtils.isNotBlank(node.getKey()) && StringUtils.isNotBlank(node.getValue())) {
if (style == null) {
style = node.getKey() + ":" + node.getValue();
} else {
style = style + node.getKey() + ":" + node.getValue();
}
}
}
return style;
}
}

@ -1,48 +0,0 @@
package com.farm.util.web;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import com.farm.core.time.TimeTool;
/**
* 访
*
* @author Administrator
*
*/
public class FarmproHotnum {
static final Logger log = Logger.getLogger(FarmproHotnum.class);
/**
*
*
* @param date12访yyyyMMddHHmm
* @param hotNum
*
* @param visitNum
* 访1
* @param hotWeight
* 19241001,
* @return
*/
public static int getHotnum(String date12, Integer hotNum,
Integer visitNum, int hotWeight) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
int minuteMinus = 0;
try {
minuteMinus = TimeTool.countMinuteMinus(sdf.parse(date12.substring(
0, 12)), new Date());
} catch (ParseException e) {
log.error(e + e.getMessage());
}
// 本期得分 = 上一期得分 × exp(-(冷却系数) × 间隔的小时数) + 本期本期票数
return Integer.valueOf(String.valueOf(Math.round(hotNum
* Math.exp(-((float) hotWeight / 100) * minuteMinus / 60))))
+ visitNum * 10;
}
}

@ -1,99 +0,0 @@
package com.farm.util.web;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class hotCase {
public String key;
public int num;
public hotCase(String key, int num) {
this.key = key;
this.num = num;
}
}
/**
*
*
* @author Administrator
*
*/
public class WebHotCase {
private static List<hotCase> HOT_CASE = new ArrayList<hotCase>();
private static Map<String, Integer> HOT_CASE_MAP = new HashMap<String, Integer>();
private static int maxNum = 1000;
private static int minNum = 500;
private static int index = 0;
/**
*
*
* @param caseStr
*/
public static void putCase(String caseStr) {
Integer num = HOT_CASE_MAP.get(caseStr);
if (num == null) {
num = 0;
}
index++;
HOT_CASE_MAP.put(caseStr, num + 1);
if (HOT_CASE_MAP.size() >= maxNum || index == 1 || index == 5 || index == 10 || index % 20 == 0) {
clearHotCase();
}
}
/**
* case
*
* @param caseStr
*/
public static List<String> getCases(int num) {
List<String> list = new ArrayList<String>();
for (int n = 0; n < HOT_CASE.size() && n < num; n++) {
list.add(HOT_CASE.get(n).key);
}
return list;
}
/**
* map
*/
private static void clearHotCase() {
// 清空list
HOT_CASE.clear();
// map放入list
for (String key : HOT_CASE_MAP.keySet()) {
int num = HOT_CASE_MAP.get(key);
HOT_CASE.add(new hotCase(key, num));
}
// list排序
Collections.sort(HOT_CASE, new Comparator<hotCase>() {
public int compare(hotCase o1, hotCase o2) {
return o2.num - o1.num;
};
});
// list截串
if (HOT_CASE.size() >= minNum) {
HOT_CASE = HOT_CASE.subList(0, minNum);
}
if (index >= minNum) {
index = minNum;
}
// 装回map
HOT_CASE_MAP.clear();
for (hotCase hc : HOT_CASE) {
int cnum = hc.num;
// 每次清理 热度都会衰减一半
if (cnum > 0) {
cnum = cnum / 2;
}
HOT_CASE_MAP.put(hc.key, cnum);
}
}
}

@ -1,53 +0,0 @@
package com.farm.util.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 访KEY访
*
* @author Administrator
*
*/
public class WebVisitBuff {
private static Map<String, WebVisitBuff> BUFF_S = new HashMap<String, WebVisitBuff>();
private Set<String> pool = new HashSet<String>();
private int max = 0;
/**
*
*
* @param domain
*
* @param maxNum
* Key
* @return
*/
public static WebVisitBuff getInstance(String domain, int maxNum) {
if (BUFF_S.get(domain) == null) {
WebVisitBuff ob = new WebVisitBuff();
BUFF_S.put(domain, ob);
}
BUFF_S.get(domain).max = maxNum;
return BUFF_S.get(domain);
}
/**
* 访访
*
* @return
*/
public boolean canVisite(String key) {
if (pool.size() > max) {
pool.clear();
}
if (pool.contains(key)) {
return false;
} else {
pool.add(key);
return true;
}
}
}

@ -1,244 +0,0 @@
package com.farm.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.time.TimeTool;
import com.farm.util.spring.BeanFactory;
import com.farm.web.constant.FarmConstant;
public class WebUtils {
/**
* Spring
*
* @param beanIndex
* @return
*/
protected Object BEAN(String beanIndex) {
return BeanFactory.getBean(beanIndex);
}
@SuppressWarnings("unchecked")
public List<WebMenu> getCurrentUserMenus(HttpSession session) {
List<WebMenu> menuList = (List<WebMenu>) session
.getAttribute(FarmConstant.SESSION_USERMENU);
return menuList;
}
/**
*
*
* @return
*/
public static LoginUser getCurrentUser(HttpSession session) {
LoginUser user = (LoginUser) session
.getAttribute(FarmConstant.SESSION_USEROBJ);
return user;
}
public LoginUser getCurrentUserByDebug(HttpSession session) {
LoginUser user = new LoginUser() {
@Override
public String getName() {
return "测试";
}
@Override
public String getLoginname() {
return "debug";
}
@Override
public String getId() {
return "debug";
}
};
return user;
}
/**
* 使httpSession
*
* @param user
* @param session
* @return
*/
@SuppressWarnings("unused")
public LoginUser setCurrentUser(LoginUser user, HttpSession session) {
session.setAttribute(FarmConstant.SESSION_USEROBJ, user);
String photoid = null;
if (photoid != null && photoid.trim().length() > 0) {
// if (session == null) {
// getSession().put(AloneConstant.SESSION_USERPHOTO,
// EkpFileFaceImpl.getInstance().getFileUrl(photoid));
// } else {
// session.setAttribute(AloneConstant.SESSION_USERPHOTO,
// EkpFileFaceImpl.getInstance().getFileUrl(photoid));
// }
}
return user;
}
/**
*
*
* @param user
* @return
*/
public void clearCurrentUser(HttpSession session) {
session.setAttribute(FarmConstant.SESSION_USEROBJ, null);
}
/**
* 使httpSession
*
* @param user
* @return
*/
public void setCurrentUserAction(Set<String> userAction, HttpSession session) {
session.setAttribute(FarmConstant.SESSION_USERACTION, userAction);
}
/**
* 使httpSession
*
* @param user
* @return
*/
public void setLoginTime(HttpSession session) {
session.setAttribute(FarmConstant.SESSION_LOGINTIME,
TimeTool.getTimeDate14());
}
/**
*
*/
public String getLoginTime(HttpSession session) {
return (String) session.getAttribute(FarmConstant.SESSION_LOGINTIME);
}
/**
* 使httpSession
*
* @param user
* @return
*/
public void setCurrentUserMenu(List<WebMenu> userMenu, HttpSession session) {
session.setAttribute(FarmConstant.SESSION_USERMENU, userMenu);
}
/**
* httpsessionhttpsessionstrutsSession
*
* @param httpSession
* @return
*/
public HttpSession getSession(HttpSession httpSession) {
return httpSession;
}
/**
* ip
*
* @return
*/
public static String getCurrentIp(HttpServletRequest httpRequest) {
return httpRequest.getRemoteAddr();
}
/**
* 30cookie
*
* @param cookieName
* @param value
*/
public void setCookie(String cookieName, String value,
HttpServletResponse httpResponse) {
Cookie cookie = new Cookie(cookieName, value);
int expireday = 60 * 60 * 24 * 30; // 不设置的话则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
cookie.setMaxAge(expireday);
httpResponse.addCookie(cookie);
}
/**
* cookie
*
* @param cookieName
* @param value
*/
public void delCookie(String cookieName, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
if (cookieName == null || cookieName.equals("")) {
return;
}
Cookie[] cookies = httpRequest.getCookies();
int length = 0;
if (cookies != null && cookies.length > 0) {
length = cookies.length;
for (int i = 0; i < length; i++) {
String cname = cookies[i].getName();
if (cname != null && cname.equals(cookieName)) {
String cValue = cookies[i].getValue();
setCookie(cname, cValue, httpResponse);
} else {
continue;
}
}
}
}
public String getCookieValue(String cookieName,
HttpServletRequest httpRequest) {
if (cookieName == null || cookieName.equals("")) {
return null;
}
Cookie[] cookies = httpRequest.getCookies();
int length = 0;
if (cookies != null && cookies.length > 0) {
length = cookies.length;
for (int i = 0; i < length; i++) {
String cname = cookies[i].getName();
if (cname != null && cname.equals(cookieName)) {
String cValue = cookies[i].getValue();
return cValue;
} else {
continue;
}
}
return null;
} else {
return null;
}
}
/**
* ididlist
*
* @param ids
* @return
*/
public List<String> parseIds(String ids) {
if (ids == null) {
return new ArrayList<String>();
}
ids = ids.replace("", ",");
String[] markdot = ids.split(",");
List<String> list_ = new ArrayList<String>();
for (int i = 0; i < markdot.length; i++) {
String temp = markdot[i];
if (temp != null && !temp.equals("") && !temp.equals(" "))
list_.add(temp);
}
return list_;
}
}

@ -1,193 +0,0 @@
package com.farm.web.action;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import com.farm.core.AuthorityService;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.page.ViewMode;
import com.farm.web.online.OnlineUserOpImpl;
import com.farm.web.online.OnlineUserOpInter;
/**
*
*
* @author MAC_alone
*
*/
public class FarmAction {
private String name;
private String password;
private String autoLogin;
private HttpSession httpSession;
private HttpServletRequest httprequest;
private HttpServletResponse httprespons;
private ViewMode page;
private List<Map<String, Object>> result;
private List<WebMenu> menus;
private String menuId;
private static final Logger log = Logger.getLogger(FarmAction.class);
// /**
// * 用户登录
// *
// * @return
// */
// public void loginCommit(HttpSession session,
// HttpServletResponse httpResponse, HttpServletRequest httpRequest) {
// AuthorityService authAdapter = farmService.getAuthorityService();
// page = ViewMode.getInstance();
// try {
// if (!authAdapter.isLegality(name, password)) {
// page.setError("登录失败:密码错误");
// log.error("登录失败:密码错误");
// return;
// } else {
// }
// } catch (Exception e) {
// page.setError(e.getMessage() + "用户验证失败");
// log.error("登录失败:用户验证失败");
// return;
// }
// try {
// {// 登录成功
// // 开始写入session用户信息
// if (httpSession == null) {
// WebUtils.setCurrentUser(authAdapter.getUserByLoginName(name));
// WebUtils.setLoginTime(session);
// } else {
// WebUtils.setCurrentUser(authAdapter.getUserByLoginName(name),
// httpSession);
// WebUtils.setLoginTime(httpSession);
// }
//
// // 开始写入session用户权限
// if (httpSession == null) {
// WebUtils.setCurrentUserAction(authAdapter
// .getUserAuthKeys(WebUtils.getCurrentUser(session).getId()));
// } else {
// WebUtils.setCurrentUserAction(
// authAdapter.getUserAuthKeys(WebUtils.getCurrentUser(
// httpSession).getId()), httpSession);
// }
// // 开始写入session用户菜单
// if (httpSession == null) {
// WebUtils.setCurrentUserMenu(authAdapter.getUserMenu(WebUtils.getCurrentUser(
// session).getId()));
// } else {
// WebUtils.setCurrentUserMenu(authAdapter.getUserMenu(WebUtils.getCurrentUser(
// httpSession).getId()), httpSession);
// }
// // 写入用户上线信息
// OnlineUserOpInter ouop = null;
// if (httpSession == null) {
// ouop = OnlineUserOpImpl.getInstance(
// WebUtils.getCurrentIp(httpRequest), name, session);
// } else {
// ouop = OnlineUserOpImpl.getInstance(
// httprequest.getRemoteAddr(), name,
// WebUtils.getSession(httpSession));
// }
// ouop.userLoginHandle(authAdapter.getUserByLoginName(name));
// // 记录用户登录时间
// authAdapter.loginHandle(WebUtils.getCurrentUser(httpSession).getId());
// }
// MDC.put("USERID", WebUtils.getCurrentUser(httpSession).getId());
// log.info("登录成功");
// } catch (Exception e) {
// page.setError(e + e.getMessage());
// log.error("登录失败:" + e.getMessage());
// return;
// }
// }
// /**
// * 获得menu
// *
// * @return
// */
// public List<WebMenu> findMenu(HttpSession session) {
// return WebUtils.getCurrentUserMenus(session);
// }
// ----------------------------------------------------------------------------------
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Map<String, Object>> getResult() {
return result;
}
public void setResult(List<Map<String, Object>> result) {
this.result = result;
}
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public HttpSession getHttpSession() {
return httpSession;
}
public void setHttpSession(HttpSession httpSession) {
this.httpSession = httpSession;
}
public String getAutoLogin() {
return autoLogin;
}
public HttpServletRequest getHttprequest() {
return httprequest;
}
public void setHttprequest(HttpServletRequest httprequest) {
this.httprequest = httprequest;
}
public HttpServletResponse getHttprespons() {
return httprespons;
}
public void setHttprespons(HttpServletResponse httprespons) {
this.httprespons = httprespons;
}
public void setAutoLogin(String autoLogin) {
this.autoLogin = autoLogin;
}
public List<WebMenu> getMenus() {
return menus;
}
public void setMenus(List<WebMenu> menus) {
this.menus = menus;
}
}

@ -1,53 +0,0 @@
package com.farm.web.constant;
public class FarmConstant {
/**
* 使
*/
public static final int MENU_TREECODE_UNIT_LENGTH=32;
/**
* SESSION
*/
public static final String SESSION_USEROBJ = "USEROBJ";
/**
* SESSION
*/
public static final String SESSION_USERPHOTO = "USERPHOTO";
/**
* SESSIONURL
*/
public static final String SESSION_GO_URL = "WANTURL";
/**
* SESSIONURL
*/
public static final String SESSION_FROM_URL = "FROMURL";
/**
* SESSION
*/
public static final String SESSION_LOGINTIME = "LOGINTIME";
/**
* SESSION
*/
public static final String SESSION_ORG = "USERORG";
/**
* SESSION
*/
public static final String SESSION_ROLES = "LOGINROLES";
/**
* SESSION
*/
public static final String SESSION_USERACTION = "USERACTION";
/**
* SESSIONList<Map<String, Object>>
* TREECODE,TYPE,URL,ID,IMG,SORT,PARENTID,NAME
*/
public static final String SESSION_USERMENU = "USERMENU";
/**
* licence
*/
public static String LICENCE;
}

@ -1,796 +0,0 @@
package com.farm.web.easyui;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
/**
* easyUI tree
*
* @author
* @date 2013-4-18 [{ "id": 1, "text": "Node 1", "state": "closed", "children":
* @note [{ "id": 11, "text": "Node 11" },{ "id": 12, "text": "Node 12" }] },{
* "id": 2, "text": "Node 2", "state": "closed" }]
*/
public class EasyUiTreeNode implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
static final Logger log = Logger.getLogger(EasyUiTreeNode.class);
private String id;
private String text;
private String state = "open";
private String iconCls;
private String url;
private String para;
private boolean checked;
private List<EasyUiTreeNode> children = new ArrayList<EasyUiTreeNode>();
public EasyUiTreeNode(String id, String text) {
this.id = id;
this.text = text;
}
public EasyUiTreeNode(String id, String text, String state) {
this.id = id;
this.text = text;
if (state != null) {
this.state = state;
}
}
public EasyUiTreeNode(String id, String text, String state, String iconCls) {
this.id = id;
this.text = text;
if (state != null) {
this.state = state;
}
if (iconCls != null && iconCls.trim().length() > 0) {
this.iconCls = iconCls;
}
}
public EasyUiTreeNode(String id, String text, String state, String iconCls,
String url, String params) {
this.id = id;
this.text = text;
if (state != null) {
this.state = state;
}
if (url != null) {
this.url = url;
}
if (params != null) {
this.para = params;
}
if (iconCls != null && iconCls.trim().length() > 0) {
this.iconCls = iconCls;
}
}
public EasyUiTreeNode(String id, String text, String state, boolean checked) {
this.id = id;
this.text = text;
if (state != null) {
this.state = state;
}
this.checked = checked;
}
/**
* ()
*
* @param nodeList
*
* @param parentId
* id
* @param id
* id
* @param text
*
* @param state
* 'open' 'closed'
*/
public static List<EasyUiTreeNode> addNode_initState(
List<EasyUiTreeNode> nodeList, String parentId, String id,
String text, String state, String icon, String url, String params) {
if (nodeList == null) {
nodeList = new ArrayList<EasyUiTreeNode>();
}
EasyUiTreeNode oNode = findNode(nodeList, parentId);
if (oNode == null) {
nodeList
.add(new EasyUiTreeNode(id, text, state, icon, url, params));
} else {
oNode.setState("closed");
}
return nodeList;
}
/**
* ()
*
* @param nodeList
*
* @param parentId
* id
* @param id
* id
* @param text
*
* @param state
* 'open' 'closed'
*/
public static List<EasyUiTreeNode> addNode_Standard(
List<EasyUiTreeNode> nodeList, String parentId, String id,
String text, String state) {
if (nodeList == null) {
nodeList = new ArrayList<EasyUiTreeNode>();
}
EasyUiTreeNode oNode = findNode(nodeList, parentId);
if (oNode == null) {
nodeList.add(new EasyUiTreeNode(id, text, state));
} else {
oNode.getChildren().add(new EasyUiTreeNode(id, text, state));
}
return nodeList;
}
public static List<EasyUiTreeNode> addNode_Standard(
List<EasyUiTreeNode> nodeList, String parentId, String id,
String text, String state, boolean idcheck) {
if (nodeList == null) {
nodeList = new ArrayList<EasyUiTreeNode>();
}
EasyUiTreeNode oNode = findNode(nodeList, parentId);
if (oNode == null) {
nodeList.add(new EasyUiTreeNode(id, text, state, idcheck));
} else {
oNode.getChildren().add(
new EasyUiTreeNode(id, text, state, idcheck));
oNode.setChecked(false);
}
return nodeList;
}
public static List<EasyUiTreeNode> addNode_Standard(
List<EasyUiTreeNode> nodeList, String parentId, String id,
String text, String state, boolean idcheck, String icon) {
if (nodeList == null) {
nodeList = new ArrayList<EasyUiTreeNode>();
}
EasyUiTreeNode oNode = findNode(nodeList, parentId);
if (oNode == null) {
EasyUiTreeNode node = new EasyUiTreeNode(id, text, state, idcheck);
if (icon != null) {
node.setIconCls(icon);
}
nodeList.add(node);
} else {
EasyUiTreeNode node = new EasyUiTreeNode(id, text, state, idcheck);
if (icon != null) {
node.setIconCls(icon);
}
oNode.getChildren().add(node);
oNode.setChecked(false);
}
return nodeList;
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAsyncAjaxTree(
List<Map<String, Object>> result1,
List<Map<String, Object>> result2, String parentIdIndex,
String idIndex, String titleIndex, String iconIndex) {
result1.addAll(result2);
List<EasyUiTreeNode> treeNodes = new ArrayList<EasyUiTreeNode>();
try {
for (Map<String, Object> node : result1) {
if (node.get(idIndex) == null) {
continue;
}
treeNodes = EasyUiTreeNode.addNode_initState(treeNodes, node
.get(parentIdIndex).toString(), node.get(idIndex)
.toString(), node.get(titleIndex).toString(), null,
node.get(iconIndex) != null ? node.get(iconIndex)
.toString() : null, null, null);
}
} catch (Exception e) {
log.error(e.getMessage());;
}
return treeNodes;
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @param iconIndex
* key
* @param urlIndex
* urlkey
* @param paramsIndex
* urlkey
* @param currentUserMenus
*
* @return
*/
public static List<EasyUiTreeNode> formatAsyncAjaxTreeForMenuTree(
List<Map<String, Object>> result1,
List<Map<String, Object>> result2, String parentIdIndex,
String idIndex, String titleIndex, String iconIndex,
String urlIndex, String paramsIndex,
List<WebMenu> currentUserMenus) {
result1.addAll(result2);
List<EasyUiTreeNode> treeNodes = new ArrayList<EasyUiTreeNode>();
try {
for (Map<String, Object> node : result1) {
boolean isShowMenu = false;
for (WebMenu menu : currentUserMenus) {
if (menu.getId().equals(node.get(idIndex))) {
isShowMenu = true;
break;
}
}
if (!isShowMenu) {
continue;
}
treeNodes = EasyUiTreeNode.addNode_initState(treeNodes, node
.get(parentIdIndex).toString(), node.get(idIndex)
.toString(), node.get(titleIndex).toString(), null,
node.get(iconIndex) != null ? node.get(iconIndex)
.toString() : null,
node.get(urlIndex) != null ? node.get(urlIndex)
.toString() : null,
node.get(paramsIndex) != null ? node.get(paramsIndex)
.toString() : null);
}
} catch (Exception e) {
log.error(e.getMessage());;
}
return treeNodes;
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAjaxTree(
List<Map<String, Object>> result1, String parentIdIndex,
String idIndex, String titleIndex) {
List<EasyUiTreeNode> treeNodes = new ArrayList<EasyUiTreeNode>();
try {
for (Map<String, Object> node : result1) {
if (node.get(idIndex) == null) {
continue;
}
treeNodes = EasyUiTreeNode.addNode_Standard(treeNodes, node
.get(parentIdIndex).toString(), node.get(idIndex)
.toString(), node.get(titleIndex).toString(), null);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return treeNodes;
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @param checkIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAjaxTree(
List<Map<String, Object>> result1, String parentIdIndex,
String idIndex, String titleIndex, String checkIndex,
String iconIndex) {
List<EasyUiTreeNode> treeNodes = new ArrayList<EasyUiTreeNode>();
try {
for (Map<String, Object> node : result1) {
if (node.get(idIndex) == null) {
continue;
}
boolean ischeck = false;
if (node.get(checkIndex) == null) {
ischeck = false;
} else {
ischeck = true;
}
treeNodes = EasyUiTreeNode.addNode_Standard(treeNodes, node
.get(parentIdIndex).toString(), node.get(idIndex)
.toString(), node.get(titleIndex).toString(), null,
ischeck, node.get(iconIndex) == null ? null : node.get(
iconIndex).toString());
}
} catch (Exception e) {
log.error(e.getMessage());;
}
return treeNodes;
}
/**
*
*
* @param nodeList
* @return
*/
public static EasyUiTreeNode findNode(List<EasyUiTreeNode> nodeList,
String id) {
for (EasyUiTreeNode node : nodeList) {
if (node.id.equals(id)) {
return node;
} else {
EasyUiTreeNode reNode = findNode(node.children, id);
if (reNode != null) {
return reNode;
}
}
}
return null;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPara() {
return para;
}
public void setPara(String para) {
this.para = para;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void setText(String text) {
this.text = text;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public List<EasyUiTreeNode> getChildren() {
return children;
}
public void setChildren(List<EasyUiTreeNode> children) {
this.children = children;
}
public String getIconCls() {
return iconCls;
}
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @return DataResult
*/
public static DataResult queryTreeNodeTow(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title) {
return queryTreeNodeTow(parentId, SortTitle, tableTitle, id_title,
parentId_title, name_title, icon_title, null);
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param userWhere
* @return
*/
public static DataResult queryTreeNodeTow(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title,
String userWhere) {
if (parentId == null || parentId.trim().length() <= 0) {
parentId = "NONE";
}
DataResult nodeResult = null;
DBSort sort = new DBSort("b." + SortTitle, "ASC");
DataQuery query = DataQuery.getInstance("1", "b." + id_title + " as "
+ id_title + ",b." + parentId_title + " as " + parentId_title
+ ",b." + name_title + " as " + name_title + ",b." + icon_title
+ " as " + icon_title, tableTitle + " a left join "
+ tableTitle + " b on b." + parentId_title + "=a." + id_title);
query.setPagesize(100);
query.addSort(sort);
DataQuerys.wipeVirus(parentId);
if (userWhere != null) {
query.setSqlRule("and a." + parentId_title + "='" + parentId + "' "
+ userWhere);
} else {
query
.setSqlRule("and a." + parentId_title + "='" + parentId
+ "' ");
}
try {
nodeResult = query.search();
} catch (SQLException e) {
log.error(e.getMessage());;
}
return nodeResult;
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param icon_title
*
* @return DataResult
*/
public static DataResult queryTreeNodeOne(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title) {
return queryTreeNodeOne(parentId, SortTitle, tableTitle, id_title,
parentId_title, name_title, icon_title, null, null);
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param icon_title
*
* @param userWhere
*
* @return DataResult
*/
public static DataResult queryTreeNodeOne(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title,
String userWhere) {
return queryTreeNodeOne(parentId, SortTitle, tableTitle, id_title,
parentId_title, name_title, icon_title, userWhere, null);
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param userWhere
* @return
*/
public static DataResult queryTreeNodeOne(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title,
String userWhere, String otherTitles) {
if (parentId == null || parentId.trim().length() <= 0) {
parentId = "NONE";
}
DataResult nodeResult = null;
DBSort sort = new DBSort("a." + SortTitle, "ASC");
DataQuery query = DataQuery.getInstance("1", (otherTitles == null ? ""
: (otherTitles + ","))
+ id_title
+ ","
+ parentId_title
+ " as "
+ parentId_title
+ ","
+ name_title
+ " as "
+ name_title
+ ",a."
+ icon_title
+ " as " + icon_title, tableTitle + " a");
query.setPagesize(100);
query.addSort(sort);
DataQuerys.wipeVirus(parentId);
if (userWhere != null) {
query.setSqlRule("and " + parentId_title + "='" + parentId + "' "
+ userWhere);
} else {
query.setSqlRule("and " + parentId_title + "='" + parentId + "'");
}
try {
nodeResult = query.search();
} catch (SQLException e) {
log.error(e.getMessage());;
}
return nodeResult;
}
/**
* easyUi
*
* @param resultList
* List<Map<String, Object>>
* @param resultList
* @param parentIndex
* @param idIndex
* @param titleIndex
* @param iconIndex
* @return
*/
public static List<EasyUiTreeNode> formatTreeNodes(
List<Map<String, Object>> resultList, String parentIndex,
String idIndex, String titleIndex, String iconIndex) {
List<EasyUiTreeNode> treeNodes = new ArrayList<EasyUiTreeNode>();
try {
for (Map<String, Object> node : resultList) {
if (node.get(idIndex) == null) {
continue;
}
treeNodes = EasyUiTreeNode.addNode_initState(treeNodes, node
.get(parentIndex).toString(), node.get(idIndex)
.toString(), node.get(titleIndex).toString(), null,
node.get(iconIndex) != null ? node.get(iconIndex)
.toString() : null, null, null);
}
} catch (Exception e) {
log.error(e.getMessage());;
}
return treeNodes;
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param userWhere
* @return
*/
public static DataQuery queryTreeNodeOneAuth(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title,
String userWhere, String otherTitles,boolean authFlag) {
if (parentId == null || parentId.trim().length() <= 0) {
parentId = "NONE";
}
@SuppressWarnings("unused")
DataResult nodeResult = null;
DBSort sort = new DBSort("a." + SortTitle, "ASC");
DataQuery query = DataQuery.getInstance("1", (otherTitles == null ? ""
: (otherTitles + ","))
+ id_title
+ ","
+ parentId_title
+ " as "
+ parentId_title
+ ","
+ name_title
+ " as "
+ name_title
+ ",a."
+ icon_title
+ " as " + icon_title, tableTitle + " a");
query.setPagesize(100);
query.addSort(sort);
DataQuerys.wipeVirus(parentId);
if(authFlag)
{
query.setSqlRule("and a." + parentId_title + " is not null");
query.setSqlRule("and " + parentId_title + "='" + parentId + "'");
}
else
{
if (userWhere != null) {
query.setSqlRule("and " + parentId_title + "='" + parentId + "' "
+ userWhere);
} else {
query.setSqlRule("and " + parentId_title + "='" + parentId + "'");
}
}
return query;
}
/**
* id"NONE",ID,PARENTID,NAME
*
* @param parentId
* id
* @param SortTitle
* index
* @param tableTitle
* index
* @param id_title
* idindex
* @param parentId_title
* parentidindex
* @param name_title
* nameindex
* @param userWhere
* @return
*/
public static DataQuery queryTreeNodeTowAuth(String parentId,
String SortTitle, String tableTitle, String id_title,
String parentId_title, String name_title, String icon_title,
String userWhere,boolean authFlag) {
if (parentId == null || parentId.trim().length() <= 0) {
parentId = "NONE";
}
@SuppressWarnings("unused")
DataResult nodeResult = null;
DBSort sort = new DBSort("b." + SortTitle, "ASC");
DataQuery query = DataQuery.getInstance("1", "b." + id_title + " as "
+ id_title + ",b." + parentId_title + " as " + parentId_title
+ ",b." + name_title + " as " + name_title + ",b." + icon_title
+ " as " + icon_title, tableTitle + " a left join "
+ tableTitle + " b on b." + parentId_title + "=a." + id_title);
query.setPagesize(100);
query.addSort(sort);
DataQuerys.wipeVirus(parentId);
if(authFlag)
{
query.setSqlRule("and a." + parentId_title + " is not null");
query.setSqlRule("and a." + parentId_title + "='" + parentId
+ "' ");
}
else
{
if (userWhere != null) {
query.setSqlRule("and a." + parentId_title + "='" + parentId + "' "
+ userWhere);
} else {
query.setSqlRule("and a." + parentId_title + "='" + parentId
+ "' ");
}
}
return query;
}
}

@ -1,227 +0,0 @@
package com.farm.web.easyui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
/**
* UI
*
* @author
* @date 2013-4-28
*/
public class EasyUiUtils {
/**
* 1
*/
private static String EDITOR_TYPE_TEXT = "text";
/**
* 2
*/
private static String EDITOR_TYPE_SELECT = "numberbox";
/**
* 3
*/
@SuppressWarnings("unused")
private static String EDITOR_TYPE_CHECKBOX = "{ \"type\":\"checkbox\", \"options\":{\"on\":true,\"off\":false} }";
/**
* 4 { "type":"checkbox", "options":{"on":true,"off":false} }
*/
@SuppressWarnings("unused")
private static String EDITOR_TYPE_NUMBERBOX = "numberbox";
public static Map<String, Object> formatGridData(DataResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", result.getTotalSize());
map.put("rows", result.getResultList());
return map;
}
/**
* propertyGridjson 1 2 3 4 rules
*
* @param list
* list
* @param nameIndex
* @param valueIndex
* @param GroupIndex
* @param editorType
* @return
*/
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> formatPropertygridData(
List<Map<String, Object>> list, String nameIndex,
String valueIndex, String GroupIndex, String editorType,
String ruleIndex, String idIndex) {
// [{"name":"Name","value":"Bill Smith","group":"ID Settings","editor":"text"}]
List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
for (@SuppressWarnings("rawtypes")
Iterator iterator = list.iterator(); iterator.hasNext();) {
Map<String, Object> map = (Map<String, Object>) iterator.next();
Map<String, Object> easyMap = new HashMap<String, Object>();
easyMap.put("name", map.get(nameIndex).toString());
easyMap.put("value", map.get(valueIndex).toString());
easyMap.put("group", map.get(GroupIndex).toString());
easyMap.put("id", map.get(idIndex).toString());
// 1是文本2是枚举
Object editor = EDITOR_TYPE_TEXT;
if ("2".equals(map.get(editorType).toString())) {
editor = EDITOR_TYPE_SELECT;
}
if ("3".equals(map.get(editorType).toString())) {
if(map.get(ruleIndex)!=null){
editor = getComboboxOptions(map.get(ruleIndex).toString());
}
}
if ("4".equals(map.get(editorType).toString())) {
Map<String, Object> type = new HashMap<String, Object>();
type.put("type", "checkbox");
Map<String, Object> type2 = new HashMap<String, Object>();
type2.put("on", true);
type2.put("off", false);
type.put("options", type2);
editor = type;
// { "type":"checkbox", "options":{"on":true,"off":false} }
}
easyMap.put("editor", editor);
returnList.add(easyMap);
}
return returnList;
}
/**
* propertyGridJSON
*
* @param Rules
*
* @return
*/
private static Map<String, Object> getComboboxOptions(String Rules) {
// "editor":{
// "type":"combobox",
// "options":{
// "data":[{"value":1,"text":"一"},{"value":2,"text":"二"}],
// "panelHeight":"auto"
// }
Map<String, Object> map1 = new HashMap<String, Object>();
// ---------------------------------------
String[] ruleArray = Rules.split(",");
List<Map<String, Object>> ruleList = new ArrayList<Map<String, Object>>();
for (int i = 0; i < ruleArray.length; i++) {
Map<String, Object> nodeMap = new HashMap<String, Object>();
nodeMap.put("value", ruleArray[i]);
nodeMap.put("text", ruleArray[i]);
ruleList.add(nodeMap);
}
Map<String, Object> mapOptions = new HashMap<String, Object>();
mapOptions.put("data", ruleList);
mapOptions.put("panelHeight", "auto");
map1.put("type", "combobox");
map1.put("options", mapOptions);
return map1;
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @param checkIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAjaxTree(
List<Map<String, Object>> result1, String parentIdIndex,
String idIndex, String titleIndex, String checkIndex) {
return EasyUiTreeNode.formatAjaxTree(result1, parentIdIndex, idIndex,
titleIndex, checkIndex, null);
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAjaxTree(
List<Map<String, Object>> result1, String parentIdIndex,
String idIndex, String titleIndex) {
return EasyUiTreeNode.formatAjaxTree(result1, parentIdIndex, idIndex,
titleIndex);
}
/**
* ajax
*
* @param result1
* id
* @param result2
* id
* @param parentIdIndex
* idkey
* @param idIndex
* idkey
* @param titleIndex
* key
* @return
*/
public static List<EasyUiTreeNode> formatAsyncAjaxTree(
List<Map<String, Object>> result1,
List<Map<String, Object>> result2, String parentIdIndex,
String idIndex, String titleIndex, String imgIndex) {
return EasyUiTreeNode.formatAsyncAjaxTree(result1, result2,
parentIdIndex, idIndex, titleIndex, imgIndex);
}
/**
* grid
*
* @param request
* @param query
* @return
*/
public static DataQuery formatGridQuery(HttpServletRequest request,
DataQuery query) {
// page=1&rows=10&sort=TITLE&order=asc
if (query == null) {
query = new DataQuery();
}
if (request.getParameter("page") != null) {
query.setCurrentPage(request.getParameter("page").toString());
}
if (request.getParameter("rows") != null) {
query.setPagesize(Integer.valueOf(request.getParameter("rows")));
}
if (request.getParameter("sort") != null) {
query.addSort(new DBSort(request.getParameter("sort"), request
.getParameter("order")));
}
return query;
}
}

@ -1,44 +0,0 @@
package com.farm.web.local;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class ConfDirHandle {
/**
*
*
* @param strPath
*
* @param index
*
* @param handle
* @param context
*/
public static void findDirForConf(String strPath, String[] indexs,
ConfHandleInter handle, Object context) {
try {
strPath=URLDecoder.decode(strPath,"utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("ERROR:配置文件夹路径,解析错误");
}
File dir = new File(strPath);
File[] files = dir.listFiles();
if (files == null)
return;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
findDirForConf(files[i].getAbsolutePath(), indexs, handle,
context);
} else {
String strFileName = files[i].getAbsolutePath().toLowerCase();
for (String index : indexs) {
if (strFileName.replace("\\", ".").replace("/", ".")
.indexOf(index) >= 0) {
handle.execute(context, files[i]);
}
}
}
}
}
}

@ -1,7 +0,0 @@
package com.farm.web.local;
import java.io.File;
public interface ConfHandleInter {
public void execute(Object para,File file);
}

@ -1,212 +0,0 @@
package com.farm.web.online;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.farm.core.sql.result.DataResult;
import com.farm.web.constant.FarmConstant;
/**
* 线 userLoginHandle()
* userVisitHandle()访
*
* @author wangdong
*
*/
public class OnlineUserOpImpl implements OnlineUserOpInter {
/**
* ip
*/
private String ip;
private String loginName;
private HttpSession httpSession;
private Map<String, Object> strutsSession;
@Override
public boolean doUserDownLine(String loginName) {
OnlineUserOpInter.onlineUserTable.remove(loginName);
return true;
}
@Override
public DataResult findOnlineUser() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (String key : OnlineUserOpInter.onlineUserTable.keySet()) {
// 处理时间----开始
// 上次访问时间
Date date = (Date) OnlineUserOpInter.onlineUserTable.get(key).get(
OnlineUserOpInter.key_TIME);
// 登录时间
Date visitdate = (Date) OnlineUserOpInter.onlineUserTable.get(key)
.get(OnlineUserOpInter.key_LOGINTIME);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat curentDayf = new SimpleDateFormat("yyyy-MM-dd");
// 当前时间
Date curentTime = new Date();
// 当前时间
Calendar curentC = Calendar.getInstance();
curentC.setTime(curentTime);
// 上次访问时间
Calendar curentV = Calendar.getInstance();
curentV.setTime(date);
// 登录时间
Calendar curentl = Calendar.getInstance();
curentl.setTime(visitdate);
// 相差分钟数
long timeMillis = (curentC.getTimeInMillis() - curentV
.getTimeInMillis())
/ (1000 * 60);
// 登录时长
long visitMillis = (curentC.getTimeInMillis() - curentl
.getTimeInMillis())
/ (1000 * 60);
if (timeMillis > OnlineUserOpInter.onlineVilaMinute) {
// 超时用户判为不在线
OnlineUserOpInter.onlineUserTable.remove(key);
continue;
}
// 处理时间----结束
Map<String, Object> map = new HashMap<String, Object>();
map.put(OnlineUserOpInter.key_LNAME, key);
map.put(OnlineUserOpInter.key_VISITTIME, visitMillis);
map.put(OnlineUserOpInter.key_TIME, sdf.format(date).replace(
curentDayf.format(new Date()), "今天"));
map.put(OnlineUserOpInter.key_USEROBJ,
OnlineUserOpInter.onlineUserTable.get(key).get(
OnlineUserOpInter.key_USEROBJ));
map.put(OnlineUserOpInter.key_LOGINTIME, sdf
.format(OnlineUserOpInter.onlineUserTable.get(key).get(
OnlineUserOpInter.key_LOGINTIME)).replace(
curentDayf.format(new Date()), "今天"));
map.put(OnlineUserOpInter.key_IP, OnlineUserOpInter.onlineUserTable
.get(key).get(OnlineUserOpInter.key_IP));
list.add(map);
}
DataResult result = DataResult.getInstance(list, list.size(), 1, list
.size());
return result;
}
@Override
public void userLoginHandle(Object user) {
if (!((httpSession == null && strutsSession == null)
|| loginName == null || ip == null)) {
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put(OnlineUserOpInter.key_IP, ip);
userMap.put(OnlineUserOpInter.key_TIME, new Date());
userMap.put(OnlineUserOpInter.key_LNAME, loginName);
userMap.put(OnlineUserOpInter.key_LOGINTIME, new Date());
userMap.put(OnlineUserOpInter.key_USEROBJ, user);
// 将用户注册在在线表中
OnlineUserOpInter.onlineUserTable.put(loginName, userMap);
} else {
throw new RuntimeException("参数错误");
}
}
@Override
public void userVisitHandle() {
// 用户没有在在线表中就将用户注销
if (!((httpSession == null && strutsSession == null)
|| loginName == null || ip == null)) {
Map<String, Object> userMap = OnlineUserOpInter.onlineUserTable
.get(loginName);
if (userMap == null) {
// 没有在线
clearSessionUser();
return;
} else {
userMap.put(OnlineUserOpInter.key_TIME, new Date());
if (!userMap.get(OnlineUserOpInter.key_IP).equals(ip)) {
// 用户ip不匹配
clearSessionUser();
return;
} else {
// 没有问题,用户是在线不处理
}
}
} else {
throw new RuntimeException("参数错误");
}
}
// ----------private------------------------------------------------
private void clearSessionUser() {
if (this.httpSession != null) {
httpSession.removeAttribute(FarmConstant.SESSION_USEROBJ);
}
if (this.strutsSession != null) {
strutsSession.put(FarmConstant.SESSION_USEROBJ, null);
strutsSession.clear();
}
}
// ----------get/set------------------------------------------------
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public HttpSession getHttpSession() {
return httpSession;
}
public void setHttpSession(HttpSession httpSession) {
this.httpSession = httpSession;
}
public Map<String, Object> getStrutsSession() {
return strutsSession;
}
public void setStrutsSession(Map<String, Object> strutsSession) {
this.strutsSession = strutsSession;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
// --------------------------------------构造方法
public static OnlineUserOpInter getInstance(String ip, String loginName,
HttpSession httpSession) {
OnlineUserOpImpl obj = new OnlineUserOpImpl();
obj.setHttpSession(httpSession);
obj.setLoginName(loginName);
obj.setIp(ip);
return obj;
}
public static OnlineUserOpInter getInstance(String ip, String loginName,
Map<String, Object> strutsSession) {
OnlineUserOpImpl obj = new OnlineUserOpImpl();
obj.setIp(ip);
obj.setLoginName(loginName);
obj.setStrutsSession(strutsSession);
return obj;
}
public static OnlineUserOpInter getInstance() {
OnlineUserOpImpl obj = new OnlineUserOpImpl();
return obj;
}
}

@ -1,86 +0,0 @@
package com.farm.web.online;
import java.util.HashMap;
import java.util.Map;
import com.farm.core.sql.result.DataResult;
/**
* 线 userLoginHandle()
* userVisitHandle()访
*
* @author wangdong
* @date 2012-03-01
*/
public interface OnlineUserOpInter {
/**
* 线
*/
static final Map<String, Map<String, Object>> onlineUserTable = new HashMap<String, Map<String, Object>>();
/**
* 访
*/
static final String key_TIME = "TIME";
/**
* IP
*/
static final String key_IP = "IP";
/**
* loginName
*/
static final String key_LNAME = "LNAME";
/**
*
*/
static final String key_USEROBJ = "USEROBJ";
/**
*
*/
static final String key_LOGINTIME = "LOGINTIME";
/**
*
*/
static final String key_VISITTIME = "VISITTIME";
/**
* 线
*/
static final long onlineVilaMinute = 60;
/**
* 访handle 线线(session)
*
* @param strutsSession
* STRUTSsession
* @param ip
* ip
*/
public void userVisitHandle();
/**
* 线 线
*
* @param httpSession
* session
* @param ip
* ip
*/
public void userLoginHandle(Object user);
/**
* 线
*
* @return
*/
public DataResult findOnlineUser();
/**
* 线
*
* @param loginName
* @return
*/
public boolean doUserDownLine(String loginName);
}

@ -1,17 +0,0 @@
package com.farm.web.task;
import javax.servlet.ServletContext;
/**
*
*
* @author
*
*/
public interface ServletInitJobInter {
/**
* @param context
*/
public void execute(ServletContext context);
}

@ -1,51 +0,0 @@
package com.farm.web.task;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import com.farm.util.spring.BeanFactory;
public class SysInit extends HttpServlet {
/**
*
*/
private static List<ServletInitJobInter> list = new ArrayList<ServletInitJobInter>();
private static final long serialVersionUID = 1L;
// 配置系统所有默认启动任务
public SysInit() {
super();
}
private final Logger log = Logger.getLogger(this.getClass());
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
list = ((TaskListInter) BeanFactory.getBean("startServerTasksId", getServletContext())).getTasks();
log.info("--系统准备运行" + list.size() + "项");
if (list == null) {
list = new ArrayList<ServletInitJobInter>();
}
int n = 0;
try {
for (Iterator<ServletInitJobInter> iterator = list.iterator(); iterator.hasNext();) {
n++;
ServletInitJobInter name = (ServletInitJobInter) iterator.next();
name.execute(this.getServletContext());
}
} catch (Exception e) {
log.error("第" + n + "项任务启动失败:" + e.getMessage());
}
}
}

@ -1,11 +0,0 @@
package com.farm.web.task;
import java.util.List;
/**springsysinit
* @author Administrator
*
*/
public interface TaskListInter {
public List<ServletInitJobInter> getTasks();
}

@ -1,64 +0,0 @@
package com.farm.web.task.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import com.farm.web.constant.FarmConstant;
import com.farm.web.task.ServletInitJobInter;
public class ServerLicenceInit implements ServletInitJobInter {
private final static Logger log = Logger.getLogger(ServerLicenceInit.class);
@Override
public void execute(ServletContext context) {
try {
FarmConstant.LICENCE = read(
new File(context.getRealPath("") + File.separator
+ "licence.data")).replace("\n", "");
} catch (Exception e) {
FarmConstant.LICENCE = null;
}
try {
// System.out.println("info: case is "+FarmConstant.LICENCE + " for "
// + MayCase.isCase(FarmConstant.LICENCE));
} catch (Exception e) {
System.out.println("info: case is "+FarmConstant.LICENCE + " for "+ ":false");
}
}
public String read(File file) throws Exception {
StringBuffer lines = new StringBuffer();
InputStream inputStream = null;
BufferedReader reader = null;
InputStreamReader inputStreamReader = null;
try {
inputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
String line = null;
while ((line = reader.readLine()) != null) {
lines.append(line).append("\n");
}
} catch (IOException e) {
log.info(e.getMessage(), e);
} finally {
try {
inputStreamReader.close();
inputStream.close();
reader.close();
} catch (IOException e) {
log.info(e.getMessage(), e);
}
}
return lines.toString();
}
}

@ -1,20 +0,0 @@
package com.farm.web.task.impl;
import java.util.List;
import com.farm.web.task.ServletInitJobInter;
import com.farm.web.task.TaskListInter;
public class TaskListImpl implements TaskListInter {
private List<ServletInitJobInter> tasks;
@Override
public List<ServletInitJobInter> getTasks() {
return tasks;
}
public void setTasks(List<ServletInitJobInter> tasks) {
this.tasks = tasks;
}
}

@ -1,7 +0,0 @@
package com.farm.web.test;
import com.farm.core.auth.domain.LoginUser;
public class FarmTest {
public LoginUser user =null;
}

@ -1,10 +0,0 @@
package com.farm.text;
import com.farm.core.auth.util.KeyUtil;
public class MarkLicenceKey {
public static void main(String[] args) {
System.out.println(KeyUtil.getMKey());
//System.out.println(KeyUtil.getFkey("8C8-60723AA5"));
System.out.println(KeyUtil.getFkey("C4B-8AF11814"));
}
}

@ -1,28 +0,0 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- //这是个pom文件,远程仓库的资源依赖在这里纪录-->
<modelVersion>4.0.0</modelVersion>
<groupId>com.farm.wcp</groupId>
<artifactId>wcp-api</artifactId>
<version>${wcp.version}</version>
<properties>
<wcp.version>3.2.0</wcp.version>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,73 +0,0 @@
package com.farm.wcp.api;
import java.rmi.Remote;
import java.rmi.RemoteException;
import com.farm.wcp.api.exception.DocCreatErrorExcepiton;
import com.farm.wcp.domain.Results;
//WcpAPPInter接口继承了Remote类Remote干嘛的
public interface WcpAppInter extends Remote {
/**
* html
*
* @param knowtitle
*
* @param knowtypeId
*
* @param text
*
* @param knowtag
* tag
* @param groupId
*
* @param fileId
*
* @param currentUserId
*
* @return
* @throws RemoteException
*/
//创建html知识传入参数标题标题分类内容小组内容图创建用户
//内容图是社么?
public String creatHTMLKnow(String knowtitle, String knowtypeId, String text, String knowtag, String currentUserId)
//抛出一些异常
throws RemoteException, DocCreatErrorExcepiton;
/**
* (便)
*
* @param fileid
* id
* @param docid
* id
* @param text
*
* @throws ErrorTypeException
* @throws RemoteException
*/
//抽象类功能负责对附件做索引需要传一些参数附件Id,知识id索引文字保存附件文本内容
public void runLuceneIndex(String fileid, String docid, String text) throws RemoteException;
/**
*
*
* @param typeid
* @param pagesize
* @param pagenum
* @return
*/
//get方法获得文档的类型需要传入参数类型id,页的大小,最近页,登录的名字)
public Results getTypeDocs(String typeid, int pagesize, int currentpage, String loginname)throws RemoteException;
//抛出RemoteException异常
/**
*
*
* @param typeid
* @param pagesize
* @param currentpage
* @return
*/
//get方法获得所有知识分类需要参数登录名字抛出RemoteException异常RemoteException干嘛的?
public Results getAllTypes(String loginname)throws RemoteException;
}

@ -1,30 +0,0 @@
package com.farm.wcp.api.client;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import com.farm.wcp.api.WcpAppInter;
public class WcpAppClient {
/**
* wcp
*
* @param rmiUrl
* rmi://127.0.0.1:8701/wcpapp
* @return
* @throws MalformedURLException
* @throws RemoteException
* @throws NotBoundException
*/
//创建一个WcpAPPInter类的get服务方法传入参数是rmiUrl
public static WcpAppInter getServer(String rmiUrl)
//抛出异常没有边界异常远程异常URL格式异常。
throws MalformedURLException, RemoteException, NotBoundException {
//创建WcpAPPInter对象使用静态方法lookup
WcpAppInter wcpApp = (WcpAppInter) Naming.lookup(rmiUrl);
//返回这个WcpApp的对象
return wcpApp;
}
}

@ -1,21 +0,0 @@
//导包
package com.farm.wcp.api.exception;
/**
* @author wangdong
*
*/
//文档创建错误异常的类继承了Exception异常类
public class DocCreatErrorExcepiton extends Exception {
/**
*
*/
//设置serialVersionUID常量为1L,serialVersionUID是干嘛的
private static final long serialVersionUID = 1L;
//初始化,构造方法
public DocCreatErrorExcepiton(Exception e) {
//把异常抛出给他的父类exception异常类
super(e);
}
}

@ -1,52 +0,0 @@
package com.farm.wcp.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//Results类Result前面返回值 getTypeDocsget方法获得文档的类型 getAllTypesget方法获得所有知识分类
public class Results {
//创建一个listList有序可重复有索引,泛型是Map集合。里面存储社么东西
private List<Map<String, Object>> list = new ArrayList<>();
//Results类的成员对象有totalsizeResult{文档有关}的size大小
private int totalsize;
//记录文档最近的页
private int currentpage;
//页面的大小
private int pagesize;
//下面是Result的get set方法
//获得list集合的方法
public List<Map<String, Object>> getList() {
return list;
}
//对list对象设置的set方法
public void setList(List<Map<String, Object>> list) {
this.list = list;
}
//get获取页的总大小
public int getTotalsize() {
return totalsize;
}
//set设置页的总大小
public void setTotalsize(int totalsize) {
this.totalsize = totalsize;
}
//获取最近的页
public int getCurrentpage() {
return currentpage;
}
//设置最近的页
public void setCurrentpage(int currentpage) {
this.currentpage = currentpage;
}
//get获取最近页的大小
public int getPagesize() {
return pagesize;
}
//get最近页的大小
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
}

@ -1,64 +0,0 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.farm</groupId>
<artifactId>wcp-authority</artifactId>
<version>${wcp.version}</version>
<name>用户和权限系统</name>
<properties>
<wcp.version>3.2.0</wcp.version>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<dependencies>
<dependency>
<groupId>com.farm</groupId>
<artifactId>farm-core</artifactId>
<version>${wcp.version}</version>
<exclusions>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.farm</groupId>
<artifactId>wcp-parameter</artifactId>
<version>${wcp.version}</version>
<exclusions>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,17 +0,0 @@
package com.farm.authority;
import javax.servlet.http.HttpSession;
import com.farm.authority.domain.Organization;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.util.spring.BeanFactory;
import com.farm.web.constant.FarmConstant;
public class AuthUtils {
public static Organization getCurrentOrganization(HttpSession session) {
UserServiceInter users = (UserServiceInter) BeanFactory.getBean("userServiceImpl");
LoginUser user = (LoginUser) session.getAttribute(FarmConstant.SESSION_USEROBJ);
return users.getOrg(user.getId());
}
}

@ -1,133 +0,0 @@
package com.farm.authority;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.farm.authority.domain.Action;
import com.farm.authority.domain.User;
import com.farm.authority.service.ActionServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.AuthorityService;
import com.farm.core.auth.domain.AuthKey;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.auth.exception.LoginUserNoExistException;
import com.farm.core.auth.util.AuthenticateInter;
import com.farm.core.auth.util.AuthenticateProvider;
import com.farm.util.spring.BeanFactory;
public class FarmAuthorityService implements AuthorityService {
private UserServiceInter userServiceImpl;
private ActionServiceInter actionServiceImpl;
private AuthenticateInter authUtil = AuthenticateProvider.getInstance();
private static FarmAuthorityService service;
public static AuthorityService getInstance() {
if (service == null) {
service = new FarmAuthorityService();
service.userServiceImpl = (UserServiceInter) BeanFactory.getBean("userServiceImpl");
service.actionServiceImpl = (ActionServiceInter) BeanFactory.getBean("actionServiceImpl");
}
return service;
}
@Override
public void loginHandle(String userId) {
userServiceImpl.setLoginTime(userId);
}
@Override
public Set<String> getUserAuthKeys(String userId) {
User user = userServiceImpl.getUserEntity(userId);
List<Action> actions = null;
if (user.getType().equals("3")) {
actions = actionServiceImpl.getAllActions();
} else {
actions = userServiceImpl.getUserActions(userId);
}
Set<String> set = new HashSet<String>();
for (Action action : actions) {
set.add(action.getAuthkey());
}
return set;
}
@Override
public LoginUser getUserById(String userId) {
return userServiceImpl.getUserEntity(userId);
}
@Override
public LoginUser getUserByLoginName(String loginName) {
return userServiceImpl.getUserByLoginName(loginName);
}
@Override
public List<WebMenu> getUserMenu(String userId) {
User user = userServiceImpl.getUserEntity(userId);
List<WebMenu> list = null;
if (user.getType().equals("3")) {
list = actionServiceImpl.getAllMenus();
} else {
list = userServiceImpl.getUserMenus(userId);
}
return list;
}
@Override
public boolean isLegality(String loginName, String password) throws LoginUserNoExistException {
User user = userServiceImpl.getUserByLoginName(loginName);
if (user == null) {
throw new LoginUserNoExistException("该登录名不存在!");
}
if (user.getType().equals("2")) {
throw new LoginUserNoExistException("该用户无登录权限!");
}
if (!user.getState().equals("1")) {
throw new LoginUserNoExistException("该用户已停用!");
}
if (authUtil.isMd5code(password)) {
if (password.toUpperCase().equals(user.getPassword())) {
return true;
}
} else {
if (authUtil.encodeLoginPasswordOnMd5(password, loginName).equals(user.getPassword())) {
return true;
}
}
return false;
}
@Override
public AuthKey getAuthKey(String key) {
return actionServiceImpl.getCacheAction(key);
}
@Override
public List<String> getUserPostKeys(String userId) {
return userServiceImpl.getUserPostIds(userId);
}
@Override
public String getUserOrgKey(String userId) {
return userServiceImpl.getUserOrganization(userId).getId();
}
public UserServiceInter getUserServiceImpl() {
return userServiceImpl;
}
public void setUserServiceImpl(UserServiceInter userServiceImpl) {
this.userServiceImpl = userServiceImpl;
}
public ActionServiceInter getActionServiceImpl() {
return actionServiceImpl;
}
public void setActionServiceImpl(ActionServiceInter actionServiceImpl) {
this.actionServiceImpl = actionServiceImpl;
}
}

@ -1,278 +0,0 @@
package com.farm.authority.controller;
//@RequestMapping("/edit") // 映射HTTP请求路径为"/edit",当客户端发送对该路径的请求时,将调用此方法
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import com.farm.authority.domain.Action;
import com.farm.authority.service.ActionServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.page.RequestMode;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.web.WebUtils;
import com.farm.web.easyui.EasyUiUtils;
//RequestMapping是干嘛的? 它用于将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
// MVC 和 REST 控制器的处理方法上是社么?
// 这个注解可以用在类或方法上
// 表示类中的所有响应请求的方法都以该地址作为父路径。
@RequestMapping("/action")//action是父路径
@Controller
//Controller是干嘛的
//Controller层的作用可概括如下
// 1. 接收和处理用户请求。当用户发起请求时Controller层会根据请求的URL、HTTP方法
// 等信息来判断请求的目标,并调用相应的方法进行处理。
//2. 调用Service层处理业务逻辑。当Controller需要进行业务逻辑处理时
// 会调用Service层的方法Service层会根据具体业务需求进行相应的处理。
//3. 返回处理结果。Controller层在完成请求处理之后会将处理结果封装成
// 一个ModelAndView对象然后将其发给前端页面进行显示
//4. 控制页面跳转。当用户请求需要跳转到另一个页面时,
// Controller层负责选择正确的View并返回相应的ModelAndView
// 然后前端页面根据ModelAndView中的信息进行页面渲染完成页面跳转。
//
//5. 验证数据。对于提交的表单数据等信息Controller层会进行验证
// 通过该验证可以确定数据的合法性,避免用户输入错误或者恶意提交的数据对系统造成危害。
//
//6. 处理异常。在Controller处理过程中可能会出现异常此时需要在Controller中捕获
// 并处理异常避免异常向上抛出影响整个Web应用程序的正常运行。
//ActionController类继承WebUtils
public class ActionController extends WebUtils {
//Logger对象是个不可变的类
private final static Logger log = Logger.getLogger(ActionController.class);
@Resource
//在启动spring的时候首先要启动容器
//启动spring容器时会默认寻找容器扫描范围内的可加载bean然后查找哪些bean上的属性和方法上有@Resource注解
//找到@Resource注解后判断@Resource注解括号中的name属性是否为空如果为空
// 看spring容器中的bean的id与@Resource要注解的那个变量属性名是否相同如相同匹配成功
// 如果不相同看spring容器中bean的id对应的类型是否与@Resource要注解的那个变量属性对应的类型
// 是否相等,若相等,匹配成功,若不相等,匹配失败。
//如果@Resource注解括号中的name属性不为空看name的属性值和容器中的bean的id名是否相等如相等则匹配成功如不相等则匹配失败。
ActionServiceInter actionServiceImpl;
//actionServiceImpl是个静态的ActionServiceInter类
//下面是getActionServiceImpl的get/set方法
public ActionServiceInter getActionServiceImpl() {
return actionServiceImpl;
}
//set方法设置setActionServiceImpl参数有actionServiceImpl
public void setActionServiceImpl(ActionServiceInter actionServiceImpl) {
this.actionServiceImpl = actionServiceImpl;
}
/**
*
*
* @return
*/
//query是父路径
@RequestMapping("/query")
//
@ResponseBody
//其返回值会被自动序列化为指定格式的数据(如 JSON 或 XML并直接写入 HTTP 响应体中,而不会触发视图解析器的处理
//query是查询的意思
public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
try {
// 使用EasyUiUtils工具类格式化前端传来的查询条件将其转换为DataQuery对象
query = EasyUiUtils.formatGridQuery(request, query);
// 创建一个简单的查询动作并执行查询操作返回DataResult对象
DataResult result = actionServiceImpl.createActionSimpleQuery(query).search();
// 对查询结果中的CHECKIS字段进行字典转换将1转换为“是”0转换为“否”
//字典转化是社么?对一个字符串转化成字典里面的另一个字符串
result.runDictionary("1:是,0:否", "CHECKIS");
// 对查询结果中的LOGINIS字段进行字典转换将1转换为“是”0转换为“否”
result.runDictionary("1:是,0:否", "LOGINIS");
// 对查询结果中的STATE字段进行字典转换将1转换为“可用”0转换为“不可用”
result.runDictionary("1:可用,0:不可用", "STATE");
// 使用ViewMode工具类将查询结果格式化为前端DataGrid所需的格式并返回
return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
} catch (Exception e) {
// 捕获并记录异常信息
log.error(e.getMessage());
// 返回一个包含错误信息的Map对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
@RequestMapping("/list")
public ModelAndView index(HttpSession session) {
// 获取ViewMode的单例实例并调用returnModelAndView方法传入视图名称"authority/ActionResult"
// 返回一个ModelAndView对象其中包含视图名称"authority/ActionResult",但不包含任何模型数据
return ViewMode.getInstance()
.returnModelAndView("authority/ActionResult");
}
/**
*
*
* @return
*/
@RequestMapping("/edit") // 映射HTTP请求路径为"/edit",当客户端发送对该路径的请求时,
// 将调用此方法
@ResponseBody // 表示该方法的返回结果直接写入HTTP response body中而不是解析为视图名称
//HTTP response body
//HTTP响应体Response Body是HTTP响应中用于传输实际数据的部分
//通常包含服务器向客户端发送的内容。其内容和格式取决于请求方法、状态码
//以及响应头中的Content-Type字段
public Map<String, Object> editSubmit(Action entity, HttpSession session) { // 方法接收一个Action对象和一个HttpSession对象作为参数
try {
// 调用actionServiceImpl的editActionEntity方法编辑实体并传入当前用户信息
entity = actionServiceImpl.editActionEntity(entity, getCurrentUser(session));
// 创建一个ViewMode对象设置操作类型为ADD并将编辑后的实体放入属性中最后返回一个包含这些信息的Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 捕获并打印异常信息
e.printStackTrace();
log.error(e.getMessage());
// 创建一个ViewMode对象设置操作类型为ADD并将错误信息放入属性中最后返回一个包含这些信息的Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/add") //映射HTTP请求为/add的路径当客户端对此方法请求时
//调用下面的方法
@ResponseBody
//一般和RequestMapping"/路径")连用
public Map<String, Object> addSubmit(Action entity, HttpSession session) {
try {
// 调用actionServiceImpl的insertActionEntity方法将Action实体插入数据库并获取当前用户信息
entity = actionServiceImpl.insertActionEntity(entity, getCurrentUser(session));
// 创建一个ViewMode实例并将插入后的entity对象放入其中然后返回一个对象模式的结果
return ViewMode.getInstance().putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 如果发生异常,记录错误日志
log.error(e.getMessage());
// 创建一个ViewMode实例并设置错误信息然后返回一个对象模式的结果
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/del")
@ResponseBody
public Map<String, Object> delSubmit(String ids, HttpSession session) {
try {
// 解析传入的ids字符串将其转换为字符串数组
for (String id : parseIds(ids)) {
// 调用actionServiceImpl的deleteActionEntity方法删除指定id的实体并传入当前用户信息
actionServiceImpl.deleteActionEntity(id, getCurrentUser(session));
}
// 返回一个成功的视图模式对象
return ViewMode.getInstance().returnObjMode();
} catch (Exception e) {
// 捕获并记录异常信息
log.error(e.getMessage());
// 返回一个包含错误信息的视图模式对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/info")
@ResponseBody
public Map<String, Object> view(String ids) {
try {
// 调用actionServiceImpl.getActionEntity方法获取实体信息并将其放入ViewMode对象中
return ViewMode.getInstance()
.putAttr("entity", actionServiceImpl.getActionEntity(ids))
.returnObjMode();
} catch (Exception e) {
// 捕获异常并记录错误日志
log.error(e.getMessage());
// 返回包含错误信息的Map对象
return ViewMode.getInstance().setError(e.getMessage())
.returnObjMode();
}
}
/**
*
*
* @return
*/
// 映射URL路径为"/form",当请求路径为"/form"时,调用此方法
@RequestMapping("/form")
public ModelAndView view(RequestMode pageset, String ids) {
try {
// 根据pageset中的操作类型operateType执行不同的逻辑
switch (pageset.getOperateType()) {
case (0): { // 操作类型为0查看操作
// 返回一个ModelAndView对象包含以下属性
// 1. "pageset"传入的pageset对象
// 2. "entity"通过actionServiceImpl获取的实体对象根据ids查询
// 视图名称为"authority/ActionForm"
return ViewMode.getInstance()
.putAttr("pageset", pageset) // 添加pageset到模型
.putAttr("entity", actionServiceImpl.getActionEntity(ids)) // 添加实体对象到模型
.returnModelAndView("authority/ActionForm"); // 返回视图
}
case (1): { // 操作类型为1新增操作
// 返回一个ModelAndView对象仅包含"pageset"属性
// 视图名称为"authority/ActionForm"
return ViewMode.getInstance()
.putAttr("pageset", pageset) // 添加pageset到模型
.returnModelAndView("authority/ActionForm"); // 返回视图
}
case (2): { // 操作类型为2修改操作
// 返回一个ModelAndView对象包含以下属性
// 1. "pageset"传入的pageset对象
// 2. "entity"通过actionServiceImpl获取的实体对象根据ids查询
// 视图名称为"authority/ActionForm"
return ViewMode.getInstance()
.putAttr("pageset", pageset) // 添加pageset到模型
.putAttr("entity", actionServiceImpl.getActionEntity(ids)) // 添加实体对象到模型
.returnModelAndView("authority/ActionForm"); // 返回视图
}
default: // 如果操作类型不在0、1、2中执行默认逻辑
break;
}
// 默认情况下返回一个空的ModelAndView对象视图名称为"authority/ActionForm"
return ViewMode.getInstance()
.returnModelAndView("authority/ActionForm"); // 返回视图
} catch (Exception e) { // 捕获异常
// 返回一个包含错误信息的ModelAndView对象
// 视图名称为"authority/UserForm"
return ViewMode.getInstance()
.setError(e + e.getMessage()) // 设置错误信息
.returnModelAndView("authority/UserForm"); // 返回视图
}
}
}

@ -1,364 +0,0 @@
package com.farm.authority.controller;
import com.farm.authority.domain.Action;
import com.farm.authority.domain.Actiontree;
import com.farm.authority.service.ActionServiceInter;
import com.farm.web.WebUtils;
import com.farm.web.easyui.EasyUiTreeNode;
import com.farm.web.easyui.EasyUiUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.farm.core.page.RequestMode;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
/* *
*
*
*
*v0.1
*Farm
*20141122211253
*
*/
// 声明这是一个Spring MVC控制器并映射到"/actiontree"路径下的所有请求
@RequestMapping("/actiontree")
@Controller
public class ActiontreeController extends WebUtils {
// 定义一个静态日志记录器,用于记录日志信息
private final static Logger log = Logger.getLogger(ActiontreeController.class);
// 注入ActionServiceInter接口的实现类用于处理业务逻辑
@Resource
ActionServiceInter actionServiceImpl;
// 映射到"/actiontree/list"路径下的GET请求
@RequestMapping("/list")
public ModelAndView index(HttpSession session) {
// 返回一个ModelAndView对象指定视图为"authority/ActiontreeResult"
return ViewMode.getInstance().returnModelAndView("authority/ActiontreeResult");
}
}
@RequestMapping("/icons")
// 创建并返回一个ModelAndView对象视图名称为"authority/ActionCssIcon"
public ModelAndView icons(HttpSession session) {
// HttpSession对象作为参数传递给方法但在这个方法中并未使用session对象进行任何操作
return ViewMode.getInstance().returnModelAndView(
// 这个方法处理对"/icons"路径的请求并返回一个ModelAndView对象其中包含视图名称
"authority/ActionCssIcon");
}
@RequestMapping("/actionsPage")
public ModelAndView actionsPage(HttpSession session) {
// 创建并返回一个ModelAndView对象指定视图为"authority/ActionChoose"
// 这里的ModelAndView对象用于将数据模型和视图名称封装在一起便于Spring MVC框架进行处理和渲染
return ViewMode.getInstance().returnModelAndView(
"authority/ActionChoose");
}
@RequestMapping("/treePage")
public ModelAndView treePage(HttpSession session, String ids) {
// 获取传入的ids参数并将其放入ModelAndView对象中以便在视图中使用
return ViewMode.getInstance().putAttr("ids", ids)
.returnModelAndView("authority/ActiontreenodeChooseTreeWin");
}
/**
*
*
* @return
*/
@RequestMapping("/query") // 映射HTTP请求路径为"/query",当客户端访问该路径时,会调用此方法[[3, 13, 27, 33, 35]]
@ResponseBody // 表示该方法的返回值直接写入HTTP response body中而不是被解析为跳转路径[[13, 32]]
public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) { // 定义一个处理查询请求的方法接收DataQuery对象和HttpServletRequest对象作为参数
try {
query = EasyUiUtils.formatGridQuery(request, query); // 使用EasyUiUtils工具类格式化查询参数将请求中的参数应用到DataQuery对象上[[27]]
if (query.getQueryRule().size() == 0) { // 检查查询规则是否为空
query.addRule(new DBRule("PARENTID", "NONE", "=")); // 如果为空则添加一个默认的查询规则即PARENTID等于"NONE"
}
DataResult result = actionServiceImpl.createActiontreeSimpleQuery(query).search(); // 调用actionServiceImpl的createActiontreeSimpleQuery方法创建查询并执行查询操作获取查询结果
result.runDictionary("1:分类,2:菜单,3:权限", "TYPE"); // 对查询结果中的TYPE字段进行字典转换将数字转换为对应的中文描述
result.runDictionary("1:可用,0:禁用", "STATE"); // 对查询结果中的STATE字段进行字典转换将数字转换为对应的中文描述
return ViewMode.getInstance() // 创建一个ViewMode实例
.putAttrs(EasyUiUtils.formatGridData(result)) // 使用EasyUiUtils工具类格式化查询结果并将其放入ViewMode实例的属性中
.returnObjMode(); // 返回格式化后的查询结果
} catch (Exception e) { // 捕获可能发生的异常
log.error(e.getMessage()); // 记录异常信息
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode(); // 创建一个ViewMode实例并设置错误信息返回错误信息
}
}
/**
*
*
* @return
*/
/**
* JSON
*
* @RequestMapping("/queryMenu") URL/queryMenu
* @ResponseBody HTTP
* @return Map<String, Object> MapEasyUIgrid
*/
@RequestMapping("/queryMenu")
@ResponseBody
public Map<String, Object> loadAllMenu() {
try {
// 创建DataQuery实例设置查询参数
DataQuery query = DataQuery
.getInstance(
1,
"ACT_TREE.NAME AS NAME, ACT_KEY.AUTHKEY AS SRCKEY, ACT_TREE.ID AS ID,ACT_TREE.PARENTID AS PARENTID",
"alone_auth_actiontree AS act_tree left join alone_auth_action AS act_key on act_tree.ACTIONID=act_key.ID");
// 设置每页大小为100
query.setPagesize(100);
// 使用ViewMode实例封装查询结果并格式化为EasyUI的grid数据格式
return ViewMode.getInstance()
.putAttrs(EasyUiUtils.formatGridData(query.search()))
.returnObjMode();
} catch (Exception e) {
// 捕获异常并记录日志
log.error(e.getMessage());
// 返回错误信息
return ViewMode.getInstance().setError(e.getMessage())
.returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/edit") // 映射HTTP请求路径为"/edit",处理该路径下的请求
@ResponseBody // 表示该方法的返回值直接写入HTTP响应体中而不是返回一个视图
public Map<String, Object> editSubmit(Actiontree entity, Action action, HttpSession session) {
try {
// 调用actionServiceImpl的editActiontreeEntity方法传入entity对象、当前用户和action的authkey
// getCurrentUser(session)方法用于从session中获取当前用户信息
entity = actionServiceImpl.editActiontreeEntity(entity, getCurrentUser(session), action.getAuthkey());
// 创建一个ViewMode实例并将编辑后的entity对象放入其中然后返回一个包含该entity的Map对象
return ViewMode.getInstance().putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 如果发生异常,记录错误日志
log.error(e.getMessage());
// 创建一个ViewMode实例并设置错误信息然后返回一个包含错误信息的Map对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @param entity
*
* @param authkey
* uri
* @param session
* @return
*/
@RequestMapping("/add") // 映射URL路径为/add的请求到此方法
@ResponseBody // 表示该方法的返回值直接写入HTTP响应体中而不是返回一个视图
public Map<String, Object> addSubmit(Actiontree entity, String authkey, HttpSession session) {
try {
// 调用actionServiceImpl的insertActiontreeEntity方法插入新的Actiontree实体
// getCurrentUser(session)方法用于从session中获取当前用户信息
entity = actionServiceImpl.insertActiontreeEntity(entity, getCurrentUser(session), authkey);
// 使用ViewMode工具类创建一个Map对象并将插入后的entity对象放入其中然后返回这个Map对象
return ViewMode.getInstance().putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 如果发生异常,记录错误日志
log.error(e.getMessage());
// 使用ViewMode工具类创建一个Map对象并将错误信息放入其中然后返回这个Map对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/del") // 将HTTP请求路径为"/del"的请求映射到此方法上[[13, 14, 23]]
@ResponseBody // 表示该方法的返回值直接写入HTTP响应体中而不是返回一个视图[[13, 14, 23]]
public Map<String, Object> delSubmit(String ids, HttpSession session) { // 定义处理方法接收两个参数ids字符串类型和sessionHttpSession类型
try {
for (String id : parseIds(ids)) { // 解析ids字符串将其拆分为多个id并遍历每个id
actionServiceImpl.deleteActiontreeEntity(id, getCurrentUser(session)); // 调用actionServiceImpl的deleteActiontreeEntity方法传入id和当前用户对象删除对应的实体
}
return ViewMode.getInstance().returnObjMode(); // 如果删除成功,返回一个成功的响应对象
} catch (Exception e) { // 捕获所有异常
log.error(e.getMessage()); // 记录错误日志
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode(); // 返回一个包含错误信息的响应对象
}
}
/**
*
*
* @return
*/
@RequestMapping("/form")
public ModelAndView view(RequestMode pageset, String domain, String ids, String parentid) {
// 创建一个ViewMode实例用于封装视图和模型数据
ViewMode mode = ViewMode.getInstance();
try {
// 初始化Actiontree对象用于存储父节点信息
Actiontree parent = new Actiontree();
// 初始化Actiontree对象用于存储当前实体信息
Actiontree entity = null;
// 根据pageset的operateType字段判断操作类型
switch (pageset.getOperateType()) {
case (1): { // 新增操作
// 新增操作的具体逻辑(此处为空,可能需要后续实现)
break;
}
case (0): { // 展示操作
// 根据ids获取Actiontree实体并将其放入mode中
entity = actionServiceImpl.getActiontreeEntity(ids);
mode.putAttr("entity", entity);
break;
}
case (2): { // 修改操作
// 根据ids获取Actiontree实体并将其放入mode中
entity = actionServiceImpl.getActiontreeEntity(ids);
mode.putAttr("entity", entity);
break;
}
default:
// 默认情况,无操作
break;
}
// 如果parentid不为空则获取父节点信息并放入mode中
if (parentid != null && parentid.trim().length() > 0) {
parent = actionServiceImpl.getActiontreeEntity(parentid);
mode.putAttr("parent", parent);
}
// 如果entity不为空且actionid不为空则获取对应的Action实体并放入mode中
if (entity != null && entity.getActionid() != null) {
Action treeAction = actionServiceImpl.getActionEntity(entity.getActionid());
mode.putAttr("treeAction", treeAction);
}
} catch (Exception e) {
// 捕获异常并设置错误信息,返回错误视图
return ViewMode.getInstance().setError(e.getMessage(), e).returnModelAndView("authority/ActiontreeForm");
}
// 将pageset和domain信息放入mode中并返回视图
return mode.putAttr("pageset", pageset).putAttr("domain", domain)
.returnModelAndView("authority/ActiontreeForm");
}
/**
*
*
* @return
*/
@RequestMapping("/move")
@ResponseBody
public Map<String, Object> moveTreeNodeSubmit(String oid, String deid) {
// 尝试移动树节点
try {
// 调用服务层的moveActionTreeNode方法传入原始节点ID(oid)和目标节点ID(deid)
actionServiceImpl.moveActionTreeNode(oid, deid);
// 移动成功返回包含操作结果的Map对象
return ViewMode.getInstance().returnObjMode();
} catch (Exception e) {
// 如果在移动过程中发生异常,记录错误日志
log.error(e.getMessage());
// 设置错误信息并返回包含错误信息的Map对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @param id
* @param domain
* @return
*/
@RequestMapping("/loadtree")
@ResponseBody
public List<EasyUiTreeNode> loadTreeNode(String id, String domain) {
// 尝试加载树节点
try {
// 调用服务层的getSyncTree方法传入节点ID和域名获取同步的树节点列表
return actionServiceImpl.getSyncTree(id, domain);
} catch (Exception e) {
// 如果在加载过程中发生异常,记录错误日志
log.error(e.getMessage());
// 返回一个空的树节点列表
return new ArrayList<EasyUiTreeNode>();
}
}
/**
*
*
* @return
*/
@RequestMapping("/cuserMenus")
@ResponseBody
public Object loadTreeNodeForCurrentUser(String id, String domain, HttpSession session) {
// 尝试为当前用户加载树节点菜单
try {
// 查询第一级树节点菜单包括名称、排序、ID、父ID、图标、URL和参数
List<Map<String, Object>> list1 = EasyUiTreeNode
.queryTreeNodeOne(
id,
"SORT",
"(SELECT c.NAME AS NAME, SORT, c.ID AS ID, PARENTID, ICON, b.AUTHKEY AS URL, c.PARAMS AS PARAM, domain FROM alone_auth_actiontree c LEFT JOIN alone_auth_action b ON c.ACTIONID = b.ID)",
"ID", "PARENTID", "NAME", "ICON",
"and a.DOMAIN='" + domain + "'", "URL,PARAM")
.getResultList();
// 查询第二级树节点菜单包括ID、父ID、名称、图标
List<Map<String, Object>> list2 = EasyUiTreeNode.queryTreeNodeTow(
id, "SORT", "alone_auth_actiontree", "ID", "PARENTID",
"NAME", "ICON", "and a.DOMAIN='" + domain + "'")
.getResultList();
// 格式化异步加载的树节点菜单,结合当前用户的菜单权限
return EasyUiTreeNode.formatAsyncAjaxTreeForMenuTree(list1, list2,
"PARENTID", "ID", "NAME", "ICON", "URL", "PARAM",
getCurrentUserMenus(session));
} catch (Exception e) {
// 如果在加载过程中发生异常,记录错误日志
log.error(e.getMessage());
// 返回包含错误信息的对象
return ViewMode.getInstance().setError(e.getMessage())
.returnObjMode();
}
}
}

@ -1,567 +0,0 @@
package com.farm.authority.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.farm.authority.AuthUtils;
import com.farm.authority.domain.Organization;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.page.RequestMode;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.web.WebUtils;
import com.farm.web.easyui.EasyUiTreeNode;
import com.farm.web.easyui.EasyUiUtils;
/* *
*
*
*
* v0.1
* @author zhaonaixia
* @time 2015-6-26 10:19:25
*
*/
@RequestMapping("/organization")
@Controller
public class OrganizationController extends WebUtils {
// 定义日志记录器,用于记录日志信息
private final static Logger log = Logger.getLogger(OrganizationController.class);
// 注入OrganizationServiceInter的实现类用于业务逻辑处理
@Resource
OrganizationServiceInter organizationServiceImpl;
// 获取OrganizationServiceInter实现类的实例
public OrganizationServiceInter getOrganizationServiceImpl() {
return organizationServiceImpl;
}
// 设置OrganizationServiceInter实现类的实例
public void setOrganizationServiceImpl(OrganizationServiceInter organizationServiceImpl) {
this.organizationServiceImpl = organizationServiceImpl;
}
}
/**
*
*
* @return
*/
@RequestMapping("/query")
@ResponseBody
public Map<String, Object> queryall(@ModelAttribute("query") DataQuery query, HttpServletRequest request) {
// 尝试执行查询操作
try {
// 使用EasyUiUtils格式化查询条件以便与EasyUI网格控件兼容
query = EasyUiUtils.formatGridQuery(request, query);
// 如果没有查询规则默认添加一个规则查询PARENTID为"NONE"的记录
if (query.getQueryRule().size() == 0) {
query.addRule(new DBRule("PARENTID", "NONE", "="));
}
// 执行查询,获取数据结果
DataResult result = organizationServiceImpl.createOrganizationSimpleQuery(query).search();
// 对结果中的"STATE"字段进行字典转换,将状态码转换为可读的文本
result.runDictionary("1:可用,0:禁用", "STATE");
// 对结果中的"TYPE"字段进行字典转换,将类型码转换为可读的文本
result.runDictionary("1:标准", "TYPE");
// 将格式化后的数据结果放入ViewMode实例中并返回JSON格式的响应
return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
} catch (Exception e) {
// 捕获并记录异常信息
log.error(e.getMessage());
// 设置错误信息并返回JSON格式的响应
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @param session
* @return
*/
@RequestMapping("/list")
public ModelAndView index(HttpSession session) {
// 获取ViewMode实例用于封装视图和模型数据
// 返回名为"authority/OrganizationResult"的视图,不包含任何模型数据
return ViewMode.getInstance().returnModelAndView("authority/OrganizationResult");
}
/**
*
*
* @param session
* @return
*/
@RequestMapping("/chooseOrg")
public ModelAndView chooseOrg(HttpSession session) {
// 获取ViewMode实例用于封装视图和模型数据
// 返回名为"authority/ChooseOrgResult"的视图,不包含任何模型数据
return ViewMode.getInstance().returnModelAndView("authority/ChooseOrgResult");
}
/**
* tabs
*
* @param session
* @return
*/
@RequestMapping("/organizationTabs")
public ModelAndView orgTabs(RequestMode pageset, String ids, String parentID) {
// 根据操作类型返回不同的视图模型
if (pageset.getOperateType() == 1) {
// 如果操作类型为1通常表示新增操作
// 设置pageset和parentId属性并返回"authority/OrganizationTabs"视图
return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parentId", parentID)
.returnModelAndView("authority/OrganizationTabs");
} else {
// 如果操作类型不是1通常表示编辑或查看操作
// 根据提供的ids获取Organization实体
Organization entity = organizationServiceImpl.getOrganizationEntity(ids);
// 设置pageset、entity、parentId和ids属性并返回"authority/OrganizationTabs"视图
return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
.putAttr("parentId", entity.getParentid()).putAttr("ids", ids)
.returnModelAndView("authority/OrganizationTabs");
}
}
/**
* tabs
*
* @param session
* @return
*/
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
*
* @param pageset
*
* @param ids IDID
* ID
* @return ModelAndView
* "authority/PostResult"JSP
* pageset便使
*/
@RequestMapping("/postConsoleTabs")
public ModelAndView postConsoleTabs(RequestMode pageset, String ids) {
// 使用ViewMode单例获取一个实例然后添加属性pageset到模型中
// 最后指定返回的视图名称为"authority/PostResult"并返回ModelAndView对象
return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("authority/PostResult");
}
/**
* tabs
*
* @param session
* @return
*/
@RequestMapping("/postActionsTabs")
public ModelAndView postActionsTabs(RequestMode pageset, String ids) {
// 创建一个ModelAndView对象并设置视图名称为"authority/OrgUserResult"
ModelAndView modelAndView = ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("authority/OrgUserResult");
// 返回ModelAndView对象该对象包含了视图信息和模型数据
return modelAndView;
}
/**
*
*
* @return
*/
@RequestMapping("/OrgTreeNodeSubmit")
@ResponseBody
public Object moveTreeNodeSubmit(String ids, String id) {
try {
// 调用组织结构服务实现类的moveOrgTreeNode方法移动组织树节点
organizationServiceImpl.moveOrgTreeNode(ids, id);
// 返回成功响应对象
return ViewMode.getInstance().returnObjMode();
} catch (Exception e) {
// 打印堆栈跟踪信息
e.printStackTrace();
// 记录错误日志
log.error(e.getMessage());
// 返回错误响应对象,包含错误信息
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/edit") // 映射HTTP请求路径为"/edit"
@ResponseBody // 表示返回的结果直接写入HTTP响应体中而不是返回一个视图
public Map<String, Object> editSubmit(Organization org, HttpSession session) { // 定义一个处理POST请求的方法接收Organization对象和HttpSession对象
try {
// 调用organizationServiceImpl的editOrganizationEntity方法编辑组织实体并传入当前用户信息
Organization entity = organizationServiceImpl.editOrganizationEntity(org, getCurrentUser(session));
// 创建一个ViewMode对象设置操作类型为ADD并将编辑后的实体放入属性中最后返回一个Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 捕获异常并打印堆栈信息
e.printStackTrace();
// 记录错误日志
log.error(e.getMessage());
// 创建一个ViewMode对象设置操作类型为ADD并将错误信息放入属性中最后返回一个Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/add") // 映射HTTP请求路径为"/add",即当客户端访问该路径时,会调用此方法
@ResponseBody // 表示该方法的返回值直接作为HTTP响应体返回而不是返回一个视图
public Map<String, Object> addSubmit(Organization org, HttpSession session) { // 定义方法addSubmit接收一个Organization对象和一个HttpSession对象作为参数
try {
// 调用organizationServiceImpl的insertOrganizationEntity方法插入组织实体并传入当前用户信息
Organization entity = organizationServiceImpl.insertOrganizationEntity(org, getCurrentUser(session));
// 创建一个ViewMode对象设置操作类型为ADD并将插入的实体对象放入属性中最后返回一个Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
} catch (Exception e) { // 捕获所有异常
e.printStackTrace(); // 打印堆栈跟踪信息
log.error(e.getMessage()); // 记录错误日志
// 创建一个ViewMode对象设置操作类型为ADD并将错误信息放入属性中最后返回一个Map对象
return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
}
}
/**
*
*
* @return
*/
@RequestMapping("/del") // 映射URL路径为"/del"的请求到此方法
@ResponseBody // 表示该方法的返回值直接写入HTTP响应体中而不是返回一个视图
public ModelAndView delSubmit(String ids, HttpSession session) { // 定义方法delSubmit接收两个参数ids字符串类型和sessionHttpSession类型
try {
for (String id : parseIds(ids)) { // 将ids字符串解析为多个id并遍历每个id
organizationServiceImpl.deleteOrganizationEntity(id, getCurrentUser(session)); // 调用organizationServiceImpl的deleteOrganizationEntity方法删除指定id的组织实体并传入当前用户信息
}
return ViewMode.getInstance().returnModelAndView("authority/OrganizationResult"); // 如果删除成功返回一个ModelAndView对象视图名为"authority/OrganizationResult"
} catch (Exception e) { // 捕获所有异常
e.printStackTrace(); // 打印异常堆栈信息
log.error(e.getMessage()); // 记录错误日志
return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView("authority/OrganizationResult"); // 返回一个包含错误信息的ModelAndView对象视图名为"authority/OrganizationResult"
}
}
/**
*
*
* @return
*/
@RequestMapping("/removePostUser")
@ResponseBody
public ModelAndView removePostUserSubmit(String id, String ids, HttpSession session) {
try {
// 调用组织服务实现类的removePostUsers方法传入岗位ID、用户ID列表和当前用户信息
organizationServiceImpl.removePostUsers(id, ids, getCurrentUser(session));
// 返回一个ModelAndView对象视图名为"authority/OrgUserResult"
return ViewMode.getInstance().returnModelAndView("authority/OrgUserResult");
} catch (Exception e) {
// 打印堆栈跟踪信息
e.printStackTrace();
// 记录错误日志
log.error(e.getMessage());
// 设置错误信息并返回一个ModelAndView对象视图名为"authority/OrgUserResult"
return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView("authority/OrgUserResult");
}
}
/**
*
*
* @return
*/
@RequestMapping("/orgTreeNodeTreeView")
public ModelAndView forSend(String ids) {
// 创建一个ModelAndView实例并将参数ids添加到模型中
return ViewMode.getInstance().putAttr("ids", ids)
// 设置视图名称为"authority/OrganizationTreenodeChooseTreeWin"
.returnModelAndView("authority/OrganizationTreenodeChooseTreeWin");
}
/**
* tree
*
* @return
*/
@RequestMapping("/userORGTreeView")
public ModelAndView userOrgTree(String ids) {
// 创建一个ModelAndView对象并设置视图名称为"authority/UserorgChooseTreeWin"
return ViewMode.getInstance().putAttr("ids", ids).returnModelAndView("authority/UserorgChooseTreeWin");
}
/**
*
*
* @return
*/
@RequestMapping("/userOrg") // 将HTTP请求映射到/userOrg路径该方法处理此路径的请求[[4, 6, 13]]
@ResponseBody // 表示该方法的返回值直接写入HTTP响应体中而不是返回一个视图[[27]]
public Object userORGSubmit(RequestMode pageset, String ids, String id, HttpSession session) {
try {
for (String userId : parseIds(ids)) { // 解析传入的ids字符串将其转换为用户ID列表
organizationServiceImpl.addUserPost(userId, id, getCurrentUser(session)); // 为每个用户ID添加岗位信息使用当前用户的会话信息
}
return ViewMode.getInstance().returnObjMode(); // 返回一个成功的响应对象
} catch (Exception e) {
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode(); // 如果发生异常,返回一个包含错误信息的响应对象
}
}
/**
*
*
* @return
*/
/**
* "/postTree" HTTP
* 使 @ResponseBody HTTP
*
* @param id ID
* @return Object organizationServiceImpl loadPostTree
* JSON
*/
@RequestMapping("/postTree")
@ResponseBody
public Object userORGLoadTree(String id) {
// 调用 organizationServiceImpl 的 loadPostTree 方法,传入 id 参数,
// 获取岗位树数据,并直接返回给客户端。
return organizationServiceImpl.loadPostTree(id);
}
/**
*
*
* @return
*/
/**
* "/form" HTTP
*
* @param pageset
* @param ids ID
* @param parentId ID
* @return ModelAndView
*/
@RequestMapping("/form")
public ModelAndView view(RequestMode pageset, String ids, String parentId) {
try {
// 初始化父组织对象
Organization parent = null;
// 如果父组织ID不为空查询父组织信息
if (!parentId.equals("") && parentId != null) {
parent = organizationServiceImpl.getOrganizationEntity(parentId);
}
// 根据操作类型执行不同逻辑
switch (pageset.getOperateType()) {
case (1): { // 新增操作
// 设置页面属性和父组织信息,返回新增组织信息的视图
return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parent", parent)
.returnModelAndView("authority/OrganizationForm");
}
case (0): { // 展示操作
// 查询指定ID的组织信息
Organization entity = organizationServiceImpl.getOrganizationEntity(ids);
// 设置页面属性、组织信息和父组织信息,返回展示组织信息的视图
return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
.putAttr("parent", parent).returnModelAndView("authority/OrganizationForm");
}
case (2): { // 修改操作
// 查询指定ID的组织信息
Organization entity = organizationServiceImpl.getOrganizationEntity(ids);
// 设置页面属性、组织信息和父组织信息,返回修改组织信息的视图
return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
.putAttr("parent", parent).returnModelAndView("authority/OrganizationForm");
}
}
} catch (Exception e) {
// 处理异常,设置错误信息,返回组织信息表单视图
return ViewMode.getInstance().setError(e + e.getMessage()).returnModelAndView("authority/OrganizationForm");
}
// 默认返回组织信息表单视图
return ViewMode.getInstance().returnModelAndView("authority/OrganizationForm");
}
/**
*
*/
/**
* "/organizationTree" HTTP
*
* @param id ID
* @return Object JSON
*/
@RequestMapping("/organizationTree")
@ResponseBody
public Object loadTreeNode(String id) {
// 如果传入的ID为null则将其设置为"NONE",可能表示加载根节点
if (id == null) {
id = "NONE";
}
try {
// 查询一级子节点和二级子节点并格式化为EasyUiTreeNode对象列表
// queryTreeNodeOne 和 queryTreeNodeTow 方法分别查询一级和二级子节点
// "SORT", "alone_auth_organization", "ID", "PARENTID", "NAME", "CTIME" 是查询用的参数
return EasyUiTreeNode
.formatAsyncAjaxTree(
EasyUiTreeNode.queryTreeNodeOne(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
"NAME", "CTIME").getResultList(),
EasyUiTreeNode
.queryTreeNodeTow(id, "SORT", "alone_auth_organization", "ID", "PARENTID", "NAME", "CTIME")
.getResultList(), "PARENTID", "ID", "NAME", "CTIME");
} catch (Exception e) {
// 如果发生异常,记录错误日志并返回包含错误信息的对象
log.error(e.getMessage());
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
}
/**
* Auth
*/
/**
* "/organizationTreeAuth" HTTP
*
* @param id ID
* @param session HttpSession
* @return Object JSON
*/
@RequestMapping("/organizationTreeAuth")
@ResponseBody
public Object loadTreeNode(String id, HttpSession session) {
// 初始化权限标志为false
boolean authFlag = false;
// 从会话中获取当前组织信息
Organization org = AuthUtils.getCurrentOrganization(session);
// 如果传入的ID为null则将其设置为"NONE",可能表示加载根节点
if (id == null) {
id = "NONE";
// 如果当前组织不为null则设置权限标志为true并使用当前组织的父ID作为节点ID
if (org != null) {
authFlag = true;
id = org.getParentid();
}
}
// ...(省略后续代码,可能包含查询节点、格式化返回数据以及异常处理等逻辑)
}
// 创建查询对象 query1用于查询一级树节点带有权限验证
DataQuery query1 = EasyUiTreeNode.queryTreeNodeOneAuth(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
"NAME", "CTIME", null, null, authFlag);
// 创建查询对象 query2用于查询二级树节点带有权限验证
DataQuery query2 = EasyUiTreeNode.queryTreeNodeTowAuth(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
"NAME", "CTIME", null, authFlag);
// 如果当前组织信息不为空,则为查询添加权限规则
if (org != null) {
// 为 query1 添加规则,只查询树编码与当前组织树编码匹配的节点
query1.addRule(new DBRule("treecode", AuthUtils.getCurrentOrganization(session).getTreecode(), "like-"));
// 为 query2 添加规则,只查询树编码与当前组织树编码匹配的节点
query2.addRule(new DBRule("b.treecode", AuthUtils.getCurrentOrganization(session).getTreecode(), "like-"));
}
// 尝试执行查询并格式化结果为异步加载的树节点
try {
// 执行查询,获取一级和二级节点列表,然后格式化为 EasyUiTreeNode 对象列表
return EasyUiTreeNode.formatAsyncAjaxTree(query1.search().getResultList(), query2.search().getResultList(),
"PARENTID", "ID", "NAME", "CTIME");
} catch (Exception e) {
// 如果在查询或格式化过程中发生异常,记录错误日志
log.error(e.getMessage());
// 返回包含错误信息的 ViewMode 对象
return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
}
/**
* v1.0 zhanghc 2015961:58:25
*
* @return List<Organization>
*/
@RequestMapping("/loadTree") // 映射到 "/loadTree" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public List<Organization> loadTree() { // 定义一个公共方法 loadTree返回类型为 Organization 列表
// 调用 organizationServiceImpl 的 getTree 方法,获取组织结构树
// 并将获取到的树结构作为返回值,@ResponseBody 会将其转换为 JSON 等格式发送给客户端
return organizationServiceImpl.getTree();
}
// ----------------------------------------------------------------------------------
/**
* v1.0 zhanghc 2015962:43:50
*
* @param orgId
* ID
* @return List<Organization>
*/
@RequestMapping("/loadPost") // 映射到 "/loadPost" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public List<Map<String, Object>> loadPost(String orgId) { // 定义一个公共方法 loadPost接收一个组织ID作为参数返回类型为 Map<String, Object> 列表
// 调用 organizationServiceImpl 的 getPostList 方法传入组织ID(orgId),获取该组织下的岗位列表
// 方法返回的岗位列表是一个 Map<String, Object> 类型的列表,每个 Map 对象代表一个岗位的信息
// @ResponseBody 注解会自动将返回的列表转换为 JSON 等格式发送给客户端
return organizationServiceImpl.getPostList(orgId);
}
/**
* v1.0 zhanghc 2015971:48:14
*
* @param orgId
* @return List<Map<String,Object>>
*/
@RequestMapping("/loadPostWithPOrgPost") // 映射到 "/loadPostWithPOrgPost" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public List<Map<String, Object>> loadPostWithPOrgPost(String orgId) { // 定义一个公共方法 loadPostWithPOrgPost接收一个组织ID作为参数返回类型为 List<Map<String, Object>>
// 调用 organizationServiceImpl 的 getPostListWithPOrgPost 方法传入组织ID(orgId),获取该组织及其父组织下的岗位列表
// 方法返回的岗位列表是一个 List<Map<String, Object>> 类型的列表,每个 Map 对象代表一个岗位的信息
// @ResponseBody 注解会自动将返回的列表转换为 JSON 等格式发送给客户端
return organizationServiceImpl.getPostListWithPOrgPost(orgId);
}
}

@ -1,382 +0,0 @@
package com.farm.authority.controller;
import java.util.List;
import java.util.Map;
import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Post;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.page.RequestMode;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.web.WebUtils;
import com.farm.web.easyui.EasyUiTreeNode;
import com.farm.web.easyui.EasyUiUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/* *
*
*
*
* v0.1
* @author zhaonaixia
* @time 2015-6-26 10:19:25
*
*/
@RequestMapping("/post") // 映射类级别的请求路径,所有该类的请求都以"/post"为前缀
@Controller // 标识该类是一个Spring MVC的控制器
public class PostController extends WebUtils { // 定义PostController类继承自WebUtils类用于处理与岗位相关的请求
private final static Logger log = Logger.getLogger(PostController.class); // 定义日志记录器,用于记录日志信息
@Resource // 注解用于自动注入OrganizationServiceInter类型的bean
OrganizationServiceInter organizationServiceImpl; // 声明OrganizationServiceInter接口的实例用于业务逻辑处理
// Getter方法用于获取organizationServiceImpl对象
public OrganizationServiceInter getOrganizationServiceImpl() {
return organizationServiceImpl;
}
// Setter方法用于设置organizationServiceImpl对象
public void setOrganizationServiceImpl(
OrganizationServiceInter organizationServiceImpl) {
this.organizationServiceImpl = organizationServiceImpl;
}
}
/**
*
*
* @return
*/
@RequestMapping("/query") // 映射到 "/query" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public Map<String, Object> queryall( // 定义一个公共方法 queryall用于处理查询请求
@ModelAttribute("query") DataQuery query, // 通过 @ModelAttribute 注解绑定请求参数到 DataQuery 对象
HttpServletRequest request, // 请求对象,用于获取请求信息
String ids) { // 组织ID字符串用于查询特定组织的岗位信息
try {
query = EasyUiUtils.formatGridQuery(request, query); // 使用 EasyUiUtils 工具类格式化查询条件
query.addRule(new DBRule("ORGANIZATIONID", ids, "=")); // 添加数据库查询规则仅查询指定组织ID的岗位
DataResult result = organizationServiceImpl.createPostSimpleQuery(query) // 调用服务层方法创建查询并执行
.search(); // 执行查询
result.runDictionary("0:否,1:是", "EXTENDIS"); // 对查询结果中的 "EXTENDIS" 字段进行字典转换,将数字转换为文字
return ViewMode.getInstance() // 获取 ViewMode 实例
.putAttrs(EasyUiUtils.formatGridData(result)) // 将格式化后的查询结果放入 ViewMode
.returnObjMode(); // 返回封装好的对象模式
} catch (Exception e) { // 捕获异常
log.error(e.getMessage()); // 记录错误日志
return ViewMode.getInstance().setError(e.getMessage()) // 设置错误信息到 ViewMode
.returnObjMode(); // 返回包含错误信息的对象模式
}
}
/**
*
* @param session
* @return
*/
@RequestMapping("/chooseUser") // 映射到 "/chooseUser" 路径的 HTTP 请求
public ModelAndView chooseUser(HttpSession session) { // 定义一个公共方法 chooseUser用于处理选择用户的请求
// 不需要使用 session 参数,但保留以符合方法签名
// 返回一个 ModelAndView 对象,该对象包含视图名称 "authority/ChooseUserResult"
// 这个视图通常用于展示选择用户的结果或提供一个用户选择界面
return ViewMode.getInstance()
.returnModelAndView("authority/ChooseUserResult");
}
/**
*
* @param session
* @return
*/
@RequestMapping("/postActions") // 映射到 "/postActions" 路径的 HTTP 请求
public ModelAndView postActions(HttpSession session, String ids) { // 定义一个公共方法 postActions用于处理岗位动作设置的请求
// 接收 HttpSession 对象,可能用于获取会话信息,但在此方法中未直接使用
// 接收一个字符串参数 ids通常表示岗位的ID或多个ID用于后续操作
// 使用 ViewMode.getInstance() 获取 ViewMode 的实例
// 调用 putAttr 方法将 ids 参数放入模型中,以便在视图中使用
// 调用 returnModelAndView 方法返回一个 ModelAndView 对象,包含视图名称 "authority/PostActionsSeting"
// 这个视图通常用于展示和设置岗位相关的动作或权限
return ViewMode.getInstance()
.putAttr("ids", ids) // 将 ids 参数添加到模型中,以便在视图中可以访问这个值
.returnModelAndView("authority/PostActionsSeting"); // 指定返回的视图名称
}
// 这段代码定义了一个处理岗位动作设置的请求方法 postActions。
// 方法接收一个 HttpSession 对象和岗位ID字符串(ids),然后将 ids 存入模型中,
// 并返回一个指向 "authority/PostActionsSeting" 视图的 ModelAndView 对象。
// 这个视图将用于展示和设置与指定岗位ID相关的动作或权限。
/**
*
*
* @return
*/
@RequestMapping("/edit") // 映射到 "/edit" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public Map<String, Object> editSubmit(Post org, HttpSession session) { // 定义一个公共方法 editSubmit用于处理编辑岗位信息的提交请求
// 参数 Post org 包含了从前端传递过来的岗位信息
// 参数 HttpSession session 用于获取当前用户的会话信息
try {
// 调用 organizationServiceImpl 的 editPost 方法来编辑岗位信息
// 参数包括岗位ID、岗位名称、扩展信息以及当前用户信息
Post entity = organizationServiceImpl.editPost(org.getId(), org.getName(),
org.getExtendis(), getCurrentUser(session));
// 使用 ViewMode.getInstance() 获取 ViewMode 的实例
// 设置操作类型为 ADD可能是一个误导实际应该是 EDIT
// 将编辑后的岗位实体放入模型中
// 调用 returnObjMode 方法返回一个包含操作结果和实体信息的 Map 对象
return ViewMode.getInstance().setOperate(OperateType.ADD)
.putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 捕获并打印异常堆栈信息
e.printStackTrace();
// 记录错误日志
log.error(e.getMessage());
// 返回一个包含错误信息的 ViewMode 对象,操作类型仍为 ADD应改为 EDIT
return ViewMode.getInstance().setOperate(OperateType.ADD)
.setError(e.getMessage()).returnObjMode();
}
} // 方法结束
// 这段代码定义了一个处理编辑岗位信息提交的请求方法 editSubmit。
// 方法尝试更新岗位信息,并在成功时返回更新后的岗位实体和操作结果。
// 如果在处理过程中发生异常,方法将捕获异常、记录错误日志,并返回一个包含错误信息的 Map 对象。
// 注意:操作类型使用了 OperateType.ADD这可能是一个错误因为实际操作是编辑EDIT
/**
*
*
* @return
*/
@RequestMapping("/add") // 映射到 "/add" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public Map<String, Object> addSubmit(Post org, HttpSession session, String ids) { // 定义一个公共方法 addSubmit用于处理添加岗位信息的提交请求
// 参数 Post org 包含了从前端传递过来的岗位信息
// 参数 HttpSession session 用于获取当前用户的会话信息
// 参数 String ids 可能表示关联的父组织ID或其他标识
try {
// 调用 organizationServiceImpl 的 insertPost 方法来添加新的岗位信息
// 参数包括关联的ID、岗位名称、扩展信息以及当前用户信息
Post entity = organizationServiceImpl.insertPost(ids, org.getName(), org.getExtendis(), getCurrentUser(session));
// 使用 ViewMode.getInstance() 获取 ViewMode 的实例
// 设置操作类型为 ADD表示这是一个添加操作
// 将添加后的岗位实体放入返回的模型中
// 返回包含操作结果和岗位实体的 Map 对象
return ViewMode.getInstance().setOperate(OperateType.ADD)
.putAttr("entity", entity).returnObjMode();
} catch (Exception e) {
// 如果在处理过程中发生异常,打印异常堆栈信息
e.printStackTrace();
// 记录错误日志
log.error(e.getMessage());
// 返回一个包含错误信息的 Map 对象,操作类型仍为 ADD
return ViewMode.getInstance().setOperate(OperateType.ADD)
.setError(e.getMessage()).returnObjMode();
}
} // 方法结束
// 这段代码定义了一个处理添加岗位信息提交的请求方法 addSubmit。
// 方法尝试添加新的岗位信息,并在成功时返回新添加的岗位实体和操作结果。
// 如果在处理过程中发生异常,方法将捕获异常、记录错误日志,并返回一个包含错误信息的 Map 对象。
/**
*
*
* @return
*/
@RequestMapping("/ALONEROLEGROUP_SYSBASE_SETTREE") // 映射到 "/ALONEROLEGROUP_SYSBASE_SETTREE" 路径的 HTTP 请求
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public ModelAndView roleGroupSetTree(String ids, String id) { // 定义一个公共方法 roleGroupSetTree用于处理角色组设置树形结构的请求
// 参数 String ids 可能表示一系列动作或权限的ID以某种分隔符分隔
// 参数 String id 可能表示特定的岗位ID或角色组ID
try {
List<String> actions = parseIds(ids); // 调用 parseIds 方法将字符串 ids 解析为 List<String>,可能按逗号或其他分隔符分割
organizationServiceImpl.setPostActionTree(actions, id); // 调用 organizationServiceImpl 的 setPostActionTree 方法,设置岗位动作树
// 参数 actions 是解析后的动作ID列表
// 参数 id 是岗位或角色组的ID
return ViewMode.getInstance() // 获取 ViewMode 实例
.returnModelAndView("authority/PostActionsSeting"); // 设置返回的视图名称为 "authority/PostActionsSeting" 并返回 ModelAndView 对象
} catch (Exception e) { // 捕获方法中可能抛出的任何异常
e.printStackTrace(); // 打印异常的堆栈信息
log.error(e.getMessage()); // 记录异常的错误信息到日志
return ViewMode.getInstance() // 获取 ViewMode 实例
.returnModelAndView("authority/PostActionsSeting"); // 即使发生异常,也返回相同的视图名称 "authority/PostActionsSeting"
}
} // 方法结束
// 这段代码定义了一个处理角色组设置树形结构的方法 roleGroupSetTree。
// 方法尝试解析动作ID列表并调用服务层的方法来设置岗位动作树。
// 如果操作成功,将返回指定的视图;如果发生异常,将记录错误并返回相同
/**
*
*
* @return
*/
@RequestMapping("/del") // 映射到 "/del" 路径的 HTTP 请求,用于处理删除操作
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public ModelAndView delSubmit(String ids, HttpSession session) { // 定义一个公共方法 delSubmit用于处理删除岗位信息的提交请求
// 参数 String ids 表示要删除的岗位ID可能是一个或多个ID以某种分隔符分隔
// 参数 HttpSession session 用于获取当前用户的会话信息
try {
organizationServiceImpl.deletePostEntity(ids, getCurrentUser(session)); // 调用服务层的 deletePostEntity 方法根据提供的ID删除岗位实体
// getCurrentUser(session) 方法用于从会话中获取当前登录用户的信息
return ViewMode.getInstance() // 获取 ViewMode 实例
.returnModelAndView("authority/PostResult"); // 删除成功后,返回 "authority/PostResult" 视图名称的 ModelAndView 对象
} catch (Exception e) { // 捕获处理过程中可能发生的异常
e.printStackTrace(); // 打印异常的堆栈信息
log.error(e.getMessage()); // 记录错误日志
return ViewMode.getInstance() // 获取 ViewMode 实例
.setError(e.getMessage()) // 设置错误信息
.returnModelAndView("authority/PostResult"); // 即使发生异常,也返回 "authority/PostResult" 视图名称的 ModelAndView 对象
}
} // 方法结束
// 这段代码定义了一个处理删除岗位信息的方法 delSubmit。
// 方法接收要删除的岗位ID和用户会话信息尝试调用服务层的方法进行删除操作。
// 如果删除成功,返回相应的视图;如果发生异常,记录错误并返回相同的视图,同时携带错误信息。
/**
*
*
* @return
*/
@RequestMapping("/ALONEMENU_RULEGROUP_TREENODE") // 映射到 "/ALONEMENU_RULEGROUP_TREENODE" 路径的 HTTP 请求,用于初始化角色组树节点
@ResponseBody // 表示返回的结果将直接写入 HTTP 响应正文,而不是作为视图名称
public Object postActionsTreeInit(DataQuery query, String ids) { // 定义一个公共方法 postActionsTreeInit用于处理初始化角色组树节点的请求
// 参数 DataQuery query 表示查询条件,用于筛选角色组数据
// 参数 String ids 可能表示特定的角色组ID或相关标识用于进一步筛选或定位数据
return EasyUiTreeNode.formatAjaxTree(initRoleGruopTreeNode(query, ids), // 调用 initRoleGruopTreeNode 方法初始化角色组树节点,并返回格式化后的树节点数据
"A_PARENTID", // 父节点ID的字段名
"A_ID", // 节点ID的字段名
"A_NAME", // 节点显示名称的字段名
"C_POSTID", // 可能表示与岗位相关联的ID字段名
"A_ICON"); // 节点图标的字段名
}
/**
*
*
* @return
*/
private List<Map<String, Object>> initRoleGruopTreeNode(DataQuery query, String ids) {
// 初始化返回结果对象
DataResult result = null;
try {
// 初始化查询对象,设置查询的表和连接条件,以及需要选择的字段
query = DataQuery.init(
query,
"alone_auth_actiontree A LEFT JOIN alone_auth_action B ON A.ACTIONID = B.ID LEFT JOIN (SELECT POSTID, MENUID FROM alone_auth_postaction WHERE POSTID = '" + ids + "') C ON A.id = C.menuid",
"A.NAME,A.DOMAIN,a.ICON,A.ID,A.SORT,A.PARENTID,A.TREECODE,B.AUTHKEY,A.name as B_LABLE,A.TYPE,c.postid");
// 设置查询结果不重复
query.setDistinct(true);
// 设置查询的页面大小
query.setPagesize(100);
// 添加排序条件
query.addSort(new DBSort("a.DOMAIN,LENGTH(A.TREECODE),a.SORT", "ASC", false));
// 设置不统计总记录数
query.setNoCount();
// 执行查询
result = query.search();
// 遍历查询结果,对每个节点进行格式化处理
for (Map<String, Object> node : result.getResultList()) {
// 在节点名称后添加域名信息,用于显示
node.put("A_NAME", node.get("A_NAME").toString() + "&nbsp;&nbsp;&nbsp;&nbsp;<span style='color:gray;font-size:10px;'>"
+ (node.get("A_DOMAIN").toString()).toUpperCase() + "</span>");
}
} catch (Exception e) {
// 捕获异常,设置错误信息到结果对象
result = DataResult.setMessager(result, e + e.getMessage());
// 记录错误日志
log.error(e.getMessage() + e);
}
// 返回查询结果列表
return result.getResultList();
}
/**
*
*
* @return
*/
@RequestMapping("/form") // 映射到 "/form" 路径的 HTTP 请求
public ModelAndView view(RequestMode pageset, String ids) { // 定义一个公共方法 view接收请求模式和ID字符串作为参数
// TODO 自动生成代码,修改后请去除本注释 // 提示开发者此部分代码为自动生成,需要手动修改后删除此注释
try {
switch (pageset.getOperateType()) { // 根据操作类型进行分支处理
case (1): { // 新增操作
// 返回新增页面,并传递 pageset 和 ids 参数
return ViewMode.getInstance().putAttr("pageset", pageset)
.putAttr("ids", ids)
.returnModelAndView("authority/PostForm");
}
case (0): { // 展示操作
Post entity = organizationServiceImpl.getPostEntity(ids); // 根据ID获取岗位实体
// 返回展示页面,并传递 pageset 和 entity 参数
return ViewMode.getInstance().putAttr("pageset", pageset)
.putAttr("entity", entity)
.returnModelAndView("authority/PostForm");
}
case (2): { // 修改操作
Post entity = organizationServiceImpl.getPostEntity(ids); // 根据ID获取岗位实体
// 返回修改页面,并传递 pageset 和 entity 参数
return ViewMode.getInstance().putAttr("pageset", pageset)
.putAttr("entity", entity)
.returnModelAndView("authority/PostForm");
}
default:
break; // 默认情况,不执行任何操作
}
} catch (Exception e) { // 捕获并处理异常
e.printStackTrace(); // 打印异常堆栈信息
log.error(e.getMessage()); // 记录错误日志
// 返回错误页面,并传递错误信息
return ViewMode.getInstance().setError(e + e.getMessage())
.returnModelAndView("authority/OrganizationForm");
}
// 如果没有匹配的操作类型或发生异常,返回组织机构表单页面
return ViewMode.getInstance().returnModelAndView("authority/OrganizationForm");
}
private static final long serialVersionUID = 1L;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save