`
alvin198761
  • 浏览: 9118 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
文章分类
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
游戏设计 http://www.fairygui.com/

        
判断表情的正则表达式
^[a-zA-Z0-9\u4e00-\u9fa5\p{N}\p{P}\p{Sm}\p{Sc}\p{Sk}\p{Z}\p{C}]+$
xxxx sssss
 'GET /api/demo/download':function (req,res,next) {
    var data = Mock.mock('@string(500)');
    res.setHeader("Content-Disposition", "attachment; filename=\"test.txt\"");
    res.setHeader("Content-Length", "" + data.length);
    res.writeHead(200, {'Content-Type': "application/octet-stream;charset=UTF-8"});
    res.write(data);
    res.end();
  }
feign 开启压缩功能
#feign 开启压缩
feign.compression.request.enabled: true
feign.compression.response.enabled: true
feign.compression.request.mime-types: application/json,application/xml,text/html,text/xml,text/plain
feign.compression.request.min-request-size: 2048
#http压缩
server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain
server.compression.min-response-size: 2048
maven smack
<repositories>
        <repository>
            <id>dev.macro10.com</id>
            <url>http://dev.macro10.com/repo</url>
        </repository>
    </repositories>     <dependencies>
        <dependency>
            <groupId>org.igniterealtime</groupId>
            <artifactId>smack</artifactId>
            <version>3.0.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.igniterealtime</groupId>
            <artifactId>smackx</artifactId>
            <version>3.0.4</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
运行maven
 <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId><!-- execute file config-->
                <version>1.8.1</version>
                <configuration>
                    <programs>
                        <program>
                            <mainClass>com.snda.sysdev.gpush.migration.Main</mainClass>
                            <id>startup</id>
                        </program>
                    </programs>
                    <repositoryName>lib</repositoryName>
                    <repositoryLayout>flat</repositoryLayout>
                    <!--<extraJvmArguments>-Xms1024m -Xmx15360m -XX:PermSize=64m -XX:MaxPermSize=256m</extraJvmArguments>-->
                    <assembleDirectory>${project.build.directory}/appassembler</assembleDirectory>
                    <showConsoleWindow>false</showConsoleWindow>
                </configuration>
                <executions>
                    <execution>
                        <id>appassembler</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
还原
 boolean loginState = false;
        if (principal != null) {

            ScopedUser user = (ScopedUser) this.aclService.getScopeUser(principal);
            modelMap.addAttribute("username", user.getUsername());
            loginState = true;
        } else {
            HttpSession session = request.getSession();
            AuthenticationException authenticationException = (AuthenticationException)
                    session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
            if (authenticationException != null) {
                modelMap.addAttribute("error", authenticationException.getMessage());
                session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
            }
            Object username = session.getAttribute("username");
            if (username != null) {
                session.removeAttribute("username");
                modelMap.addAttribute("username", username);
            }
        }




HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        HttpLoggingInterceptor.Level logLevel = profile.equals("dev") ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE;
        httpLoggingInterceptor.setLevel(logLevel);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                        if (authentication != null) {
                            Object principal = authentication.getPrincipal();
                            if (principal != null && principal instanceof ScopedUser) {
                                ScopedUser user = (ScopedUser) principal;
                                if (user.getSessionId() != null) {
                                    Headers headers = request.headers().newBuilder().set("Cookie", "JSESSIONID=" + user.getSessionId()).build();
                                    request = request.newBuilder().headers(headers).build();
                                }
                            }
                        }
                        return chain.proceed(request);
                    }
                }).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(endPoint).addConverterFactory(GsonConverterFactory.create(new Gson())).client(okHttpClient).build();



  UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetails(request));
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication(authentication);
            HttpSession session = request.getSession();
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
定时任务
JobDataMap quartz
rule.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
	- you may not use this file except in compliance with the License. - You 
	may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 
	- - Unless required by applicable law or agreed to in writing, software - 
	distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
	License for the specific language governing permissions and - limitations 
	under the License. -->
<!DOCTYPE mycat:rule SYSTEM "rule.dtd">
<mycat:rule xmlns:mycat="http://org.opencloudb/">
	<tableRule name="sharding-by-murmur">
		<rule>
			<columns>id</columns>
			<algorithm>murmur</algorithm>
		</rule>
	</tableRule>
	<tableRule name="sharding-device-by-murmur">
		<rule>
			<columns>device_id</columns>
			<algorithm>murmur</algorithm>
		</rule>
	</tableRule>
	

	<function name="murmur"
		class="org.opencloudb.route.function.PartitionByMurmurHash">
		<property name="seed">0</property><!-- 默认是0 -->
		<property name="count">3</property><!-- 要分片的数据库节点数量,必须指定,否则没法分片 -->
		<property name="virtualBucketTimes">160</property><!-- 一个实际的数据库节点被映射为这么多虚拟节点,默认是160倍,也就是虚拟节点数是物理节点数的160倍 -->
		<!-- <property name="weightMapFile">weightMapFile</property> 节点的权重,没有指定权重的节点默认是1。以properties文件的格式填写,以从0开始到count-1的整数值也就是节点索引为key,以节点权重值为值。所有权重值必须是正整数,否则以1代替 -->
		<!-- <property name="bucketMapPath">/etc/mycat/bucketMapPath</property> 
			用于测试时观察各物理节点与虚拟节点的分布情况,如果指定了这个属性,会把虚拟节点的murmur hash值与物理节点的映射按行输出到这个文件,没有默认值,如果不指定,就不会输出任何东西 -->
	</function>
</mycat:rule>



<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://org.opencloudb/" >

	<schema name="gpush" checkSQLschema="false">
		<!-- auto sharding by id (long) -->
		<table name="device" primaryKey="id" dataNode="dn1,dn2,dn3" rule="sharding-by-murmur" />
		<table name="app_device_alias" dataNode="dn1,dn2,dn3" rule="sharding-device-by-murmur" />
		<table name="app_device_channel" dataNode="dn1,dn2,dn3" rule="sharding-device-by-murmur" />
        <table name="tag_device" dataNode="dn1,dn2,dn3" rule="sharding-device-by-murmur" />
        <table name="device_token_prod" dataNode="dn1,dn2,dn3" rule="sharding-device-by-murmur" />
    	<table name="device_token_test" dataNode="dn1,dn2,dn3" rule="sharding-device-by-murmur" />


		<table name="application" type="global" dataNode="dn2"/>
		<table name="channel" type="global" dataNode="dn2"/>
		<table name="notification" type="global" dataNode="dn2"/>
		<table name="notif_range" type="global" dataNode="dn2"/>
		<table name="stat_notif" type="global" dataNode="dn2"/>
		<table name="stat_device" type="global" dataNode="dn2"/>
        <table name="tag" type="global" dataNode="dn2"/>
        <table name="test_device" type="global" dataNode="dn2"/>
        <table name="apns_conf" type="global" dataNode="dn2"/>
        <table name="stat_notif_min5" type="global" dataNode="dn2"/>
        <table name="notif_repeat" type="global" dataNode="dn2"/>
        <table name="notif_repeat_item" type="global" dataNode="dn2"/>
	</schema>
	<dataNode name="dn1" dataHost="host1" database="gpush1" />
	<dataNode name="dn2" dataHost="host2" database="gpush2" />
	<dataNode name="dn3" dataHost="host3" database="gpush3" />
	<dataHost name="host1" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
		<heartbeat>select user()</heartbeat>
		<writeHost host="hostM1" url="127.0.0.1:3306" user="sysdev" password="sysdev@snda"/>
	</dataHost>
	<dataHost name="host2" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
		<heartbeat>select user()</heartbeat>
		<writeHost host="hostM2" url="127.0.0.1:3306" user="sysdev" password="sysdev@snda"/>
	</dataHost>
	<dataHost name="host3" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
		<heartbeat>select user()</heartbeat>
		<writeHost host="hostM3" url="127.0.0.1:3306" user="sysdev" password="sysdev@snda"/>
	</dataHost>
</mycat:schema>



loader
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.keqi.client.launcher;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 加载 /NetBeansProjects/keqiDOS/ClientDist文件下的
 * 所有文件,同时递归子目录下的文件,没有区分文件类型
 * 
 * @author zhxu
 * @date 2012.9.6
 */
public class ClientClassLoader extends URLClassLoader {

    private List<String> moduleList = new ArrayList<String>();          //  存放模块的集合
    private List<String> componentList = new ArrayList<String>();    //  存放组件的集合
    private List<String[]> actionList = new ArrayList<String[]>();        //  存放操作的Action
    private float fileCount = 0, loaded = 0;                                         //  fileCount : 文件个数, loaded  :  加载进度

    public ClientClassLoader() {
        super(new URL[]{});
        addLibraries();
    }
    
    /**
     * 到用户目录下加载文件
     * 
     * @author zhxu
     * @date  2012.8.6
     */
    private void addLibraries() {
        try {
            String dir = System.getProperty("user.dir");
            File file = new File(dir);
            // 计算用户目录下文件的个数
            calculateFileCount(file);
            // 加载文件
            loadFile(file);
        } catch (Exception ex) {
            Logger.getLogger(ClientClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 计算用户目录下文件的个数
     * 
     * @param file 
     */
    private void calculateFileCount(File file) {
        if (file.isFile()) {
            fileCount++;
        } else {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    calculateFileCount(f);
                }
            }
        }
    }

    /**
     * 加载资源文件。如果是server则提取服务相关信息。
     *
     * @param file 资源文件
     * @throws MalformedURLException 错误的URL
     */
    protected void addFile(File file) throws MalformedURLException {
        loaded++;
        addURL(file.toURI().toURL());
        String message = java.util.ResourceBundle.getBundle("com/keqi/client/launcher/bound").getString("loadResources");
        Launcher.splash((int) (loaded * 100.0 / fileCount), message, 1);
        System.out.println(file.getAbsolutePath());
        if (file.getName().endsWith("jar")) {
            try {
                JarFile jarFile = new JarFile(file);
                ZipEntry entry = jarFile.getEntry("config.xml");
                if (entry != null) {
                    InputStream inputStream = jarFile.getInputStream(entry);
                    parseConfiguration(inputStream);
                }
                //                Attributes attributes = jarFile.getManifest().getMainAttributes();
                //                String ModuleClass = attributes.getValue(new Attributes.Name("ModuleClass"));
                //                String ComponentClass = attributes.getValue(new Attributes.Name("ComponentClass"));
                //                if (ModuleClass != null) {
                //                    moduleList.add(ModuleClass);
                //                }
                //                if (ComponentClass != null) {
                //                    componentList.add(ComponentClass);
                //                }
            } catch (Exception ex) {
                Logger.getLogger(ClientClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * 解析config.xml中的配置信息
     * 
     * @param inputStream 
     */
    public void parseConfiguration(InputStream inputStream) {
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            NodeList modules = document.getElementsByTagName("module");
            for (int i = 0; i < modules.getLength(); i++) {
                Node node = modules.item(i);
                Node attribute = node.getAttributes().getNamedItem("class");
                if (attribute != null) {
                    moduleList.add(attribute.getNodeValue());
                }
            }
            NodeList components = document.getElementsByTagName("component");
            for (int i = 0; i < components.getLength(); i++) {
                Node node = components.item(i);
                Node attribute = node.getAttributes().getNamedItem("class");
                if (attribute != null) {
                    componentList.add(attribute.getNodeValue());
                }
            }
            NodeList actions = document.getElementsByTagName("action");
            for (int i = 0; i < actions.getLength(); i++) {
                Node node = actions.item(i);
                String[] strs = new String[5];
                Node attribute = node.getAttributes().getNamedItem("class");
                if (attribute != null) {
                      strs[0] = attribute.getNodeValue();
                }
                  attribute = node.getAttributes().getNamedItem("type");
                if (attribute != null) {
                      strs[1] = attribute.getNodeValue();
                }
                  attribute = node.getAttributes().getNamedItem("catelog");
                if (attribute != null) {
                      strs[2] = attribute.getNodeValue();
                }
                  attribute = node.getAttributes().getNamedItem("index");
                if (attribute != null) {
                      strs[3] = attribute.getNodeValue();
                }
                  attribute = node.getAttributes().getNamedItem("separator");
                if (attribute != null) {
                      strs[4] = attribute.getNodeValue();
                }
                getActionList().add(strs);
            }
        } catch (Exception ex) {
            Logger.getLogger(ClientClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 开始加载文件
     * 
     * @param file
     * @throws MalformedURLException 
     */
    private void loadFile(File file) throws MalformedURLException {
        if (file.isFile()) {
            // 加载文件
            addFile(file);
        } else {
            // 加载子目录下的文件
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    loadFile(f);
                }
            }
        }
    }

    /**
     * @return the moduleList
     */
    public List<String> getModuleList() {
        return moduleList;
    }

    /**
     * @return the componentList
     */
    public List<String> getComponentList() {
        return componentList;
    }

    /**
     * @return the actionList
     */
    public List<String[]> getActionList() {
        return actionList;
    }
}
mysql tong
个人趋向用第二种,简要说一下操作步骤:
	MySql 同步主端 Master 配置
环境说明:
Master库:
Os:centos 6.8 
Ip:192.168.0.103
		Slave 库:
			Os:centos 6.8
			Ip:192.168.0.104
[root@master mysql]# vim /etc/my.cnf
server-id       = 103 #根据ip来配置
binlog-do-db	  = gpush #主库名
gtid_mode=on                 #开启gtid模式
enforce_gtid_consistency=on  #强制gtid一致性,开启后对于特定create table不被支持
#binlog
log_bin=master-binlog
log-slave-updates=1    
binlog_format=row            #其他格式可能造成数据不一致

#relay log
skip_slave_start=1    
	MySql 同步从端 Slave 配置
参数与上面一样,不同的有
server-id=105
binlog-do-db	  = gpush //从库名
gtid_mode=on
enforce_gtid_consistency=on

#binlog
log-bin=slave-binlog
log-slave-updates=1
binlog_format=row      #其他格式可能造成数据不一致

#relay log
skip_slave_start=1
	执行同步操作相关命令
重启两端服务:Service mysql restart
赋予相关权限:
Mysql>  grant replication slave,replication client on *.* to 'sysdev'@'172.16.%.%' identified by 'sysdev@snda';
Mysql>  flush privileges;

	同步原有的数据
	Master 数据库全局读锁 
Mysql> flush tables with read lock;

	Master 用mysqldump对主数据库进行一次全量数据备份 
	mysqldump -usysdev –psysdev@snda gpush>db.sql;

	导入到Slave库中 
	Mysql> source /home/db.sql

	查看Master 库偏移量 Position
Mysql> show master status

	修改Slave 库信息
Mysql> slave stop ;
Mysql> change master to
 MASTER_HOST=’192.168.0.103’,
 MASTER_USER=’sysdev’,
 MASTER_PASSWORD=’sysdev@snda’,
 MASTER_LOG_FILE=’’,
 MASTER_AUTO_POSITION=1,
 MASTER_RETRY_COUNT=3,
 MASTER_LOG_POS=查询出来的偏移量 position
Mysql> slave start

	配置Mycat 读写分离
Schame.xml 示例 注意 balance="1" writeType="0"
	测试
插入一个测试数据,然后到从库中查看是不是有对应的数据
简单api访问例子
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from urllib import urlencode
import json
import urllib2
import hmac
import time


class GPushSDK:
    def __init__(self, endpoint, app_key, secret_key):
        self.endpoint = endpoint
        self.app_key = app_key
        self.secret_key = secret_key

    def push(self, action, params):
        timestamp = int(time.mktime(datetime.datetime.now().timetuple()))
        params.appKey = self.app_key
        params.timestamp = timestamp
        params.signature = self.hmac(params, self.secret_key)
        body = self.makeBody(params)
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8'
        }
        url = self.endpoint + "/" + action
        response = urllib2.Http().request(url, 'POST', body, headers)
        return json.load(response)

    def hmac(self, params, secret_key):
        content = self.make_message(params)
        return hmac.new(b'' + secret_key).update(b'' + content).hexdigest()

    @classmethod
    def make_message(cls, params):
        array = []
        for entry in params:
            array.append(entry)
        array.sort()
        items = []
        for item in array:
            items.append(item + '=' + params[item])
        return '&'.join(items)

    @classmethod
    def make_body(cls, params):
        array = []
        for entry in params:
            value = urlencode(params[entry].encode('utf-8'))
            array.append(entry + '=' + value)
        return '&'.join(array)


if __name__ == '__main__':
    sdk = GPushSDK('http://www.baidu.com', 'appkey', 'sekey')
    sdk.push('aaa', {'cc': 1, 'bb': 2, 'ab ': 2})
idea maven 配置
-DarchetypeCatalog=internal 

序列号
43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVFbWFpbCI6IiIsImxpY2Vuc2VSZXN0cmljdGlvbiI6IkZvciBlZHVjYXRpb25hbCB1c2Ugb25seSIsImNoZWNrQ29uY3VycmVudFVzZSI6ZmFsc2UsInByb2R1Y3RzIjpbeyJjb2RlIjoiSUkiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJBQyIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IkRQTiIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlBTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiRE0iLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJDTCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJTMCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJDIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiUEMiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJSTSIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IldTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiREIiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJEQyIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9XSwiaGFzaCI6IjMzOTgyOTkvMCIsImdyYWNlUGVyaW9kRGF5cyI6MCwiYXV0b1Byb2xvbmdhdGVkIjpmYWxzZSwiaXNBdXRvUHJvbG9uZ2F0ZWQiOmZhbHNlfQ==-keaxIkRgXPKE4BR/ZTs7s7UkP92LBxRe57HvWamu1EHVXTcV1B4f/KNQIrpOpN6dgpjig5eMVMPmo7yMPl+bmwQ8pTZaCGFuLqCHD1ngo6ywHKIQy0nR249sAUVaCl2wGJwaO4JeOh1opUx8chzSBVRZBMz0/MGyygi7duYAff9JQqfH3p/BhDTNM8eKl6z5tnneZ8ZG5bG1XvqFTqWk4FhGsEWdK7B+He44hPjBxKQl2gmZAodb6g9YxfTHhVRKQY5hQ7KPXNvh3ikerHkoaL5apgsVBZJOTDE2KdYTnGLmqxghFx6L0ofqKI6hMr48ergMyflDk6wLNGWJvYHLWw==-MIIEPjCCAiagAwIBAgIBBTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBMB4XDTE1MTEwMjA4MjE0OFoXDTE4MTEwMTA4MjE0OFowETEPMA0GA1UEAwwGcHJvZDN5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxcQkq+zdxlR2mmRYBPzGbUNdMN6OaXiXzxIWtMEkrJMO/5oUfQJbLLuMSMK0QHFmaI37WShyxZcfRCidwXjot4zmNBKnlyHodDij/78TmVqFl8nOeD5+07B8VEaIu7c3E1N+e1doC6wht4I4+IEmtsPAdoaj5WCQVQbrI8KeT8M9VcBIWX7fD0fhexfg3ZRt0xqwMcXGNp3DdJHiO0rCdU+Itv7EmtnSVq9jBG1usMSFvMowR25mju2JcPFp1+I4ZI+FqgR8gyG8oiNDyNEoAbsR3lOpI7grUYSvkB/xVy/VoklPCK2h0f0GJxFjnye8NT1PAywoyl7RmiAVRE/EKwIDAQABo4GZMIGWMAkGA1UdEwQCMAAwHQYDVR0OBBYEFGEpG9oZGcfLMGNBkY7SgHiMGgTcMEgGA1UdIwRBMD+AFKOetkhnQhI2Qb1t4Lm0oFKLl/GzoRykGjAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBggkA0myxg7KDeeEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCwYDVR0PBAQDAgWgMA0GCSqGSIb3DQEBCwUAA4ICAQC9WZuYgQedSuOc5TOUSrRigMw4/+wuC5EtZBfvdl4HT/8vzMW/oUlIP4YCvA0XKyBaCJ2iX+ZCDKoPfiYXiaSiH+HxAPV6J79vvouxKrWg2XV6ShFtPLP+0gPdGq3x9R3+kJbmAm8w+FOdlWqAfJrLvpzMGNeDU14YGXiZ9bVzmIQbwrBA+c/F4tlK/DV07dsNExihqFoibnqDiVNTGombaU2dDup2gwKdL81ua8EIcGNExHe82kjF4zwfadHk3bQVvbfdAwxcDy4xBjs3L4raPLU3yenSzr/OEur1+jfOxnQSmEcMXKXgrAQ9U55gwjcOFKrgOxEdek/Sk1VfOjvS+nuM4eyEruFMfaZHzoQiuw4IqgGc45ohFH0UUyjYcuFxxDSU9lMCv8qdHKm+wnPRb0l9l5vXsCBDuhAGYD6ss+Ga+aDY6f/qXZuUCEUOH3QUNbbCUlviSz6+GiRnt1kA9N2Qachl+2yBfaqUqr8h7Z2gsx5LcIf5kYNsqJ0GavXTVyWh7PYiKX4bs354ZQLUwwa/cG++2+wNWP+HtBhVxMRNTdVhSm38AknZlD+PTAsWGu9GyLmhti2EnVwGybSD2Dxmhxk3IPCkhKAK+pl0eWYGZWG3tJ9mZ7SowcXLWDFAk0lRJnKGFMTggrWjV8GYpw5bq23VmIqqDLgkNzuoog==




43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVFbWFpbCI6IiIsImxpY2Vuc2VSZXN0cmljdGlvbiI6IkZvciBlZHVjYXRpb25hbCB1c2Ugb25seSIsImNoZWNrQ29uY3VycmVudFVzZSI6ZmFsc2UsInByb2R1Y3RzIjpbeyJjb2RlIjoiSUkiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJBQyIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IkRQTiIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlBTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiRE0iLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJDTCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJTMCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJDIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiUEMiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJSTSIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IldTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiREIiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJEQyIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9XSwiaGFzaCI6IjMzOTgyOTkvMCIsImdyYWNlUGVyaW9kRGF5cyI6MCwiYXV0b1Byb2xvbmdhdGVkIjpmYWxzZSwiaXNBdXRvUHJvbG9uZ2F0ZWQiOmZhbHNlfQ==-keaxIkRgXPKE4BR/ZTs7s7UkP92LBxRe57HvWamu1EHVXTcV1B4f/KNQIrpOpN6dgpjig5eMVMPmo7yMPl+bmwQ8pTZaCGFuLqCHD1ngo6ywHKIQy0nR249sAUVaCl2wGJwaO4JeOh1opUx8chzSBVRZBMz0/MGyygi7duYAff9JQqfH3p/BhDTNM8eKl6z5tnneZ8ZG5bG1XvqFTqWk4FhGsEWdK7B+He44hPjBxKQl2gmZAodb6g9YxfTHhVRKQY5hQ7KPXNvh3ikerHkoaL5apgsVBZJOTDE2KdYTnGLmqxghFx6L0ofqKI6hMr48ergMyflDk6wLNGWJvYHLWw==-MIIEPjCCAiagAwIBAgIBBTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBMB4XDTE1MTEwMjA4MjE0OFoXDTE4MTEwMTA4MjE0OFowETEPMA0GA1UEAwwGcHJvZDN5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxcQkq+zdxlR2mmRYBPzGbUNdMN6OaXiXzxIWtMEkrJMO/5oUfQJbLLuMSMK0QHFmaI37WShyxZcfRCidwXjot4zmNBKnlyHodDij/78TmVqFl8nOeD5+07B8VEaIu7c3E1N+e1doC6wht4I4+IEmtsPAdoaj5WCQVQbrI8KeT8M9VcBIWX7fD0fhexfg3ZRt0xqwMcXGNp3DdJHiO0rCdU+Itv7EmtnSVq9jBG1usMSFvMowR25mju2JcPFp1+I4ZI+FqgR8gyG8oiNDyNEoAbsR3lOpI7grUYSvkB/xVy/VoklPCK2h0f0GJxFjnye8NT1PAywoyl7RmiAVRE/EKwIDAQABo4GZMIGWMAkGA1UdEwQCMAAwHQYDVR0OBBYEFGEpG9oZGcfLMGNBkY7SgHiMGgTcMEgGA1UdIwRBMD+AFKOetkhnQhI2Qb1t4Lm0oFKLl/GzoRykGjAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBggkA0myxg7KDeeEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCwYDVR0PBAQDAgWgMA0GCSqGSIb3DQEBCwUAA4ICAQC9WZuYgQedSuOc5TOUSrRigMw4/+wuC5EtZBfvdl4HT/8vzMW/oUlIP4YCvA0XKyBaCJ2iX+ZCDKoPfiYXiaSiH+HxAPV6J79vvouxKrWg2XV6ShFtPLP+0gPdGq3x9R3+kJbmAm8w+FOdlWqAfJrLvpzMGNeDU14YGXiZ9bVzmIQbwrBA+c/F4tlK/DV07dsNExihqFoibnqDiVNTGombaU2dDup2gwKdL81ua8EIcGNExHe82kjF4zwfadHk3bQVvbfdAwxcDy4xBjs3L4raPLU3yenSzr/OEur1+jfOxnQSmEcMXKXgrAQ9U55gwjcOFKrgOxEdek/Sk1VfOjvS+nuM4eyEruFMfaZHzoQiuw4IqgGc45ohFH0UUyjYcuFxxDSU9lMCv8qdHKm+wnPRb0l9l5vXsCBDuhAGYD6ss+Ga+aDY6f/qXZuUCEUOH3QUNbbCUlviSz6+GiRnt1kA9N2Qachl+2yBfaqUqr8h7Z2gsx5LcIf5kYNsqJ0GavXTVyWh7PYiKX4bs354ZQLUwwa/cG++2+wNWP+HtBhVxMRNTdVhSm38AknZlD+PTAsWGu9GyLmhti2EnVwGybSD2Dxmhxk3IPCkhKAK+pl0eWYGZWG3tJ9mZ7SowcXLWDFAk0lRJnKGFMTggrWjV8GYpw5bq23VmIqqDLgkNzuoog==


npm taobao: npm install --registry=https://registry.npm.taobao.org
项目需求
1.设备列表
	查询设备
2.通道管理
	增删改查通道
3.文件管理
	添加,删除,复制,移动,下发文件
4.执行命令
	执行指定类型的命令,并对执行结果进行管理,失败可以重新执行,执行过程中还可以取消
5.项目管理
	项目列表,指定发布服务器列表,
	项目部署:
		> 编译并发布项目:
			1.根据版本管理和密码,获得项目,根据构建类型进行编译
			2.复制所有的路径到指定位置
			3.分发给服务器,
			4.删除临时目录
		> 部署项目:
			1.设置好配置文件
			2.设置好部署命令列表
			3.位每一个生成路径,指定好下发位置,位置必须制定好服务器
			4.执行部署
			5.发送邮箱通知,和短信通知,项目已经部署
6.系统管理
	用户管理
	权限管理
	资源控制
	通道控制
	邮件设置
-----------------
设备管理需求:
1.机房管理
	机房基本属性:机房名称,地点,负责人,联系方式,邮件
2.设备管理
	设备基础属性:增加机房,秘钥
3.秘钥管理
	秘钥管理:用户,秘钥:有两种类型:密码和key ,目前只支持密码
-----------------
项目管理需求:
1.项目关键属性
	编号,名称,责任人,手机,邮箱,
	项目类型(枚举,目前是有java) ,版本管理工具(枚举:svn ,git ,无),编译工具(ant,maven,gradle)
	项目地址:url 或者项目根路径 ,用户名,密码 (用户密码是用来做项目签出)
	---
	生成路径: 项目生成的路径,整个目录或者一个文件 ,考虑现在都是模块化,这里设为可以添加多个路径
2.功能,添加项目,编辑项目,删除项目,提供项目接口,方便中心平台获取
---------------
公司人员管理系统
1.人员信息管理,
	录入信息,申请账号,删除信息。
	基本属性:
		员工编号,名称,名字拼音,性别,年龄,邮件,电话 
2.提供查询接口,根据名称查询,根据员工编号查询
mysql 5.6 密码问题
作者:唐植超
时间:2106/5/25

实验环境:centos 6.7 mysql 5.7
出现问题:
	1.安装完成以后 输入:mysql -u root -p  提示错误
		ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
	2.输入: mysqladmin -u root password 'newpassword'
		mysqladmin: connect to server at 'localhost' failed
		error: 'Access denied for user 'root'@'localhost' (using password: YES)' 
解决办法:
	使用 --skip-grant-tables
	1.停止mysql:/etc/init.d/mysqld stop 
	2.执行命令:mysqld_safe --skip-grant-tables --skip-networking &
	3.输入命令: mysql -u root mysql 
	4.修改密码:update mysql.user set authentication_string=password('T_pass123') where user='root' and Host = 'localhost';
	5.刷新权限:FLUSH PRIVILEGES; 
	6.退出: quit;
	7.重启mysql服务:/etc/init.d/mysqld restart
	8.登录:mysql -uroot -pT_pass123 mysql
	----------------

再次登录以后,输入命令:show databases;
出现新问题:ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
	这是要我重置密码才能操作啊,于是乎,我退出:quit;
	重新:mysqladmin -u root password 'newpassword' ,结果报错。
	需要这样:
	1.登录数据库
	2.先随便重置一个密码:SET PASSWORD = PASSWORD('123456'); 
	  结果又错了:ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
	  说 你的密码不安全
	3.我换个密码重新执行:SET PASSWORD = PASSWORD('T_test123');
	4.执行成功

5.7的数据库 user 表好像跟以前不一样了,没有password 字段了
	 
	
Netbeans清理
C:\Users\Administrator\AppData\Local\NetBeans
C:\Users\Administrator\AppData\Roaming\NetBeans
C:\Users\Administrator\.nbi
C:\Users\Administrator\.netbeans-derby
安装目录 nb\var\log

http://www.lagou.com/gongsi/j27061.html
http://www.lagou.com/gongsi/j81491.html
http://www.bilibili.com/html/join-list.html

netbeans maven 下载问题
<repositories>
    <repository>
      <id>repository.jboss.org</id>
      <url>http://repository.jboss.org/maven2</url>
    </repository>
    ...
  </repositories>


SecureCRT

模式的JFrame 调用,可能还可以改进一下
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.swing.JFrame;

// @author Santhosh Kumar T - santhosh@in.fiorano.com 
public class ModalFrameUtil {

    static class EventPump implements InvocationHandler {

        Frame frame;

        public EventPump(Frame frame) {
            this.frame = frame;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return frame.isShowing();
        }

        // when the reflection calls in this method has to be
        // replaced once Sun provides a public API to pump events.
        public void start() throws Exception {
            Class<?> clazz = Class.forName("java.awt.Conditional");
            Object conditional = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz},
                    this);
            Method pumpMethod = Class.forName("java.awt.EventDispatchThread").getDeclaredMethod(
                    "pumpEvents", new Class[]{clazz});
            pumpMethod.setAccessible(true);
            pumpMethod.invoke(Thread.currentThread(), new Object[]{conditional});
        }
    }

    // show the given frame as modal to the specified owner.
    // NOTE: this method returns only after the modal frame is closed.
    public static void showAsModal(final Frame frame, final Frame owner) {
        frame.addWindowListener(new WindowAdapter() {
            public void windowOpened(WindowEvent e) {
                owner.setEnabled(false);
            }

            public void windowClosing(WindowEvent e) {
                owner.setEnabled(true);
                frame.removeWindowListener(this);
            }

            public void windowClosed(WindowEvent e) {
                owner.setEnabled(true);
                frame.removeWindowListener(this);
            }
        });

        owner.addWindowListener(new WindowAdapter() {
            public void windowActivated(WindowEvent e) {
                if (frame.isShowing()) {
                    frame.setExtendedState(JFrame.NORMAL);
                    frame.toFront();
                } else {
                    owner.removeWindowListener(this);
                }
            }
        });

        frame.setVisible(true);
        try {
            new EventPump(frame).start();
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
windows设置时间服务器
@echo off
::设置时间服务器
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers /v 0 /t REG_SZ /d %1 /f
@echo off
::W32time 时间服务器
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v NtpServer /t REG_SZ /d %1 /f
::设置为同步
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /t REG_SZ /d NTP /f
@echo off
::同步间隔时间
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient /v SpecialPollInterval /t REG_DWORD /d %2 /f
@echo off
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time /v Start /t REG_DWORD /d 2 /f
@echo off
::设置刚刚添加的项为默认项
REG ADD HKEY_LoCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\DATETIME\SERVERS\ /t REG_SZ /d 0 /f
@echo off
net time /setsntp:%1

net time \\%1 /set /yes

net stop w32time

net start w32time

w32tm /config /manualpeerlist:%1 /reliable:yes /update

w32tm /resync

---禁用
@echo off
::W32time 时间服务器
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v NtpServer /t REG_SZ /d %1 /f
::W32time 设置为不同步
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /t REG_SZ /d NoSync /f
@echo off
::同步间隔时间
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient /v SpecialPollInterval /t REG_DWORD /d %2 /f
@echo off
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time /v Start /t REG_DWORD /d 2 /f
@echo off
::设置默认项
REG ADD HKEY_LoCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\DATETIME\SERVERS\ /t REG_SZ /d %3 /f
单元格合并
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.keqi.pducenter.gui.xcomp;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author zctang
 * @date 2014-9-1 17:21:41
 */
public class GridBagTable extends JTable {

    GridBagModel gridBagModel;

    public GridBagModel getGridBagModel() {
        return gridBagModel;
    }

    public void setGridBagModel(GridBagModel gridBagModel) {
        if (gridBagModel != null && gridBagModel != this.gridBagModel) {
            this.gridBagModel = gridBagModel;
        }
    }

    public GridBagTable(AbstractTableModel dm) {
        super(dm);
        getTableHeader().setReorderingAllowed(false);
        gridBagModel = new DefaultGridBagTableModel(dm);
        getColumnModel().setColumnSelectionAllowed(true);
    }

    private void updateSubComponentUI(Object componentShell) {
        if (componentShell == null) {
            return;
        }
        Component component = null;
        if (componentShell instanceof Component) {
            component = (Component) componentShell;
        }
        if (componentShell instanceof DefaultCellEditor) {
            component = ((DefaultCellEditor) componentShell).getComponent();
        }

        if (component != null) {
            SwingUtilities.updateComponentTreeUI(component);
        }
    }

    public void updateUI() {
        // Update the UIs of the cell renderers, cell editors and header renderers.  
        TableColumnModel cm = getColumnModel();
        for (int column = 0; column < cm.getColumnCount(); column++) {
            TableColumn aColumn = cm.getColumn(column);
            updateSubComponentUI(aColumn.getCellRenderer());
            updateSubComponentUI(aColumn.getCellEditor());
            updateSubComponentUI(aColumn.getHeaderRenderer());
        }

        // Update the UIs of all the default renderers.  
        Enumeration defaultRenderers = defaultRenderersByColumnClass.elements();
        while (defaultRenderers.hasMoreElements()) {
            updateSubComponentUI(defaultRenderers.nextElement());
        }

        // Update the UIs of all the default editors.  
        Enumeration defaultEditors = defaultEditorsByColumnClass.elements();
        while (defaultEditors.hasMoreElements()) {
            updateSubComponentUI(defaultEditors.nextElement());
        }

        // Update the UI of the table header  
        if (tableHeader != null && tableHeader.getParent() == null) {
            tableHeader.updateUI();
        }
        setUI(new GridBagTableUI());
    }

    public Rectangle getGridCellRect(int row, int column, boolean includeSpacing) {
        return super.getCellRect(row, column, includeSpacing);
    }

    public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
        Rectangle cellRect = super.getCellRect(row, column, includeSpacing);
        int cols = gridBagModel.getColumnGrid(row, column);
        TableColumnModel cm = getColumnModel();
        for (int n = 1; n < cols; n++) {
            cellRect.width += cm.getColumn(column + n).getWidth();
        }
        int rows = gridBagModel.getRowGrid(row, column);
        for (int n = 1; n < rows; n++) {
            cellRect.height += getRowHeight(row + n);
        }
        return cellRect;
    }

    public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        //TODO  
    }

    public boolean mergeCells(int startRow, int endRow, int startColumn, int endColumn) {
        if (gridBagModel.mergeCells(startRow, endRow, startColumn, endColumn)) {
            repaint();
            return true;
        }
        return false;
    }

    public boolean mergeCells(int[] rows, int[] columns) {
        if (gridBagModel.mergeCells(rows, columns)) {
            repaint();
            return true;
        }
        return false;
    }

    public boolean spliteCellAt(int row, int column) {
        if (gridBagModel.spliteCellAt(row, column)) {
            repaint();
            return true;
        }
        return false;
    }

    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
        if (gridBagModel.getCellState(rowIndex, columnIndex) != GridBagModel.COVERED) {
            super.changeSelection(rowIndex, columnIndex, toggle, extend);
        }
        Point p;
        for (int row = rowIndex; row >= 0; row--) {
            for (int col = columnIndex; col >= 0; col--) {
                p = gridBagModel.getGrid(row, col);
                //p = ((Point)((Vector)rowVector.get(row)).get(col));  
                if (col + p.x > columnIndex && row + p.y > rowIndex) {
                    rowIndex = row;
                    columnIndex = col;
                    break;
                }
            }
        }
        super.changeSelection(rowIndex, columnIndex, toggle, extend);
        repaint();
    }

    public boolean editCellAt(int rowIndex, int columnIndex, EventObject e) {
        if (gridBagModel.getCellState(rowIndex, columnIndex) != GridBagModel.COVERED) {
            return super.editCellAt(rowIndex, columnIndex, e);
        }
        Point p;
        for (int row = rowIndex; row >= 0; row--) {
            for (int col = columnIndex; col >= 0; col--) {
                p = gridBagModel.getGrid(row, col);
                if (col + p.x > columnIndex && row + p.y > rowIndex) {
                    rowIndex = row;
                    columnIndex = col;
                    break;
                }
            }
        }
        return super.editCellAt(rowIndex, columnIndex, e);
    }

    interface GridBagModel {

        //格子处于正常状态
        int DEFAULT = 0;
        //格子合并了其他的格子
        int MERGE = 1;
        //格子被其他格子合并
        int COVERED = -1;

        /**
         * @param row 行
         * @param column 列
         * @return 该单元格在行、列的跨度
         */
        Point getGrid(int row, int column);

        /**
         * 在Y轴方向的跨度
         *
         * @param row
         * @param column
         * @return
         */
        int getRowGrid(int row, int column);

        /**
         * 在X轴方向的跨度
         *
         * @param row
         * @param column
         * @return
         */
        int getColumnGrid(int row, int column);

        /**
         * @param rows 行集合
         * @param columns 列集合
         * @return 单元格集合是否可以合并在一起
         */
        boolean canMergeCells(int[] rows, int[] columns);

        /**
         * 判断该单元格状态
         *
         * @param row
         * @param column
         * @return MERGE|DEFAULT|COVERED
         */
        int getCellState(int row, int column);

        /**
         * 将单元格集合合并
         *
         * @param startRow 开始行
         * @param endRow 结束行
         * @param startColumn 开始列
         * @param endColumn 结束列
         * @return 是否合并成功
         */
        boolean mergeCells(int startRow, int endRow, int startColumn, int endColumn);

        /**
         * 将单元格集合合并
         *
         * @param rows 行集合
         * @param columns 列集合
         * @return 是否合并成功
         */
        boolean mergeCells(int[] rows, int[] columns);

        /**
         * 拆分单元格
         *
         * @param row 行
         * @param column 列
         * @return 是否拆分成功
         */
        boolean spliteCellAt(int row, int column);

        /**
         * 清除 所有合并
         */
        void clearMergence();
    }

    class DefaultGridBagTableModel implements GridBagModel, TableModelListener {

        protected AbstractTableModel model;
        protected List<List<Point>> gridInfo;

        DefaultGridBagTableModel(AbstractTableModel model) {
            gridInfo = new Vector<List<Point>>();
            setTableModel(model);
        }

        public void setTableModel(AbstractTableModel model) {
            if (model != null && model != this.model) {
                if (this.model != null) {
                    this.model.removeTableModelListener(this);
                }
                //防止多次添加监听器
                model.removeTableModelListener(this);
                model.addTableModelListener(this);
                this.model = model;
                clearMergence();
            }
        }

        public void clearMergence() {
            if (gridInfo == null) {
                gridInfo = new Vector<List<Point>>();
            } else {
                gridInfo.clear();
            }

            if (model == null) {
                return;
            }

            //初始化,每个格子占的格子数为(1,1);
            for (int row = model.getRowCount(); --row >= 0;) {
                List<Point> infos = new Vector<Point>();
                gridInfo.add(infos);
                for (int col = model.getColumnCount(); --col >= 0;) {
                    infos.add(getDefaultPoint());
                }
            }
        }

        public Point getDefaultPoint() {
            return new Point(1, 1);
        }

        @Override
        public boolean canMergeCells(int[] rows, int[] columns) {
            if (rows == null || columns == null) {
                return false;
            }
            Arrays.sort(rows);
            for (int index = 0; index < rows.length - 1; index++) {
                if (rows[index + 1] - rows[index] > 1) {
                    return false;
                }
            }
            Arrays.sort(columns);
            for (int index = 0; index < columns.length - 1; index++) {
                if (columns[index + 1] - columns[index] > 1) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public int getCellState(int row, int column) {
            Point grid = getGrid(row, column);
            if (grid == null) {
                return DEFAULT;
            }
            if (grid.x > 1 || grid.y > 1) {
                return MERGE;
            }
            if (grid.x <= 0 || grid.y <= 0) {
                return COVERED;
            }
            return DEFAULT;
        }

        @Override
        public int getColumnGrid(int row, int column) {
            if (gridInfo != null && row >= 0 && row < gridInfo.size()) {
                List<Point> gridRow = gridInfo.get(row);
                if (gridRow != null && column >= 0 && column < gridRow.size()) {
                    Point point = gridRow.get(column);
                    if (point != null) {
                        return point.x;
                    }
                }
            }
            return 1;
        }

        @Override
        public Point getGrid(int row, int column) {
            if (gridInfo != null && row >= 0 && row < gridInfo.size()) {
                List<Point> gridRow = gridInfo.get(row);
                if (gridRow != null && column >= 0 && column < gridRow.size()) {
                    return gridRow.get(column);
                }
            }
            return getDefaultPoint();
        }

        @Override
        public int getRowGrid(int row, int column) {
            if (gridInfo != null && row >= 0 && row < gridInfo.size()) {
                List<Point> gridRow = gridInfo.get(row);
                if (gridRow != null && column >= 0 && column < gridRow.size()) {
                    Point point = gridRow.get(column);
                    if (point != null) {
                        return point.y;
                    }
                }
            }
            return 1;
        }

        protected boolean setGrid(int row, int column, Point grid) {
            if (gridInfo != null && row >= 0 && row < gridInfo.size()) {
                List<Point> gridRow = gridInfo.get(row);
                if (gridRow != null && column >= 0 && column < gridRow.size()) {
                    Point point = gridRow.get(column);
                    if (point != null) {
                        point.setLocation(grid);
                    } else {
                        gridRow.set(column, grid.getLocation());
                    }
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean spliteCellAt(int row, int column) {
            if (gridInfo != null && row >= 0 && row < gridInfo.size()) {
                List<Point> gridRow = gridInfo.get(row);
                if (gridRow != null && column >= 0 && column < gridRow.size()) {
                    Point point = gridRow.get(column);
                    if (point != null) {
                        point = point.getLocation();
                        for (int a = 0; a < point.y; a++) {
                            for (int b = 0; b < point.x; b++) {
                                setGrid(row + a, column + b, getDefaultPoint());
                            }
                        }
                    } else {
                        gridRow.set(column, getDefaultPoint());
                    }
                    return true;
                }
            }
            return false;
        }

        @Override
        /**
         * table中发生行的添加和删除的时候需要修改该模型
         */
        public void tableChanged(TableModelEvent e) {
            //TODO
        }

        @Override
        public boolean mergeCells(int[] rows, int[] columns) {
            if (!canMergeCells(rows, columns)) {
                return false;
            }
            Arrays.sort(rows);
            Arrays.sort(columns);
            return mergeCells(rows[0], rows[rows.length - 1], columns[0], columns[columns.length - 1]);
        }

        @Override
        public boolean mergeCells(int startRow, int endRow, int startColumn, int endColumn) {
            setGrid(startRow, startColumn, new Point(endColumn - startColumn + 1, endRow - startRow + 1));
            for (int row = startRow; row <= endRow; row++) {
                for (int col = startColumn; col <= endColumn; col++) {
                    if (row == startRow && col == startColumn) {
                        continue;
                    } else {
                        setGrid(row, col, new Point(COVERED, COVERED));
                    }
                }
            }
            return true;
        }

        public String toString() {
            if (gridInfo == null) {
                return "";
            }
            StringBuffer sb = new StringBuffer();
            for (List<Point> rowInfo : gridInfo) {
                for (Point grid : rowInfo) {
                    sb.append("[" + grid.x + "," + grid.y + "], ");
                }
                sb.append("\n");
            }
            return sb.toString();
        }
    }

    public class GridBagTableUI extends BasicTableUI {

        public Dimension getPreferredSize(JComponent c) {
            long width = 0;
            Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
            while (enumeration.hasMoreElements()) {
                TableColumn aColumn = (TableColumn) enumeration.nextElement();
                width = width + aColumn.getPreferredWidth();
            }
            return createTableSize(width);
        }

        private Dimension createTableSize(long width) {
            int height = 0;
            int rowCount = table.getRowCount();
            if (rowCount > 0 && table.getColumnCount() > 0) {
                Rectangle r = table.getCellRect(rowCount - 1, 0, true);
                height = r.y + r.height;
            }
            // Width is always positive. The call to abs() is a workaround for
            // a bug in the 1.1.6 JIT on Windows.
            long tmp = Math.abs(width);
            if (tmp > Integer.MAX_VALUE) {
                tmp = Integer.MAX_VALUE;
            }
            return new Dimension((int) tmp, height);
        }

        public void paint(Graphics g, JComponent c) {
            Rectangle clip = g.getClipBounds();

            Rectangle bounds = table.getBounds();
            // account for the fact that the graphics has already been translated
            // into the table's bounds
            bounds.x = bounds.y = 0;

            if (table.getRowCount() <= 0 || table.getColumnCount() <= 0
                    || // this check prevents us from painting the entire table
                    // when the clip doesn't intersect our bounds at all
                    !bounds.intersects(clip)) {

                paintDropLines(g);
                return;
            }

            boolean ltr = table.getComponentOrientation().isLeftToRight();

            Point upperLeft = clip.getLocation();
            if (!ltr) {
                upperLeft.x++;
            }

            Point lowerRight = new Point(clip.x + clip.width - (ltr ? 1 : 0),
                    clip.y + clip.height);

            int rMin = table.rowAtPoint(upperLeft);
            int rMax = table.rowAtPoint(lowerRight);
            // This should never happen (as long as our bounds intersect the clip,
            // which is why we bail above if that is the case).
            if (rMin == -1) {
                rMin = 0;
            }
            // If the table does not have enough rows to fill the view we'll get -1.
            // (We could also get -1 if our bounds don't intersect the clip,
            // which is why we bail above if that is the case).
            // Replace this with the index of the last row.
            if (rMax == -1) {
                rMax = table.getRowCount() - 1;
            }

            int cMin = table.columnAtPoint(ltr ? upperLeft : lowerRight);
            int cMax = table.columnAtPoint(ltr ? lowerRight : upperLeft);
            // This should never happen.
            if (cMin == -1) {
                cMin = 0;
            }
            // If the table does not have enough columns to fill the view we'll get -1.
            // Replace this with the index of the last column.
            if (cMax == -1) {
                cMax = table.getColumnCount() - 1;
            }

            // Paint the grid.
            //paintGrid(g, rMin, rMax, cMin, cMax);

            // Paint the cells.
            paintCells(g, rMin, rMax, cMin, cMax);

            paintDropLines(g);
        }

        private void paintDropLines(Graphics g) {
            JTable.DropLocation loc = table.getDropLocation();
            if (loc == null) {
                return;
            }

            Color color = UIManager.getColor("Table.dropLineColor");
            Color shortColor = UIManager.getColor("Table.dropLineShortColor");
            if (color == null && shortColor == null) {
                return;
            }

            Rectangle rect;

            rect = getHDropLineRect(loc);
            if (rect != null) {
                int x = rect.x;
                int w = rect.width;
                if (color != null) {
                    extendRect(rect, true);
                    g.setColor(color);
                    g.fillRect(rect.x, rect.y, rect.width, rect.height);
                }
                if (!loc.isInsertColumn() && shortColor != null) {
                    g.setColor(shortColor);
                    g.fillRect(x, rect.y, w, rect.height);
                }
            }

            rect = getVDropLineRect(loc);
            if (rect != null) {
                int y = rect.y;
                int h = rect.height;
                if (color != null) {
                    extendRect(rect, false);
                    g.setColor(color);
                    g.fillRect(rect.x, rect.y, rect.width, rect.height);
                }
                if (!loc.isInsertRow() && shortColor != null) {
                    g.setColor(shortColor);
                    g.fillRect(rect.x, y, rect.width, h);
                }
            }
        }

        /*
         * Paints the grid lines within <I>aRect</I>, using the grid
         * color set with <I>setGridColor</I>. Paints vertical lines
         * if <code>getShowVerticalLines()</code> returns true and paints
         * horizontal lines if <code>getShowHorizontalLines()</code>
         * returns true.
         */
        private void paintGrid(Graphics g, int rMin, int rMax, int cMin, int cMax) {
            g.setColor(table.getGridColor());

            Rectangle minCell = table.getCellRect(rMin, cMin, true);
            Rectangle maxCell = table.getCellRect(rMax, cMax, true);
            Rectangle damagedArea = minCell.union(maxCell);

            if (table.getShowHorizontalLines()) {
                int tableWidth = damagedArea.x + damagedArea.width;
                int y = damagedArea.y;
                for (int row = rMin; row <= rMax; row++) {
                    y += table.getRowHeight(row);
                    g.drawLine(damagedArea.x, y - 1, tableWidth - 1, y - 1);
                }
            }
            if (table.getShowVerticalLines()) {
                TableColumnModel cm = table.getColumnModel();
                int tableHeight = damagedArea.y + damagedArea.height;
                int x;
                if (table.getComponentOrientation().isLeftToRight()) {
                    x = damagedArea.x;
                    for (int column = cMin; column <= cMax; column++) {
                        int w = cm.getColumn(column).getWidth();
                        x += w;
                        g.drawLine(x - 1, 0, x - 1, tableHeight - 1);
                    }
                } else {
                    x = damagedArea.x;
                    for (int column = cMax; column >= cMin; column--) {
                        int w = cm.getColumn(column).getWidth();
                        x += w;
                        g.drawLine(x - 1, 0, x - 1, tableHeight - 1);
                    }
                }
            }
        }

        private void paintCells(Graphics g, int rMin, int rMax, int cMin, int cMax) {
            JTableHeader header = table.getTableHeader();
            TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn();

            TableColumnModel cm = table.getColumnModel();
            int columnMargin = cm.getColumnMargin();
            Rectangle cellRect;
            TableColumn aColumn;
            int columnWidth;
            if (table.getComponentOrientation().isLeftToRight()) {
                for (int row = rMin; row <= rMax; row++) {
                    if (table instanceof GridBagTable) {
                        cellRect = ((GridBagTable) table).getGridCellRect(row, cMin, false);
                    } else {
                        cellRect = table.getCellRect(row, cMin, false);
                    }
                    for (int column = cMin; column <= cMax; column++) {
                        aColumn = cm.getColumn(column);
                        columnWidth = aColumn.getWidth();
                        //TODO
                        cellRect.width = columnWidth - columnMargin;
                        int oldHeight = cellRect.height;
                        if (table instanceof GridBagTable) {
                            if (((GridBagTable) table).getGridBagModel().getCellState(row, column) == GridBagModel.COVERED) {
                                cellRect.width = 0;
                                cellRect.height = 0;
                            } else {
                                int h = ((GridBagTable) table).getGridBagModel().getColumnGrid(row, column);
                                if (h > 1) {
                                    for (int n = 1; n < h; n++) {
                                        cellRect.width += cm.getColumn(column + n).getWidth();
                                    }
                                }
                                int v = ((GridBagTable) table).getGridBagModel().getRowGrid(row, column);
                                if (v > 1) {
                                    for (int n = 1; n < v; n++) {
                                        cellRect.height += table.getRowHeight(row + n);
                                    }
                                }
                            }
                        }
                        if (aColumn != draggedColumn) {
                            paintCell(g, cellRect, row, column);
                        }
                        cellRect.height = oldHeight;
                        cellRect.x += columnWidth;
                    }
                }
            } else {
                for (int row = rMin; row <= rMax; row++) {
                    cellRect = table.getCellRect(row, cMin, false);
                    aColumn = cm.getColumn(cMin);
                    if (aColumn != draggedColumn) {
                        columnWidth = aColumn.getWidth();
                        cellRect.width = columnWidth - columnMargin;
                        paintCell(g, cellRect, row, cMin);
                    }
                    for (int column = cMin + 1; column <= cMax; column++) {
                        aColumn = cm.getColumn(column);
                        columnWidth = aColumn.getWidth();
//                      TODO
                        cellRect.width = columnWidth - columnMargin;
                        cellRect.x -= columnWidth;
                        if (aColumn != draggedColumn) {
                            paintCell(g, cellRect, row, column);
                        }
                    }
                }
            }

            // Paint the dragged column if we are dragging.
            if (draggedColumn != null) {
                paintDraggedArea(g, rMin, rMax, draggedColumn, header.getDraggedDistance());
            }

            // Remove any renderers that may be left in the rendererPane.
            rendererPane.removeAll();
        }

        private void paintCell(Graphics g, Rectangle cellRect, int row, int column) {
            if (table.isEditing() && table.getEditingRow() == row
                    && table.getEditingColumn() == column) {
                Component component = table.getEditorComponent();
                component.setBounds(cellRect);
                component.validate();
            } else {
                TableCellRenderer renderer = table.getCellRenderer(row, column);
                Component component = table.prepareRenderer(renderer, row, column);

                if (component instanceof JComponent) {
                    ((JComponent) component).setBorder(BorderFactory.createLineBorder(Color.gray));
                }
                rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y,
                        cellRect.width, cellRect.height, true);
            }
        }

        private Rectangle getHDropLineRect(JTable.DropLocation loc) {
            if (!loc.isInsertRow()) {
                return null;
            }

            int row = loc.getRow();
            int col = loc.getColumn();
            if (col >= table.getColumnCount()) {
                col--;
            }

            Rectangle rect = table.getCellRect(row, col, true);

            if (row >= table.getRowCount()) {
                row--;
                Rectangle prevRect = table.getCellRect(row, col, true);
                rect.y = prevRect.y + prevRect.height;
            }

            if (rect.y == 0) {
                rect.y = -1;
            } else {
                rect.y -= 2;
            }

            rect.height = 3;

            return rect;
        }

        private void paintDraggedArea(Graphics g, int rMin, int rMax, TableColumn draggedColumn, int distance) {
            int draggedColumnIndex = viewIndexForColumn(draggedColumn);

            Rectangle minCell = table.getCellRect(rMin, draggedColumnIndex, true);
            Rectangle maxCell = table.getCellRect(rMax, draggedColumnIndex, true);

            Rectangle vacatedColumnRect = minCell.union(maxCell);

            // Paint a gray well in place of the moving column.
            g.setColor(table.getParent().getBackground());
            g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y,
                    vacatedColumnRect.width, vacatedColumnRect.height);

            // Move to the where the cell has been dragged.
            vacatedColumnRect.x += distance;

            // Fill the background.
            g.setColor(table.getBackground());
            g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y,
                    vacatedColumnRect.width, vacatedColumnRect.height);

            // Paint the vertical grid lines if necessary.
            if (table.getShowVerticalLines()) {
                g.setColor(table.getGridColor());
                int x1 = vacatedColumnRect.x;
                int y1 = vacatedColumnRect.y;
                int x2 = x1 + vacatedColumnRect.width - 1;
                int y2 = y1 + vacatedColumnRect.height - 1;
                // Left
                g.drawLine(x1 - 1, y1, x1 - 1, y2);
                // Right
                g.drawLine(x2, y1, x2, y2);
            }

            for (int row = rMin; row <= rMax; row++) {
                // Render the cell value
                Rectangle r = table.getCellRect(row, draggedColumnIndex, false);
                r.x += distance;
                paintCell(g, r, row, draggedColumnIndex);

                // Paint the (lower) horizontal grid line if necessary.
                if (table.getShowHorizontalLines()) {
                    g.setColor(table.getGridColor());
                    Rectangle rcr = table.getCellRect(row, draggedColumnIndex, true);
                    rcr.x += distance;
                    int x1 = rcr.x;
                    int y1 = rcr.y;
                    int x2 = x1 + rcr.width - 1;
                    int y2 = y1 + rcr.height - 1;
                    g.drawLine(x1, y2, x2, y2);
                }
            }
        }

        private int viewIndexForColumn(TableColumn aColumn) {
            TableColumnModel cm = table.getColumnModel();
            for (int column = 0; column < cm.getColumnCount(); column++) {
                if (cm.getColumn(column) == aColumn) {
                    return column;
                }
            }
            return -1;
        }

        private Rectangle extendRect(Rectangle rect, boolean horizontal) {
            if (rect == null) {
                return rect;
            }

            if (horizontal) {
                rect.x = 0;
                rect.width = table.getWidth();
            } else {
                rect.y = 0;

                if (table.getRowCount() != 0) {
                    Rectangle lastRect = table.getCellRect(table.getRowCount() - 1, 0, true);
                    rect.height = lastRect.y + lastRect.height;
                } else {
                    rect.height = table.getHeight();
                }
            }

            return rect;
        }

        private Rectangle getVDropLineRect(JTable.DropLocation loc) {
            if (!loc.isInsertColumn()) {
                return null;
            }

            boolean ltr = table.getComponentOrientation().isLeftToRight();
            int col = loc.getColumn();
            Rectangle rect = table.getCellRect(loc.getRow(), col, true);

            if (col >= table.getColumnCount()) {
                col--;
                rect = table.getCellRect(loc.getRow(), col, true);
                if (ltr) {
                    rect.x = rect.x + rect.width;
                }
            } else if (!ltr) {
                rect.x = rect.x + rect.width;
            }

            if (rect.x == 0) {
                rect.x = -1;
            } else {
                rect.x -= 2;
            }

            rect.width = 3;

            return rect;
        }
    }  // End of Class BasicTableUI
}
生成红包
import java.text.NumberFormat;

/**
 * 功能:<br>
 * a、将50万元的话费随机生成10万个红包,每个在0.5元-99.99元之间。<br>
 * b、将10万个红包划分为10等份,每份为1万个,话费总额约等于5万元。<br>
 * c、将红包固定顺序,按客户刮卡的时间顺序发送红包。<br>
 * 作者: mhpi <br>
 * 公司: 深讯信科 <br>
 * 日期: 2014-5-12 <br>
 */
public class RandomNumber {
	/** 总额 */
	private static final double TOTAL_NUM = 50000;
	/** 份数 */
	private static final int SIZE = 10000;
	/** 最小面额 */
	private static final double MIN = 0.5;
	/** 最大面额 */
	private static final double MAX = 99.99;
	/** 每批生成面额数 */
	private static final int STEP = 50;
	
	private static NumberFormat numFormat = NumberFormat.getNumberInstance();
	
	/**
	 * 获取礼包列表
	 * 
	 * @return
	 */
	public static void getPacks() {
		// 平均面额
		double avg_val = TOTAL_NUM / SIZE;
		// 实际汇总
		double real_sum = 0;
		// 保存面额的集合
		double[] packs = new double[SIZE];
		// 批数
		int step_count = SIZE / STEP;
		
		for (int i = 0; i < step_count; i++) {
			// 每批总额
			double step_total = avg_val * STEP;
			for (int j = 0; j < STEP - 1; j++) {
				double ran;
				while (true) {
					ran = getRandomDouble();
					if (step_total - ran > 0 && (step_total - ran) / (STEP - j) < MAX && (step_total - ran) / (STEP - j) > MIN) {
						break;
					}
				}
				packs[i * STEP + j] = ran;
				step_total -= ran;
				
				System.out.println(i * STEP + j + " : " + packs[i * STEP + j]);
			}
			if (step_total > MAX) {
				double sale_val = step_total - MAX;
				double sale_avg_val = sale_val / STEP;
				
				for (int k = 0; k < i * STEP; k++) {
					// double tmp = MAX - packs[k];
					if (packs[k] + sale_avg_val <= MAX) {
						packs[k] = packs[k] + sale_avg_val;
						sale_val -= sale_avg_val;
					}
					if (sale_val <= 0) {
						sale_val = 0;
						break;
					}
				}
				
				if (sale_val > 0) {
					for (int k = 0; k < i * STEP; k++) {
						double idle = MAX - packs[k];
						packs[k] += idle;
						sale_val -= idle;
						if (sale_val <= 0) {
							sale_val = 0;
							break;
						}
					}
				}
				
			} else {
				packs[(i + 1) * STEP - 1] = Double.parseDouble(numFormat.format(step_total));
			}
		}
		for (double d : packs) {
			real_sum += d;
		}
		System.out.println(real_sum);
	}
	
	public static void main(String[] args) {
		System.out.println("====================");
		numFormat.setMaximumFractionDigits(2);
		getPacks();
		System.out.println("\n====================");
	}
	
	/**
	 * 获取随机面额
	 * 
	 * @return
	 */
	public static double getRandomDouble() {
		double ranVal;
		while (true) {
			ranVal = Double.parseDouble(numFormat.format(Math.random() * 100));
			if (ranVal <= MAX && ranVal >= MIN) {
				break;
			}
		}
		return ranVal;
	}
	
}
全屏代码
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.alvin.fullscreen;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.List;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 *
 * @author Administrator
 */
public class FullScreenWindow extends JFrame {

    private Container parentContainer;
    private JComponent childComponent;
    private JFloatBar floatBar;
    private List<JComponent> toolbarComponents;
    private int box_width = 320;
    private int menu_with;
    private AltTabStopper stoptor;

    public FullScreenWindow(JComponent childComponent, List<JComponent> toolbarComponents) {
        this.parentContainer = childComponent.getParent();
        this.childComponent = childComponent;
        this.toolbarComponents = toolbarComponents;
        for (JComponent component : toolbarComponents) {
            menu_with += component.getWidth() + 5;
        }
        initUI();
        setUndecorated(true);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        stoptor = altTabStopThreand(this);
    }

    public void doFullScreen() {
        floatBar = new JFloatBar();
        this.parentContainer.remove(childComponent);
        this.add(childComponent);
        this.add(floatBar, BorderLayout.NORTH);
        if (GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().isFullScreenSupported()) {
            GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
        }
    }

    private void initUI() {
        setLayout(new BorderLayout());
    }

    private class JFloatBar extends JPanel {

        public JFloatBar() {
            final JFloatMenuBar menubar = new JFloatMenuBar();
            addMouseMotionListener(new MouseMotionListener() {
                @Override
                public void mouseDragged(MouseEvent e) {
                }

                @Override
                public void mouseMoved(MouseEvent e) {
                    if (new Rectangle((FullScreenWindow.this.getWidth() - box_width) >> 1, 0, box_width, 2).contains(e.getPoint())) {
                        menubar.show(FullScreenWindow.this, (FullScreenWindow.this.getWidth() - menu_with) >> 1, 0);
                    }
                }
            });
            setPreferredSize(new Dimension(FullScreenWindow.this.getWidth(), 2));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.white);
            g.fillRect((FullScreenWindow.this.getWidth() - box_width) >> 1, 0, box_width, 2);
            g.drawRect((FullScreenWindow.this.getWidth() - box_width) >> 1, 0, box_width, 2);
        }
    }

    private class JFloatMenuBar extends JPopupMenu {

        public JFloatMenuBar() {
            setLayout(new BorderLayout());
            JPanel toolbar = new JPanel();
            this.add(toolbar);
            toolbar.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
            for (JComponent component : toolbarComponents) {
                toolbar.add(component);
            }
            setPreferredSize(new Dimension(menu_with, 35));
            JButton btn = new JButton("退出全屏");
            toolbar.add(btn);
            toolbar.add(Box.createGlue());
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    stoptor.stop();
                    FullScreenWindow.this.setVisible(false);
                }
            });

        }
    }

    public static AltTabStopper altTabStopThreand(JFrame frame) {
        AltTabStopper stopper = new AltTabStopper(frame);
        new Thread(stopper, "Alt-Tab Stopper").start();
        return stopper;
    }

    static class AltTabStopper implements Runnable {

        private boolean working = true;
        private JFrame frame;

        public AltTabStopper(JFrame frame) {
            this.frame = frame;
        }

        public void stop() {
            working = false;
        }

        public void run() {
            try {
                Robot robot = new Robot();
                while (working) {
                    robot.keyRelease(KeyEvent.VK_ALT);
                    robot.keyRelease(KeyEvent.VK_TAB);
                    frame.requestFocus();
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }
}
动态编译java
public class CompilerUtils {

    public static void main(String[] args) throws Exception {

        String code = "public class Test {"
                + "public void test(String name){"
                + "System.out.println(\"hello \"+name);"
                + "}"
                + "}";
        boolean b = compilerFromStr("Test", code, "D:/");
        System.out.println(b);
        URLClassLoader cl = new URLClassLoader(new URL[]{new File("D:/").toURI().toURL()}, ClassLoader.getSystemClassLoader());
        Class c = cl.loadClass("Test");
        Object obj = c.newInstance();
        Method m = c.getDeclaredMethod("test", String.class);
        m.invoke(obj, "alvin");
    }

    public static boolean compilerFromDir(String dirName) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        // 建立用于保存被编译文件名的对象    
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("test3.java"));
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
        // 编译源程序
        try {
            return task.call();
        } finally {
            try {
                fileManager.flush();
                fileManager.close();
            } catch (IOException ex) {
                Logger.getLogger(CompilerUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static boolean compilerFromStr(String className, String code, String buildPath) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, null, null);
        JavaFileObject jf = new JavaStringObject(className, code);
        //
        CompilationTask task = compiler.getTask(null, null, null, Arrays.asList("-d", buildPath), null, Arrays.asList(jf));
        try {
            return task.call();
        } finally {
            try {
                fileManager.flush();
                fileManager.close();
            } catch (Exception ex) {
                Logger.getLogger(CompilerUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static class JavaStringObject extends SimpleJavaFileObject {

        private String code;

        public JavaStringObject(String name, String code) {
            super(URI.create(name + ".java"), Kind.SOURCE);
            this.code = code;
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return code;
        }
    }
}
下载rpm
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Administrator
 */
public class DownLoadXENRPM {

    public static void main(String[] args) {
        try {
            String rpms[] = new String[]{"kernel-([0-9.-]+).el6.centos.alt.x86_64.rpm",
                "kernel-firmware-([0-9.-]+).el6.centos.alt.noarch.rpm",
                "xen-([0-9.-]+).el6.centos.alt.x86_64.rpm",
                "xen-hypervisor-([0-9.-]+).el6.centos.alt.x86_64.rpm",
                "xen-libs-([0-9.-]+).el6.centos.alt.x86_64.rpm",
                "xen-licenses-([0-9.-]+).el6.centos.alt.x86_64.rpm",
                "xen-runtime-([0-9.-]+).el6.centos.alt.x86_64.rpm"};
            String rootURL = "http://mirrors.163.com/centos/6/xen4/x86_64/Packages/";
            String content = getHTMLContent(rootURL);
            System.out.println(content);
            List<String> rmpURLs = getAllDownLoadRMPs(content, rpms);
            System.out.println("---------------搜索结果-----------------");
            for (String rmp : rmpURLs) {
                System.out.println(rmp);
            }
            System.out.println("---------------开始下载-----------------");
            for (String rpm : rmpURLs) {
                downloadRMP(rpm, rootURL, "\\\\10.20.65.241\\private\\tzc\\rpms\\");
            }
        } catch (Exception ex) {
            Logger.getLogger(DownLoadXENRPM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getHTMLContent(String urladdr) throws Exception {
        String content;
        URL url = new URL(urladdr);
        URLConnection connect = url.openConnection();
        connect.connect();
        InputStream is = connect.getInputStream();
        int b;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((b = is.read()) != -1) {
            out.write(b);
        }
        content = new String(out.toByteArray());
        return content;
    }

    public static List<String> getAllDownLoadRMPs(String content, String[] rmps) {
        List<String> result = new ArrayList<String>();
        for (String rmp : rmps) {
            Pattern p = Pattern.compile("href=\"(" + rmp + ")\"");
            Matcher m = p.matcher(content);
            List<String> versions = new ArrayList<String>();
            List<String> allVersionURL = new ArrayList<String>();
            System.out.println("---------------******-------");
            while (m.find()) {
                allVersionURL.add(m.group(1));
                versions.add(m.group(2));
                System.out.println(m.group(2));
            }
            String url = getLastVersion(versions, allVersionURL);
            result.add(url);
        }
        return result;
    }

    private static void downloadRMP(String rpm, String rootURL, String dir) throws Exception {
        String rpmurl = rootURL + rpm;
        String downloadPath = dir + rpm;
        File file = new File(downloadPath);
        if (file.exists()) {
            System.out.println(file.getAbsolutePath() + " 已经存在,跳出");
            return;
        }
        System.out.println("---开始下载:" + rpmurl);
        URL url = new URL(rpmurl);
        URLConnection connect = url.openConnection();
        connect.connect();
        InputStream is = connect.getInputStream();
        int b = -1;
        System.out.println("下载到本地:" + file.getAbsolutePath());
        file.getParentFile().mkdirs();
        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
			byte [] buff = new byte[1024];
			int len ;
            while ((len =is.read(buff)) != -1) {
                out.write(buff,0,len);
            }
        } finally {
            out.flush();
            out.close();
        }
    }

    private static String getLastVersion(List<String> versions, List<String> result) {
        String max = versions.get(0);
        int index = 0;
        for (int i = 0; i < versions.size(); i++) {
            String a = versions.get(i);
            if (a.equals(max)) {
                continue;
            }
            if (max.matches("\\d+")) {
                if (Integer.parseInt(a) > Integer.parseInt(max)) {
                    max = a;
                    index = i;
                }
            } else {
                if (isMax(a, max)) {
                    max = a;
                    index = i;
                }
            }
        }
        return result.get(index);
    }

    public static boolean isMax(String a, String max) {
        String[] as = a.split("[.]");
        String[] bs = max.split("[.]");
        if (Integer.parseInt(as[0]) < Integer.parseInt(bs[0])) {
            return false;
        } else if (Integer.parseInt(as[0]) > Integer.parseInt(bs[0])) {
            return true;
        }
        if (Integer.parseInt(as[1]) < Integer.parseInt(bs[1])) {
            return false;
        } else if (Integer.parseInt(as[1]) > Integer.parseInt(bs[1])) {
            return true;
        }
        if (as[2].contains("-")) {
            String[] ass = as[2].split("-");
            String[] bss = bs[2].split("-");
            if (Integer.parseInt(ass[0]) < Integer.parseInt(bss[0])) {
                return false;
            } else if (Integer.parseInt(ass[0]) > Integer.parseInt(bss[0])) {
                return true;
            }
            return Integer.parseInt(ass[1]) > Integer.parseInt(bss[1]);
        } else {
            return Integer.parseInt(as[2]) > Integer.parseInt(bs[2]);
        }
    }
}
jcom
配置环境:

1,将jcom.jar导入到工程classpath下 2,将jcom.dll文件拷贝到jdk\bin目录下

 

package sample1;

import java.io.File;
import java.util.Date;

import jp.ne.so_net.ga2.no_ji.jcom.IDispatch;
import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelApplication;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelRange;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbook;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbooks;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheet;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheets;


public class JcomExcelSample1 {

 private static ReleaseManager rm = null; // ReleaseManager相当于一个容器,与你机器上的所有JCOM组建交互,根据你传的参数他会去寻找你机器上的所有JCOM能操作的组建;

 public static void main(String[] args) throws Exception {
  rm = new ReleaseManager();//查找JCOM能够操作的组件
  IDispatch appl = null;
  try {
   System.out.println("EXCEL loading...");
   ExcelApplication excel = new ExcelApplication(rm);//创建可加载excel组件
   excel.Visible(true);//表示显示操作的excel文件
   System.out.println("Version=" + excel.Version());
   System.out.println("UserName=" + excel.UserName());
   System.out.println("Caption=" + excel.Caption());
   System.out.println("Value=" + excel.Value());

   ExcelWorkbooks xlBooks = excel.Workbooks();//创建工作薄对象
   ExcelWorkbook xlBook = xlBooks.Add();//添加工作薄
   
   ExcelWorksheets xlSheets = xlBook.Worksheets();//获得工作薄中的工作表,返回的是以数组形式存放
   ExcelWorksheet xlSheet = xlSheets.Item(2);//选中第2个工作表
   xlSheet.Name("new sheet name");//修改当前sheet的名字
   ExcelRange xlRange = xlSheet.Cells();//得到工作表的单元格
   
   //向指定的单元格中添加值
   xlRange.Item(1, 1).Value("第1行,第1列");
   xlRange.Item(1, 2).Value("第1行,第2列");
   xlRange.Item(1, 3).Value("第1行,第3列");
   xlRange.Item(1, 4).Value("第1行,第4列");
   xlRange.Item(1, 5).Value("第1行,第5列");
   xlRange.Item(1, 6).Value("第1行,第6列");
   xlRange.Item(1, 7).Value("第1行,第7列");

   File path = new File("./");//创建一个文件对象(.表示当前路径下或者使用(./))
   String[] filenames = path.list();//列出该文件加下的所有文件
   for (int i = 0; i < filenames.length; i++) {
    File file = new File(filenames[i]);//得到目录下当前文件对象
    System.out.println("file:"+file);//
    xlRange.Item(i + 2, 1).Value(file.getName());//文件的名字
    xlRange.Item(i + 2, 2).Value((int) file.length());//**返回文件大小**
    xlRange.Item(i + 2, 3).Value(new Date(file.lastModified()));//文件最后更新时间
    xlRange.Item(i + 2, 4).Value(file.isDirectory() ? "Yes" : "No");//判断是否是目录
    xlRange.Item(i + 2, 5).Value(file.isFile() ? "Yes" : "No");//判断是否是文件
    xlRange.Item(i + 2, 6).Value(file.canRead() ? "Yes" : "No");//判断是否可写
    xlRange.Item(i + 2, 7).Value(file.canWrite() ? "Yes" : "No");//判断是否可读
   }
   String expression_r = "=Sum(B2:B" + (filenames.length + 1) + ")";
   System.out.println("计算公式:" + expression_r);
   xlRange.Item(filenames.length + 2, 1).Value("大小合计");
   xlRange.Item(filenames.length + 2, 2).Formula(expression_r);//添加使用的表达式
   xlRange.Columns().AutoFit();//可以自动调整列宽以适应文字

//    xlSheet.PrintOut();//是否打印该文件
    xlBook.SaveAs("testExcel.xls");//保存在上面的目录下
   
   System.out.println("[Enter]");
   System.in.read();

   xlBook.Close(false, null, false);
   excel.Quit();
   System.out.println("");
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   rm.release();
  }
 }
}

jcom
在JAVA中使用JCOM和JXL注意要点:

  (1)在你的lib下要有jdom-1.0.jar(可选),jxl-2.5.5.jar(可选),jcom-2.2.4.jar,jcom.dll。

  (2)要把jcom.dll同时放到你JDK的bin目录下或者放到系统盘的windows下(推荐放到JDK的BIN下)

  把上面的JAR包都放好后开始写应用中的工具类(申明一下在JCOM中得到的都是IDispatch对象,以下还会抛出一个JComException的异常)

  (1)首先应该判断一个传进来的路径是Word 或是 Excel 还是其他的东东。

if(path.endsWith(".doc")){
......
} 

  注:如果是excel后缀是".xls";

  (2)然后你要有两个对象:

ReleaseManager rm = new ReleaseManager();
IDispatch xlsApp=null; 

  注:ReleaseManager相当于一个容器,与你机器上的所有JCOM组建交互,根据你传的参数他会去寻找你机器上的所有JCOM能操作的组建;

  IDispatch 可以理解为一个对象,所有的东东都是对象;

  (3)你要让他知道你要和EXCEL交互你得这样做

xlsApp = new IDispatch(rm, "Excel.Application"); 

  (4)接着要得到一个Workbooks(工作薄)

IDispatch excel = (IDispatch) xlsApp.get("Workbooks"); 

  (5)设置当前对象是否可见

xlsApp.put("Visible", new java.lang.Boolean(false)); 

  (6)得到工作薄以后要打开

IDispatch workbook = (IDispatch) excel.method("open", new Object[] { FilePath(EXCEL存放的路径) }); 

  (7)判断文件是否存在如果存在则删除

File f = new File(outPath);
if (f.exists())
f.delete(); 

  (8)将工作薄另存为

workbook.method("saveAs", new Object[] { outPath, new Integer(9) }); 

  (9)获得一个工作薄(workbook)下的所有工作表(Sheets)

IDispatch sheets = (IDispatch) workbook.get("Sheets"); 

  注:得到的是一个数组;

  (10)获得工作表(Sheets)的总数

int sheetsCount = Integer.parseInt(sheets.get("Count").toString()); 

  (11)得到每个工作表(Sheets)的名称

for(int sheetInx=1;sheetInx <= sheetsCount;sheetInx++) {
IDispatch sheet = (IDispatch) sheets.get("item", new Object[] { new Integer(sheetInx) });
String sheetName = sheet.get("name").toString();
} 

  注意:excel都是从1开始遍历 而不是从0开始 所以for里面有多种写法看自己怎么顺手怎么写;

  遍历工作表除了传索引还能传工作表名称:IDispatch sheet = ((IDispatch) sheets.get("item", new Object[] { sheetName }));

  (12)获得正在活动的工作表(sheet)

IDispatch asheet = (IDispatch) xlsApp.get("ActiveSheet"); 

  注:xlsApp是从ReleaseManager里面获得EXCEL对象的一个IDispatch对象

  如果是获得sheets要先获得工作薄(Workbook)然后用工作薄(Workbook)获得他下的所有工作表(sheets)

  (13)获得工作表里面的所有行总数(6万多行吧)

IDispatch row = (IDispatch)cursheet.get("Rows");
int rows = Integer.parseInt(row.get("Count").toString()); 

  (14)获得工作表里面的所有列总数(256列)

IDispatch col = (IDispatch)sheet.get("Columns");
int cols = Integer.parseInt(col.get("Count").toString()); 

  (15)获得工作表里面可视的所有行总数

IDispatch row = (IDispatch) ((IDispatch)cursheet.get("UsedRange")).get("Rows");
int rows = Integer.parseInt(row.get("Count").toString()); 

  (16)获得工作表里面可视的所有列总数

IDispatch col = (IDispatch) ((IDispatch)cursheet.get("UsedRange")).get("Columns");
int cols = Integer.parseInt(col.get("Count").toString()); 

  (17)获得行列以后要获得里面的内容(这里用的rows 和 cols就是上面所得的)

String cellVal="";
String cellTxt="";
String hasFormula= "";
String cellFormula="";
for(int i=0;i
for(int j=0;j
IDispatch cells = (IDispatch) cursheet.get("Cells", new Object[] { new Integer(i+1),new Integer(j+1) });
cellVal = cells.get("value").toString();
cellTxt = cells.get("text").toString();
hasFormula = cells.get("HasFormula").toString();
cellFormula = cells.get("FormulaR1C1").toString();
}
} 

  注:这个遍历的时候也是从1开始;

  cells.get("value")获得的是浮点数格式 如果你输入的是1,得到的会是1.0;

  cells.get("text")获得的是本身,你输入什么获得的就是什么;

  cells.get("HasFormula")判断是否是公式,如果单元格里是公式则返回真(true),如果不是公式则返回假(false);

  cells.get("FormulaR1C1")获得公式,获得单元格里公式的内容;

  (18)保护工作表

asheet.method("Protect", new Object[] {
 password, new java.lang.Boolean(true), new java.lang.Boolean(true)
}); 

  注:Protect后有N多参数 第1--3个分别是 password,DrawingObjects,Contects。

  (19)解工作表保护

asheet.method("Unprotect", new Object[] { password }); 

  (20)在finally里面写关闭

if (xlsApp != null) {
((IDispatch) xlsApp.get("ActiveWorkbook")).put("Saved", new java.lang.Boolean(true)); //保存工作薄
xlsApp.method("quit", null); //quit 是关闭的是整个EXCEL
xlsApp = null;
}
rm.release();
rm = null; 

  (21)关闭根据情况也写在finally 里面

workbook.method("close", null);
xlsApp.method("quit", null);
xlsApp=null;
rm.release();
rm = null; 

  注:workbook.method("close", null);关闭的是Workbook里的工作表;

  xlsApp.method("quit", null);关闭的是整个工作薄

  注意:

  关闭的时候一定要加上

//rm 就是ReleaseManager的实例
rm.release();
rm = null;
如果你打开EXCEL不加上面两句的话在进程里面还运行着EXCEL.EXE
//---------------------------------------------------------------- 

  如有不对请多多指教!!谢谢
xen
SetShellVarContext all

Centos5安装配置Xen虚拟化环境(2013-06-09 17:27:20)转载▼标签: xenit 分类: ESXi/XEN  
Xen安装:


yum install kernel-xen xen


修改GRUB以Xen内核启动:


vim /boot/grub/menu.lst 
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.18-308.8.2.el5xen)
root (hd0,0)
kernel /xen.gz-2.6.18-308.8.2.el5
module /vmlinuz-2.6.18-308.8.2.el5xen ro root=/dev/VolGroup00/LogVol00
module /initrd-2.6.18-308.8.2.el5xen.img


关闭SELinux:


sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config


重新启动系统:


reboot


重新登录验证Xen是否正常运行:


uname -a|grep xen
xm list


新建Xen虚拟机,如果服务器CPU支持全虚拟化可直接使用ISO安装Xen虚拟机,CPU支持半虚拟机要使用网络安装,如果有相应的Xen模板可直接使用模板新建。
本次以网络安装Centos5.8为例,可将下载的ISO解压至本地电脑,以http://127.0.0.1/iso安装,也可以通过互联网安装,如http://mirrors.163.com/centos/5.8/os/i386/。


mkdir /vm #新建VM目录
dd if=/dev/zero of=/vm/101.img bs=1M count=10240 #新建虚拟机硬盘文件,10G
virt-install -n vm101 -r 128 -f /vm/101.img --nographics -p -l http://mirrors.163.com/centos/5.8/os/i386/
-n #虚拟机名称
-r #虚拟机内存
-f #虚拟机文件
--nograhics #无X环境,以字符界面安装


Xen虚拟机管理:


xm list #列出VM列表
xm start vm101 #启动虚拟机
xm shutdown vm 101 #关闭虚拟机
xm console vm01 #打开虚拟机管理界面


http://blog.onovps.com/archives/centos-install-xen.html
centos svn 客户端
一、CentOS安装TortoiseSVN yum install -y subversion

二、SVN客户端命令

1、查看帮助 命令:svn help

启动服务

使用命令svnserve启动服务

svnserve -d  -r /srv/svn/repos

也可以加端口号 svnserve -d --listen-port 9999 -r /srv/svn/repos 

注意:后面的路径必须是一个svnadmin创建的仓库路径,否则会报错:Not a repository

2、同步(checkout)服务器数据到本地 命令:svn checkout [directory] svn co [directory]

eg:

#cd /www/website

#svn co svn://svn_site_url  ./

3、提交(commit)本地文档到服务器 命令:svn commit -m “” [directory|file] svn ci -m “” [directory|file]
4、更新(update)服务器数据到本地 命令:svn update [directory|file] svn up [directory|file]

5、查看日志 命令:svn log [directory|file]

6、增加(add)本地数据到服务器

命令:svn add

7、项目导出 export

命令:svn export --force svn_project_dir target_dir 
centos搭建svn
搭建SVN服务,有效的管理代码,以下三步可以快速搞定。
1、安装          
#yum install subversion

  判断是否安装成功
#subversion -v


  svnserve, version 1.6.11 (r934486)
出现上面的提示,说明安装成功。



有了SVN软件后还需要建立SVN库。
#mkdir /opt/svn/repos
#svnadmin create /opt/svn/repos
执行上面的命令后,自动在repos下建立多个文件, 分别是conf, db,format,hooks, locks, README.txt。    

2、配置

     上面的操作很简单,几个命令就搞定, 下面的操作也不难。
     进入上面生成的文件夹conf下,进行配置,   有以下几个文件authz, passwd, svnserve.conf
     其中authz 是权限控制,可以设置哪些用户可以访问哪些目录,   passwd是设置用户和密码的,    svnserve是设置svn相关的操作。


   2.1先设置passwd
    
[users]
# harry = harryssecret
# sally = sallyssecret
hello=123
用户名=密码


这样我们就建立了hello用户, 123密码  
   2.2 再设置权限authz

[/]
hello= rw


意思是hello用户对所有的目录有读写权限,当然也可以限定。
如果是自己用,就直接是读写吧。


2.3最后设定snvserv.conf

anon-access = none # 使非授权用户无法访问
auth-access = write # 使授权用户有写权限
password-db = password
authz-db = authz   # 访问控制文件
realm = /opt/svn/repos # 认证命名空间,subversion会在认证提示里显示,并且作为凭证缓存的关键字。
采用默认配置. 以上语句都必须顶格写, 左侧不能留空格, 否则会出错.
好了,通过以上配置,你的svn就可以了。

3、连接

启动svn: svnserve -d -r /opt/svn/repos

如果已经有svn在运行,可以换一个端口运行
svnserve -d -r /opt/svn/repos --listen-port 3391

这样同一台服务器可以运行多个svnserver

好了,启动成功后,就可以使用了。
建议采用TortoiseSVN, 连接地址为: svn://your server address (如果指定端口需要添加端口  :端口号)

连接后可以上传本地的文件,有效的管理你的代码。

通过以上三步,可以快速的搭建起svn, 开启你的项目吧,如果您觉得有用,请留言,谢谢您的支持。
转载请著名来自(公共信息服务网), 谢谢!
在保证图片完整的情况下,保存我的数据
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DataUtil {

    private static void putToArray(byte[] oldLenArry, long oldLen) throws Exception {
        String str = oldLen + "";
        byte[] cs = str.getBytes();
        if (cs.length > 13) {
            throw new Exception("data to long: length " + cs.length + " > 13");
        } else if (cs.length <= 0) {
            throw new Exception("no data: length " + cs.length + " <= 0");
        } else {
            byte[] l;
            //保证前面有两个字节的长度
            String sl = cs.length + "";
            if (sl.length() == 1) {
                sl = "0" + sl;
            }
            l = sl.getBytes();
            int index = 0;
            //字节长度
            for (byte b : l) {
                oldLenArry[index++] = b;
            }
            //字节内容
            for (byte c : cs) {
                oldLenArry[index++] = c;
            }
        }
    }

    public static void main(String args[]) {
        File f = new File("D:\\1.png");
//        try {
//            save(f, "唐植超到此一游".getBytes());
//        } catch (Exception ex) {
//            Logger.getLogger(DataUtil.class.getName()).log(Level.SEVERE, null, ex);
//        }
        try {
            byte[] bs = read(f);
            System.out.println(new String(bs));
        } catch (Exception ex) {
            Logger.getLogger(DataUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static int getLen(byte[] data) {
        byte[] dataLen = new byte[2];
        System.arraycopy(data, 0, dataLen, 0, 2);
        String str = new String(dataLen);
        if (str.startsWith("0")) {
            str = str.substring(1);
        }
        int len = Integer.parseInt(str);
        byte[] dataArray = new byte[len];
        System.arraycopy(data, 2, dataArray, 0, dataArray.length);
        str = new String(dataArray);
        return Integer.parseInt(str);
    }

    private DataUtil() {
    }

    public static byte[] read(File savePath) throws Exception {
        InputStream is;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        is = new BufferedInputStream(new FileInputStream(savePath));
        //文件原来的内容
        byte[] buff = new byte[512];
        while (is.read(buff) != -1) {
            out.write(buff);
        }
        is.close();
        byte[] oldLenArray = new byte[15];
        byte[] bs = out.toByteArray();
        System.arraycopy(bs, ((int) savePath.length() - 15), oldLenArray, 0, oldLenArray.length);
        int oldLen = getLen(oldLenArray);
        int dataArrayLen = (int) (savePath.length() - 15 - oldLen);
        byte[] dataArray = new byte[dataArrayLen];
        System.arraycopy(bs, oldLen, dataArray, 0, dataArrayLen);
        return dataArray;
    }

    public static void save(File savePath, byte[] saveData) throws Exception {
        InputStream is;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        is = new BufferedInputStream(new FileInputStream(savePath));
        //文件原来的内容
        byte[] buff = new byte[512];
        while (is.read(buff) != -1) {
            out.write(buff);
        }
        is.close();
        buff = out.toByteArray();
        long oldLen = buff.length;
        //调整后写入新的内容
        OutputStream os = new BufferedOutputStream(new FileOutputStream(savePath));
        os.write(buff);
        os.write(saveData);
        byte[] oldLenArry = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        putToArray(oldLenArry, oldLen);
        os.write(oldLenArry);
        os.flush();
        os.close();
    }
}
模块管理控件雏形
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.test;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.*;

/**
 *
 * @author Administrator
 */
public class ModulePanel extends JComponent {

    private Action currentAction;
    private Component component;

    public ModulePanel(Map<String, List<Action>> module) {
        setLayout(new ModuleLayout());
        setBackground(Color.white);
        for (Entry<String, List<Action>> entry : module.entrySet()) {
            add(new ModuleListItem(entry.getKey(), entry.getValue()));
        }
    }

    private class ModuleLayout implements LayoutManager {

        @Override
        public void addLayoutComponent(String name, Component comp) {
            comp.doLayout();
        }

        @Override
        public void removeLayoutComponent(Component comp) {
            comp.doLayout();
        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {
            return parent.getSize();
        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {
            return preferredLayoutSize(parent);
        }

        @Override
        public void layoutContainer(Container parent) {
            int itemHeight = 120;
            int w = 0;
            int h = 0;
            w = parent.getWidth();
            for (int i = 0; i < parent.getComponentCount(); i++) {
                Component c = parent.getComponent(i);
                c.setBounds(2, i * itemHeight + 5, parent.getWidth(), itemHeight);
                h += itemHeight;
            }
            parent.setSize(w, h);
        }
    }

    private class ModuleListItem extends JComponent {

        private ModuleItem item;

        public ModuleListItem(String category, List<Action> modles) {
            setLayout(new BorderLayout(0, 0));
            add(new ItemTitle(category), BorderLayout.NORTH);
            item = new ModuleItem(modles);
            add(item);
            setPreferredSize(new Dimension(100, 120));
        }
    }

    private class ItemTitle extends JComponent {

        private String title;

        public ItemTitle(String title) {
            this.title = title;
            setPreferredSize(new Dimension(100, 30));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
            g2d.setColor(Color.white);
            g2d.fill(new Rectangle(0, 0, getWidth(), getHeight()));

            Polygon p = new Polygon();
            p.addPoint(0, 0);
            p.addPoint(200, 0);
            p.addPoint(200 - 30, 30);
            p.addPoint(0, 30);
            GeneralPath path = new GeneralPath(p);

            g2d.setColor(SystemColor.control);
            g2d.fill(path);

            g2d.setColor(SystemColor.control);
            g2d.fill(new Rectangle2D.Double(0, 0, getWidth(), 3));
            g2d.draw(path);

            g2d.setColor(Color.BLACK);
            g2d.drawString(title, 10, 25);
        }

        @Override
        public void update(Graphics g) {
            this.paintComponent(g);
        }
    }

    private class ModuleItem extends JList {

        private List<Action> actions;

        public ModuleItem(List<Action> actions) {
            setLayoutOrientation(HORIZONTAL_WRAP);
            setVisibleRowCount(1);
            setFixedCellWidth(80);
            setFixedCellHeight(80);
            this.actions = actions;
            setListData(actions.toArray());
            addMouseListener(listItemAction);
            addMouseMotionListener(listItemAction);
            setCellRenderer(new ListCellRenderer() {

                @Override
                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    if (value.equals(currentAction)) {
                        return new JButton(currentAction);
                    } else {
                        JLabel l = new JLabel(value.toString());
                        l.setHorizontalAlignment(JLabel.CENTER);
                        return l;
                    }
                }
            });
        }
        private MouseAdapter listItemAction = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                mouseMoved(e);
                if (e.getClickCount() == 2) {
                    if (currentAction != null) {
                        currentAction.actionPerformed(null);
                    }
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                int index = locationToIndex(e.getPoint());
                currentAction = null;
                if (index != -1) {
                    currentAction = actions.get(index);
                    if (component != null && component != ModuleItem.this) {
                        component.repaint();
                    }
                    component = ModuleItem.this;
                    component.repaint();
                }
            }
        };
    }
}
--------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JGroupPanel extends JPanel {
    /* 用来管理组的三个容器 */
    private JPanel pNorth = new JPanel() {
    };

    private JPanel pCenter = new JPanel();

    private JPanel pSouth = new JPanel();

    int[] openFlag = new int[3];

    /* 当前全部组的集合 */
    private ArrayList groupList = new ArrayList();

    /* 是否已禁止添加组件 */
    private boolean forbidFlag = false;

    String[][] str = new String[3][5];

    /* 当前激活的组 */
    private JGroupContainer activeGroup = null;

    transient ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            JButton bttTitle = (JButton) e.getSource();
            expandGroup((JGroupContainer) bttTitle.getParent());
        }
    };

    public boolean hasCreateDefaultGroup = false;

    public JGroupPanel() {
        initComponents();
        createDefaultGroup();
    }

    private void initComponents() {
        this.setLayout(new BorderLayout());
        this.add(pNorth, BorderLayout.NORTH);
        this.add(pCenter, BorderLayout.CENTER);
        this.add(pSouth, BorderLayout.SOUTH);
        pNorth.setLayout(new GroupLayout());
        pCenter.setLayout(new BorderLayout());
        pSouth.setLayout(new GroupLayout());
        forbidFlag = true;
        for (int i = 0; i < 3; i++) {
            openFlag[i] = 0;
        }
    }

    private void createDefaultGroup() {
        // Default Group
        for (int i = 1; i <= 3; i++) {
            insertGroup(i - 1, "Group " + i);

            for (int j = 1; j <= 5; j++) {
                str[i - 1][j - 1] = "Member " + j + "of " + i;
                JButton bttMember = new JButton(str[i - 1][j - 1]);
                bttMember.setActionCommand(str[i - 1][j - 1]);

                addMember(i - 1, bttMember);
                bttMember.setPreferredSize(new Dimension(1, 40));
                bttMember.setOpaque(false);
            }

            getGroup(i - 1).setMemberGap(20, 5);
        }
        // expandGroup(0);
        hasCreateDefaultGroup = true;
    }

    /**
     * @param groupNames
     *            String[] 预设组名
     */
    public JGroupPanel(String groupNames[]) {
        initComponents();
        addGroup(groupNames);
    }

    /**
     * 展开组
     * 
     * @param name
     *            String 组名
     */
    public void expandGroup(String name) {
        for (int i = getGroupCount() - 1; i >= 0; i--) {
            if (getGroupName(i).equals(name)) {
                expandGroup(i);
            }
        }
    }

    /**
     * 展开组
     * 
     * @param index
     *            int 组的顺序号
     */
    public void expandGroup(int index) {
        expandGroup(getGroup(index));
    }

    /**
     * 展开组
     * 
     * @param group
     *            JGroupContainer 组
     */
    protected void expandGroup(JGroupContainer group) {
        int num = 0;
        pNorth.removeAll();
        pCenter.removeAll();
        pSouth.removeAll();
        boolean hasAddCenter = false;
        for (int i = 0; i < groupList.size(); i++) {
            Component c = (Component) groupList.get(i);
            if (openFlag[i] == 0) {
                if (hasAddCenter) {
                    pSouth.add(c);
                } else if (c == group) {
                    pCenter.add(c, BorderLayout.CENTER);
                    openFlag[i] = 1;
                    num = i + 1;
                    hasAddCenter = true;
                } else {
                    pNorth.add(c);
                }
            } else {
                if (activeGroup != null) {
                    activeGroup.collapse();
                    activeGroup = null;
                }
                if (c == group) {
                    pNorth.add(c);
                } else if (num == 0) {
                    pNorth.add(c);
                } else if (num > i + 1) {
                    pNorth.add(c);
                } else {
                    pSouth.add(c);
                }

                openFlag[i] = 0;
            }
        }
        if (activeGroup != null) {
            activeGroup.collapse();
        }
        for (int i = 0; i < groupList.size(); i++) {
            Component c = (Component) groupList.get(i);
            if (c == group && openFlag[i] == 1) {
                activeGroup = group;
                activeGroup.expand();
            }
        }
        pNorth.doLayout();
        pCenter.doLayout();
        pSouth.doLayout();
        doLayout();
    }

    /**
     * 收缩组
     * 
     * @param name
     *            String 组名
     */
    public void collapseGroup(String name) {
        for (int i = getGroupCount() - 1; i >= 0; i--) {
            if (getGroupName(i).equals(name)) {
                collapseGroup(i);
            }
        }
    }

    /**
     * 收缩组
     * 
     * @param index
     *            int 组的顺序号
     */
    public void collapseGroup(int index) {
        collapseGroup(getGroup(index));
    }

    /**
     * 收缩组
     * 
     * @param group
     *            JGroupContainer 组
     */
    protected void collapseGroup(JGroupContainer group) {
        if (group == activeGroup) {
            activeGroup.collapse();
            activeGroup = null;
        }
    }

    /**
     * 添加组
     * 
     * @param name
     *            String 组名
     */
    public void addGroup(String name) {
        this.insertGroup(getGroupCount(), name);
    }

    /**
     * 添加多个组
     * 
     * @param names
     *            String[] 组名
     */
    public void addGroup(String names[]) {
        for (int i = 0; i < names.length; i++) {
            addGroup(names[i]);
        }
    }

    /**
     * 插入一个组
     * 
     * @param index
     *            int 顺序号
     * @param name
     *            String 组名
     * @param bg
     *            Color 背景色
     */
    public void insertGroup(int index, String name, Color bg) {
        if (index < 0 || index > groupList.size()) {
            throw new ArrayIndexOutOfBoundsException("index:" + index
                    + " >count:" + groupList.size());
        }
        if (hasCreateDefaultGroup) {
            while (getGroupCount() > 0) {
                removeGroup(0);
            }
            hasCreateDefaultGroup = false;
        }
        int countNorth = pNorth.getComponentCount();
        int countCenter = pCenter.getComponentCount();
        int countSouth = pSouth.getComponentCount();
        JGroupContainer group;
        if (index <= countNorth) {
            group = insertGroup(pNorth, index, name, bg);
        } else if (index <= countNorth + countCenter) {
            group = insertGroup(pCenter, index - countNorth, name, bg);
        } else if (index <= countNorth + countCenter + countSouth) {
            group = insertGroup(pSouth, index - countNorth - countCenter, name,
                    bg);
        } else {
            group = insertGroup(pSouth, countSouth, name, bg);
        }
        group.getTitleButton().addActionListener(al);
        groupList.add(index, group);

    }

    /**
     * 插入一个组
     * 
     * @param index
     *            int 顺序号
     * @param name
     *            String 组名
     */
    public void insertGroup(int index, String name) {
        insertGroup(index, name, UIManager.getColor("Desktop.background"));
    }

    /**
     * 插入一个组
     * 
     * @param p
     *            JPanel 目标面板
     * @param index
     *            int 顺序号
     * @param name
     *            String 组名
     * 
     * 
     * /** 插入一个组
     * @param p
     *            JPanel 目标面板
     * @param index
     *            int 顺序号
     * @param name
     *            String 组名
     * @return JGroupContainer
     */
    private JGroupContainer insertGroup(JPanel p, int index, String name,
            Color bg) {
        JGroupContainer group = new JGroupContainer(name, bg);
        p.add(group);
        return group;
    }

    /**
     * 删除一个组
     * 
     * @param index
     *            int 顺序号
     */
    public void removeGroup(int index) {
        JGroupContainer c = (JGroupContainer) groupList.get(index);
        c.getParent().remove(c);
        c.getTitleButton().removeActionListener(al);
    }

    /**
     * 删除一个组
     * 
     * @param name
     *            String 组名
     */
    public void removeGroup(String name) {
        for (int i = getGroupCount() - 1; i >= 0; i--) {
            if (getGroupName(i).equals(name)) {
                this.removeGroup(i);
            }
        }
    }

    /**
     * 设置组名
     * 
     * @param index
     *            int 顺序号
     * @param name
     *            String 组名
     */
    public void setGroupName(int index, String name) {
        this.getGroup(index).setName(name);
    }

    /**
     * 取得组名
     * 
     * @param groupIndex
     *            int 顺序号
     * @return String 组名
     */
    public String getGroupName(int groupIndex) {
        return getGroup(groupIndex).getName();
    }

    /**
     * 取得全部组名
     * 
     * @return String[]
     */
    public String[] getGroupNames() {
        String sResult[] = new String[getGroupCount()];
        for (int i = 0; i < getGroupCount(); i++) {
            sResult[i] = getGroupName(i);
        }
        return sResult;
    }

    /**
     * 取得当前组的总数
     * 
     * @return int
     */
    public int getGroupCount() {
        return groupList.size();
    }

    /**
     * 往组中添加成员组件
     * 
     * @param groupIndex
     *            int 组的顺序号
     * @param member
     *            Component 成员组件
     */
    public void addMember(int groupIndex, Component member) {
        getGroup(groupIndex).addMember(getGroup(groupIndex).getMemberCount(),
                member);
    }

    /**
     * 往组中插入成员组件
     * 
     * @param groupIndex
     *            int 组的顺序号
     * @param memberIndex
     *            int 插入的顺序号
     * @param member
     *            Component 成员组件
     */
    public void insertMember(int groupIndex, int memberIndex, Component member) {
        getGroup(groupIndex).addMember(memberIndex, member);
    }

    /**
     * 从组中移除成员组件
     * 
     * @param groupIndex
     *            int
     * @param memberIndex
     *            int
     */
    public void removeMember(int groupIndex, int memberIndex) {
        getGroup(groupIndex).removeMember(memberIndex);
    }

    /**
     * 取得成员组件
     * 
     * @param groupIndex
     *            int 组的顺序号
     * @param memberIndex
     *            int 成员组件的顺序号
     * @return Component 成员组件
     */
    public Component getMember(int groupIndex, int memberIndex) {
        return getGroup(groupIndex).getMember(memberIndex);
    }

    /**
     * 取得全部成员组件
     * 
     * @param groupIndex
     *            int 组的顺序号
     * @return Component[] 全部成员组件
     */
    public Component[] getMembers(int groupIndex) {
        return getGroup(groupIndex).getMembers();
    }

    /**
     * 取得成员组件的总数
     * 
     * @param groupIndex
     *            int 组的顺序号
     * @return int 总数
     */
    public int getMemberCount(int groupIndex) {
        return getGroup(groupIndex).getMemberCount();
    }

    /**
     * 取得组
     * 
     * @param index
     *            int 组的顺序号
     * @return JGroupContainer 组
     */
    protected JGroupContainer getGroup(int index) {
        return (JGroupContainer) groupList.get(index);
    }

    /**
     * 覆写的addImpl方法,禁止再向JGroupPane中添加组件
     * 
     * @param comp
     *            Component
     * @param constraints
     *            Object
     * @param index
     *            int
     */
    protected void addImpl(Component comp, Object constraints, int index) {
        if (forbidFlag) {
            if (!(comp instanceof JGroupContainer)) {
                throw new UnsupportedOperationException(
                        "JGroupPane can't add component!");
            }
        } else {
            super.addImpl(comp, constraints, index);
        }
    }

    /**
     * <p>
     * Title: OpenSwing
     * </p>
     * <p>
     * Description: 组面板布局管理器
     * </p>
     * <p>
     * Copyright: Copyright (c) 2004
     * </p>
     * <p>
     * Company:
     * </p>
     * 
     * @author <a href="mailto:sunkingxie@hotmail.com">SunKing</a>
     * @version 1.0
     */
    class GroupLayout implements LayoutManager, java.io.Serializable {
        int vgap = 0;

        int hgap = 0;

        public GroupLayout() {
        }

        public GroupLayout(int hg, int vg) {
            this.hgap = hg;
            this.vgap = vg;
        }

        public void addLayoutComponent(String name, Component comp) {
        }

        public void removeLayoutComponent(Component comp) {
        }

        public Dimension preferredLayoutSize(Container parent) {
            synchronized (parent.getTreeLock()) {
                Insets insets = parent.getInsets();
                int ncomponents = parent.getComponentCount();
                int w = 0;
                int h = 0;
                for (int i = 0; i < ncomponents; i++) {
                    Component comp = parent.getComponent(i);
                    Dimension d = comp.getPreferredSize();
                    if (w < d.width) {
                        w = d.width;
                    }
                    h += d.height + vgap;
                }
                return new Dimension(insets.left + insets.right + w + 2 * hgap,
                        insets.top + insets.bottom + h + 2 * vgap);
            }
        }

        public Dimension minimumLayoutSize(Container parent) {
            return preferredLayoutSize(parent);
        }

        public void layoutContainer(Container parent) {
            synchronized (parent.getTreeLock()) {
                Insets insets = parent.getInsets();
                int ncomponents = parent.getComponentCount();
                if (ncomponents == 0) {
                    return;
                }
                int y = insets.top + vgap;
                for (int c = 0; c < ncomponents; c++) {
                    int h = parent.getComponent(c).getPreferredSize().height;
                    parent.getComponent(c).setBounds(
                            insets.left + hgap,
                            y,
                            parent.getWidth() - insets.left - insets.right - 2
                                    * hgap, h);
                    y += h + vgap;
                }
            }
        }

        public String toString() {
            return getClass().getName();
        }
    }

    /**
     * <p>
     * Title: OpenSwing
     * </p>
     * <p>
     * Description: 组
     * </p>
     * <p>
     * Copyright: Copyright (c) 2004
     * </p>
     * <p>
     * Company:
     * </p>
     * 
     * @author <a href="mailto:sunkingxie@hotmail.com">SunKing</a>
     * @version 1.0
     */
    class JGroupContainer extends JPanel {
        private JButton bttGroupTitle = new JButton();

        private JPanel pMembers = new JPanel();

        // private JScrollPane sp;
        public JGroupContainer() {
            this("");
        }

        public JGroupContainer(String name) {
            this(name, UIManager.getColor("Desktop.background"));
        }

        /**
         * @param name
         *            String 组名
         * @param background
         *            Color 成员组件所在面板背景色
         */
        public JGroupContainer(String name, Color background) {
            bttGroupTitle.setText(name);
            bttGroupTitle.setFocusable(false);
            pMembers.setLayout(new GroupLayout(5, 5));
            this.setLayout(new BorderLayout());
            this.add(bttGroupTitle, BorderLayout.NORTH);

            // pMembers.setBackground(background);

            Color thumbColor = UIManager.getColor("ScrollBar.thumb");
            Color trackColor = UIManager.getColor("ScrollBar.track");
            Color trackHighlightColor = UIManager
                    .getColor("ScrollBar.trackHighlight");

            UIManager.put("ScrollBar.thumb", background);
            UIManager.put("ScrollBar.track", background);
            UIManager.put("ScrollBar.trackHighlight", background);
            /*
             * sp = new JScrollPane(pMembers); sp.setHorizontalScrollBarPolicy(
             * JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
             */
            this.add(pMembers, BorderLayout.CENTER);
            collapse();
            UIManager.put("ScrollBar.thumb", thumbColor);
            UIManager.put("ScrollBar.track", trackColor);
            UIManager.put("ScrollBar.trackHighlight", trackHighlightColor);

        }

        /**
         * 设置间距
         * 
         * @param hgap
         *            int 横间距
         * @param vgap
         *            int 竖间距
         */
        public void setMemberGap(int hgap, int vgap) {
            pMembers.setLayout(new GroupLayout(hgap, vgap));
        }

        /**
         * 取得组的标题按钮
         * 
         * @return JButton
         */
        public JButton getTitleButton() {
            return bttGroupTitle;
        }

        /**
         * 取得组的成员组件面板
         * 
         * @return JPanel
         */
        public JPanel getMembersContainer() {
            return pMembers;
        }

        /**
         * 收缩组
         */
        public void collapse() {
            pMembers.setVisible(false);
            this.revalidate();
        }

        /**
         * 展开组
         */
        public void expand() {
            pMembers.setVisible(true);
            this.revalidate();
        }

        /**
         * 设置组名
         * 
         * @param name
         *            String 组名
         */
        public void setName(String name) {
            bttGroupTitle.setText(name);
        }

        /**
         * 取得组名
         * 
         * @return String
         */
        public String getName() {
            return bttGroupTitle.getText();
        }

        /**
         * 添加一个成员组件
         * 
         * @param index
         *            int 顺序号
         * @param c
         *            Component 成员组件
         */
        public void addMember(int index, Component c) {
            pMembers.add(c, index);
            pMembers.doLayout();
        }

        /**
         * 删除一个成员组件
         * 
         * @param index
         *            int 顺序号
         */
        public void removeMember(int index) {
            pMembers.remove(index);
            pMembers.doLayout();
        }

        /**
         * 取得一个成员组件
         * 
         * @param index
         *            int 顺序号
         * @return Component 成员组件
         */
        public Component getMember(int index) {
            return pMembers.getComponent(index);
        }

        /**
         * 取得全部成员组件
         * 
         * @return Component[] 成员组件
         */
        public Component[] getMembers() {
            Component coms[] = new Component[getMemberCount()];
            for (int i = 0; i < coms.length; i++) {
                coms[i] = pMembers.getComponent(i);
            }
            return coms;
        }

        /**
         * 取得成员组件总数
         * 
         * @return int 总数
         */
        public int getMemberCount() {
            return pMembers.getComponentCount();
        }

        /**
         * 重写的toString方法
         * 
         * @return String
         */
        public String toString() {
            return getName();
        }
    }

    /**
     * /** 测试程序
     * 
     * @param args
     *            String[]
     */
    public static void main(String[] args) {
        try {
            String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            UIManager.setLookAndFeel((LookAndFeel) Class.forName(
                    windowsClassName).newInstance());
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JFrame frame = new JFrame("JGroupPanel Demo");
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(new JGroupPanel(), BorderLayout.CENTER);
        frame.setSize(150, 600);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation(d.width - frame.getSize().width - 10, 10);
        frame.setVisible(true);
    }
}
Global site tag (gtag.js) - Google Analytics