guanxf

我的博客:http://blog.sina.com.cn/17learning

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  71 随笔 :: 1 文章 :: 41 评论 :: 0 Trackbacks

2013年9月10日 #


createTree(1, orgNodeTree, sameOrgNodes, 0);


@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class NodeTree {
private String pName;
private String name;
private int level;
private List<NodeTree> children;
}

private void createTree(int leave, int ind, Map<String, NodeTree> pIndexNodeNameMap, List<NodeVo> childNodes) {
Map<String, NodeTree> cIndexNodeNameMap = new HashMap();
//构建树
int treeNo = pIndexNodeNameMap.size();
if (treeNo == 0) {
return;
}
int group = 0;
for (int i = ind; i < childNodes.size(); i++) {
NodeVo node = childNodes.get(i);
long index = node.getId() % treeNo;
NodeTree pNode = pIndexNodeNameMap.get(index + "");
List<NodeTree> children = pNode.getChildren();
if (CollectionUtils.isEmpty(children)) {
children = new ArrayList();
}
if (children.size() > 2) {
leave++;
createTree(leave, i, cIndexNodeNameMap, childNodes);
break;
} else {
NodeTree child = new NodeTree();
child.setLevel(leave);
child.setPName(pNode.getName());
child.setName(node.getNodeName());
children.add(child);
pNode.setChildren(children);
cIndexNodeNameMap.put(group + "", child);
group++;
}
}
}


private boolean createTree(int level, List<NodeTree> parentNodes, List<NodeVo> childNodes, int beginIndex) {
//构建树
List<NodeTree> nextLevelNodes = new ArrayList<>();
for (int i = beginIndex; i < childNodes.size(); i++) {
int parentCount = 1;
for (NodeTree pNode : parentNodes) {
List<NodeTree> children = pNode.getChildren();
if (CollectionUtils.isEmpty(children)) {
children = new ArrayList();
pNode.setChildren(children);
}
if (children.size() >= 3) {
if(parentCount >= parentNodes.size()){
return createTree(++level, nextLevelNodes, childNodes, beginIndex);
}
} else {
if (beginIndex >= childNodes.size()) {
return true;
}
NodeTree child = new NodeTree();
child.setLevel(level);
child.setPName(pNode.getName());
NodeVo node = childNodes.get(beginIndex);
child.setName(node.getNodeName());
pNode.getChildren().add(child);
nextLevelNodes.add(child);
beginIndex++;
}
parentCount++;
}
}
return true;
}
posted @ 2020-09-07 09:56 管先飞 阅读(236) | 评论 (0)编辑 收藏

执行命名:
git pull github master --allow-unrelated-histories

执行结果如下:

E:\WorkSpace\workspaceJ2ee\abocode\jfaster>git pull github master --allow-unrelated-histories
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 3
Unpacking objects: 100% (3/3), done.
From https://github.com/abocode/jfaster
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> github/master
Merge made by the 'recursive' strategy.
 .gitattributes | 3 +++
 1 file changed, 3 insertions(+)
 create mode 100644 .gitattributes
posted @ 2018-05-20 12:30 管先飞 阅读(304) | 评论 (0)编辑 收藏

进入“控制面板”——“用户账户”-凭据管理器——windows凭据

找到了git的用户名密码。修改正确后ok

posted @ 2018-05-20 12:29 管先飞 阅读(242) | 评论 (0)编辑 收藏

元注解:

  元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解:
    1.@Target,
    2.@Retention,
    3.@Documented,
    4.@Inherited

  这些类型和它们所支持的类在java.lang.annotation包中可以找到。下面我们看一下每个元注解的作用和相应分参数的使用说明。
以下为一个简单场景的应用:
 1.定义注解:
   
@Target(TYPE)
@Retention(RUNTIME)
public @interface Table {
/**
* (Optional) The name of the table.
* <p/>
* Defaults to the entity name.
*/
String name() default "";
}
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Column {

/**
* (Optional) The name of the column. Defaults to
* the property or field name.
*/
String name() default "";
}
2、定义实体类:
  

@Table(name = "t_s_user")
public class User {
@Column(name="name")
private String name;

@Column(name="pwd")
private String pwd;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPwd() {
return pwd;
}

public void setPwd(String pwd) {
this.pwd = pwd;
}
}

3、运行:

public static void print() {
System.out.println("table's name" + User.class.getAnnotation(Table.class).name());
Field[] fields = User.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
System.out.println("field's type:" + field.getType().getName());
System.out.println("field's columnName:" + field.getAnnotation(Column.class).name());
}
}

关于注解的详细介绍:http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html
posted @ 2016-08-18 20:42 管先飞 阅读(2820) | 评论 (0)编辑 收藏

1.选择:File->project structure->libraries

2.左上角选择添加,选择添加java(还提供了添加maven项目),然后选择所需要的目录:

3.idea 会提示选择添加什么类型的文件,我们是单纯的文件,所以选择classes

   

 
posted @ 2016-04-29 15:42 管先飞 阅读(1681) | 评论 (0)编辑 收藏

nginx 反向代理到 apache
server {
        listen       80;
        server_name  app.haeee.com;
index index.html index.htm index.php;
   root /alidata/www/movie-app;
     error_page 404 500 502 503 504 http://app.haeee.com; 
location ~ .*\.(php|php5)?$
{
#fastcgi_pass  unix:/tmp/php-cgi.sock;
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
#伪静态规则
#include /alidata/server/nginx/conf/rewrite/phpwind.conf;
access_log  /alidata/log/nginx/access/movie-app.log;
}

nginx 反向代理到 tomcat
server {
    listen   80;
    server_name  hulasou.com www.hulasou.com;
index index.html index.htm index.jsp;
#location ~ .*\.(jsp)?$
location /{      
index index.jsp;
        proxy_pass http://localhost:8181;
}
#伪静态规则
include /alidata/server/nginx/conf/rewrite/uuxiaohua.conf;
access_log  /alidata/log/nginx/access/uuxiaohua.log;
}
posted @ 2016-01-19 17:46 管先飞 阅读(384) | 评论 (0)编辑 收藏

1、修改启动项:
@SpringBootApplication
@ComponentScan
@Import({DBConfiguration.class, ResourceConfiguration.class,AppConfiguration.class})
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
2、修改pom文件:
    修改packaging
    <packaging>war</packaging>
  加入打包到tomcat的配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-legacy</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

3、如果不需要JMX在application.properties文件中加入配置项:
endpoints.jmx.uniqueNames=true
或者直接关闭:
 endpoints.jmx.enabled=false
posted @ 2016-01-14 17:21 管先飞 阅读(6543) | 评论 (1)编辑 收藏

spring data 系列一直是开发者追捧的热潮,而官方并未出spring data  jdbc,国外一个开发者让我们看到了福音,文档如下供大家共同学习。

Build Status Maven Central

Spring Data JDBC generic DAO implementation

The purpose of this project is to provide generic, lightweight and easy to use DAO implementation for relational databases based on JdbcTemplate from Spring framework, compatible with Spring Data umbrella of projects.

Design objectives

  • Lightweight, fast and low-overhead. Only a handful of classes, no XML, annotations, reflection
  • This is not full-blown ORM. No relationship handling, lazy loading, dirty checking, caching
  • CRUD implemented in seconds
  • For small applications where JPA is an overkill
  • Use when simplicity is needed or when future migration e.g. to JPA is considered
  • Minimalistic support for database dialect differences (e.g. transparent paging of results)

Features

Each DAO provides built-in support for:

  • Mapping to/from domain objects through RowMapper abstraction
  • Generated and user-defined primary keys
  • Extracting generated key
  • Compound (multi-column) primary keys
  • Immutable domain objects
  • Paging (requesting subset of results)
  • Sorting over several columns (database agnostic)
  • Optional support for many-to-one relationships
  • Supported databases (continuously tested):
    • MySQL
    • PostgreSQL
    • H2
    • HSQLDB
    • Derby
    • MS SQL Server (2008, 2012)
    • Oracle 10g / 11g (9i should work too)
    • ...and most likely many others
  • Easily extendable to other database dialects via SqlGenerator class.
  • Easy retrieval of records by ID

API

Compatible with Spring Data PagingAndSortingRepository abstraction, all these methods are implemented for you:

public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
 T  save(T entity);
Iterable<T> save(Iterable<? extends T> entities);
 T  findOne(ID id);
boolean exists(ID id);
Iterable<T> findAll();
   long count();
   void delete(ID id);
   void delete(T entity);
   void delete(Iterable<? extends T> entities);
   void deleteAll();
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
Iterable<T> findAll(Iterable<ID> ids);
}

Pageable and Sort parameters are also fully supported, which means you get paging and sorting by arbitrary properties for free. For example say you have userRepository extending PagingAndSortingRepository<User, String> interface (implemented for you by the library) and you request 5th page of USERS table, 10 per page, after applying some sorting:

Page<User> page = userRepository.findAll(
new PageRequest(
5, 10, 
new Sort(
new Order(DESC, "reputation"), 
new Order(ASC, "user_name")
)
)
);

Spring Data JDBC repository library will translate this call into (PostgreSQL syntax):

SELECT *
FROM USERS
ORDER BY reputation DESC, user_name ASC
LIMIT 50 OFFSET 10

...or even (Derby syntax):

SELECT * FROM (
SELECT ROW_NUMBER() OVER () AS ROW_NUM, t.*
FROM (
SELECT * 
FROM USERS 
ORDER BY reputation DESC, user_name ASC
) AS t
) AS a 
WHERE ROW_NUM BETWEEN 51 AND 60

No matter which database you use, you'll get Page<User> object in return (you still have to provide RowMapper<User> yourself to translate from ResultSet to domain object). If you don't know Spring Data project yet, Page<T> is a wonderful abstraction, not only encapsulating List<T>, but also providing metadata such as total number of records, on which page we currently are, etc.

Reasons to use

  • You consider migration to JPA or even some NoSQL database in the future.

    Since your code will rely only on methods defined in PagingAndSortingRepository and CrudRepository from Spring Data Commons umbrella project you are free to switch from JdbcRepository implementation (from this project) to: JpaRepository, MongoRepository, GemfireRepository or GraphRepository. They all implement the same common API. Of course don't expect that switching from JDBC to JPA or MongoDB will be as simple as switching imported JAR dependencies - but at least you minimize the impact by using same DAO API.

  • You need a fast, simple JDBC wrapper library. JPA or even MyBatis is an overkill

  • You want to have full control over generated SQL if needed

  • You want to work with objects, but don't need lazy loading, relationship handling, multi-level caching, dirty checking... You need CRUD and not much more

  • You want to by DRY

  • You are already using Spring or maybe even JdbcTemplate, but still feel like there is too much manual work

  • You have very few database tables

Getting started

For more examples and working code don't forget to examine project tests.

Prerequisites

Maven coordinates:

<dependency>
<groupId>com.nurkiewicz.jdbcrepository</groupId>
<artifactId>jdbcrepository</artifactId>
<version>0.4</version>
</dependency>

This project is available under maven central repository.

Alternatively you can download source code as ZIP.


In order to start your project must have DataSource bean present and transaction management enabled. Here is a minimal MySQL configuration:

@EnableTransactionManagement
@Configuration
public class MinimalConfig {
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSource dataSource() {
MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
ds.setUser("user");
ds.setPassword("secret");
ds.setDatabaseName("db_name");
return ds;
}
}

Entity with auto-generated key

Say you have a following database table with auto-generated key (MySQL syntax):

CREATE TABLE COMMENTS (
id INT AUTO_INCREMENT,
user_name varchar(256),
contents varchar(1000),
created_time TIMESTAMP NOT NULL,
PRIMARY KEY (id)
);

First you need to create domain object User mapping to that table (just like in any other ORM):

public class Comment implements Persistable<Integer> {
private Integer id;
private String userName;
private String contents;
private Date createdTime;
@Override
public Integer getId() {
return id;
}
@Override
public boolean isNew() {
return id == null;
}
//getters/setters/constructors/...
}

Apart from standard Java boilerplate you should notice implementing Persistable<Integer> where Integer is the type of primary key. Persistable<T> is an interface coming from Spring Data project and it's the only requirement we place on your domain object.

Finally we are ready to create our CommentRepository DAO:

@Repository
public class CommentRepository extends JdbcRepository<Comment, Integer> {
public CommentRepository() {
super(ROW_MAPPER, ROW_UNMAPPER, "COMMENTS");
}
public static final RowMapper<Comment> ROW_MAPPER = //see below
private static final RowUnmapper<Comment> ROW_UNMAPPER = //see below
@Override
protected <S extends Comment> S postCreate(S entity, Number generatedId) {
entity.setId(generatedId.intValue());
return entity;
}
}

First of all we use @Repository annotation to mark DAO bean. It enables persistence exception translation. Also such annotated beans are discovered by CLASSPATH scanning.

As you can see we extend JdbcRepository<Comment, Integer> which is the central class of this library, providing implementations of all PagingAndSortingRepository methods. Its constructor has three required dependencies: RowMapper, RowUnmapper and table name. You may also provide ID column name, otherwise default "id" is used.

If you ever used JdbcTemplate from Spring, you should be familiar with RowMapper interface. We need to somehow extract columns from ResultSet into an object. After all we don't want to work with raw JDBC results. It's quite straightforward:

public static final RowMapper<Comment> ROW_MAPPER = new RowMapper<Comment>() {
@Override
public Comment mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Comment(
rs.getInt("id"),
rs.getString("user_name"),
rs.getString("contents"),
rs.getTimestamp("created_time")
);
}
};

RowUnmapper comes from this library and it's essentially the opposite of RowMapper: takes an object and turns it into a Map. This map is later used by the library to construct SQL CREATE/UPDATE queries:

private static final RowUnmapper<Comment> ROW_UNMAPPER = new RowUnmapper<Comment>() {
@Override
public Map<String, Object> mapColumns(Comment comment) {
Map<String, Object> mapping = new LinkedHashMap<String, Object>();
mapping.put("id", comment.getId());
mapping.put("user_name", comment.getUserName());
mapping.put("contents", comment.getContents());
mapping.put("created_time", new java.sql.Timestamp(comment.getCreatedTime().getTime()));
return mapping;
}
};

If you never update your database table (just reading some reference data inserted elsewhere) you may skip RowUnmapper parameter or use MissingRowUnmapper.

Last piece of the puzzle is the postCreate() callback method which is called after an object was inserted. You can use it to retrieve generated primary key and update your domain object (or return new one if your domain objects are immutable). If you don't need it, just don't override postCreate().

Check out JdbcRepositoryGeneratedKeyTest for a working code based on this example.

By now you might have a feeling that, compared to JPA or Hibernate, there is quite a lot of manual work. However various JPA implementations and other ORM frameworks are notoriously known for introducing significant overhead and manifesting some learning curve. This tiny library intentionally leaves some responsibilities to the user in order to avoid complex mappings, reflection, annotations... all the implicitness that is not always desired.

This project is not intending to replace mature and stable ORM frameworks. Instead it tries to fill in a niche between raw JDBC and ORM where simplicity and low overhead are key features.

Entity with manually assigned key

In this example we'll see how entities with user-defined primary keys are handled. Let's start from database model:

CREATE TABLE USERS (
user_name varchar(255),
date_of_birth TIMESTAMP NOT NULL,
enabled BIT(1) NOT NULL,
PRIMARY KEY (user_name)
);

...and User domain model:

public class User implements Persistable<String> {
private transient boolean persisted;
private String userName;
private Date dateOfBirth;
private boolean enabled;
@Override
public String getId() {
return userName;
}
@Override
public boolean isNew() {
return !persisted;
}
public void setPersisted(boolean persisted) {
this.persisted = persisted;
}
//getters/setters/constructors/...
}

Notice that special persisted transient flag was added. Contract of [CrudRepository.save()](http://static.springsource.org/spring-data/data-commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#save(S)) from Spring Data project requires that an entity knows whether it was already saved or not (isNew()) method - there are no separate create() and update() methods. Implementing isNew() is simple for auto-generated keys (see Comment above) but in this case we need an extra transient field. If you hate this workaround and you only insert data and never update, you'll get away with return true all the time from isNew().

And finally our DAO, UserRepository bean:

@Repository
public class UserRepository extends JdbcRepository<User, String> {
public UserRepository() {
super(ROW_MAPPER, ROW_UNMAPPER, "USERS", "user_name");
}
public static final RowMapper<User> ROW_MAPPER = //...
public static final RowUnmapper<User> ROW_UNMAPPER = //...
@Override
protected <S extends User> S postUpdate(S entity) {
entity.setPersisted(true);
return entity;
}
@Override
protected <S extends User> S postCreate(S entity, Number generatedId) {
entity.setPersisted(true);
return entity;
}
}

"USERS" and "user_name" parameters designate table name and primary key column name. I'll leave the details of mapper and unmapper (see source code). But please notice postUpdate() and postCreate() methods. They ensure that once object was persisted, persisted flag is set so that subsequent calls to save() will update existing entity rather than trying to reinsert it.

Check out JdbcRepositoryManualKeyTest for a working code based on this example.

Compound primary key

We also support compound primary keys (primary keys consisting of several columns). Take this table as an example:

CREATE TABLE BOARDING_PASS (
flight_no VARCHAR(8) NOT NULL,
seq_no INT NOT NULL,
passenger VARCHAR(1000),
seat CHAR(3),
PRIMARY KEY (flight_no, seq_no)
);

I would like you to notice the type of primary key in Persistable<T>:

public class BoardingPass implements Persistable<Object[]> {
private transient boolean persisted;
private String flightNo;
private int seqNo;
private String passenger;
private String seat;
@Override
public Object[] getId() {
return pk(flightNo, seqNo);
}
@Override
public boolean isNew() {
return !persisted;
}
//getters/setters/constructors/...
}

Unfortunately library does not support small, immutable value classes encapsulating all ID values in one object (like JPA does with @IdClass), so you have to live with Object[] array. Defining DAO class is similar to what we've already seen:

public class BoardingPassRepository extends JdbcRepository<BoardingPass, Object[]> {
public BoardingPassRepository() {
this("BOARDING_PASS");
}
public BoardingPassRepository(String tableName) {
super(MAPPER, UNMAPPER, new TableDescription(tableName, null, "flight_no", "seq_no")
);
}
public static final RowMapper<BoardingPass> ROW_MAPPER = //...
public static final RowUnmapper<BoardingPass> UNMAPPER = //...
}

Two things to notice: we extend JdbcRepository<BoardingPass, Object[]> and we provide two ID column names just as expected: "flight_no", "seq_no". We query such DAO by providing both flight_no and seq_no (necessarily in that order) values wrapped by Object[]:

BoardingPass pass = boardingPassRepository.findOne(new Object[] {"FOO-1022", 42});

No doubts, this is cumbersome in practice, so we provide tiny helper method which you can statically import:

import static com.nurkiewicz.jdbcrepository.JdbcRepository.pk;
//...
BoardingPass foundFlight = boardingPassRepository.findOne(pk("FOO-1022", 42));

Check out JdbcRepositoryCompoundPkTest for a working code based on this example.

Transactions

This library is completely orthogonal to transaction management. Every method of each repository requires running transaction and it's up to you to set it up. Typically you would place @Transactional on service layer (calling DAO beans). I don't recommend placing @Transactional over every DAO bean.

Caching

Spring Data JDBC repository library is not providing any caching abstraction or support. However adding @Cacheable layer on top of your DAOs or services using caching abstraction in Spring is quite straightforward. See also: @Cacheable overhead in Spring.

Contributions

..are always welcome. Don't hesitate to submit bug reports and pull requests.

Testing

This library is continuously tested using Travis (Build Status). Test suite consists of 60+ distinct tests each run against 8 different databases: MySQL, PostgreSQL, H2, HSQLDB and Derby + MS SQL Server and Oracle tests not run as part of CI.

When filling bug reports or submitting new features please try including supporting test cases. Each pull request is automatically tested on a separate branch.

Building

After forking the official repository building is as simple as running:

$ mvn install

You'll notice plenty of exceptions during JUnit test execution. This is normal. Some of the tests run against MySQL and PostgreSQL available only on Travis CI server. When these database servers are unavailable, whole test is simply skipped:

Results :
Tests run: 484, Failures: 0, Errors: 0, Skipped: 295

Exception stack traces come from root AbstractIntegrationTest.

Design

Library consists of only a handful of classes, highlighted in the diagram below (source):

UML diagram

JdbcRepository is the most important class that implements all PagingAndSortingRepository methods. Each user repository has to extend this class. Also each such repository must at least implement RowMapper and RowUnmapper (only if you want to modify table data).

SQL generation is delegated to SqlGenerator. PostgreSqlGenerator. and DerbySqlGenerator are provided for databases that don't work with standard generator.

Changelog

0.4.1

0.4

  • Repackaged: com.blogspot.nurkiewicz -> com.nurkiewicz

0.3.2

  • First version available in Maven central repository
  • Upgraded Spring Data Commons 1.6.1 -> 1.8.0

0.3.1

0.3

0.2

0.1

License

This project is released under version 2.0 of the Apache License (same as Spring framework).

posted @ 2015-12-28 23:48 管先飞 阅读(4067) | 评论 (2)编辑 收藏

Idea是目前最好的开发工具,经收集及整理如下常用快捷键: 
一、常用快捷键:
 

     
  1.常用操作:
       Ctrl+E,可以显示最近编辑的文件列表
  Shift+Click可以关闭文件
  Ctrl+[或]可以跳到大括号的开头结尾
  Ctrl+Shift+Backspace可以跳转到上次编辑的地方
  Ctrl+F12,可以显示当前文件的结构
  Ctrl+F7可以查询当前元素在当前文件中的引用,然后按F3可以选择
  Ctrl+N,可以快速打开类
  Ctrl+Shift+N,可以快速打开文件
  Alt+Q可以看到当前方法的声明
  Ctrl+W可以选择单词继而语句继而行继而函数
  Alt+F1可以将正在编辑的元素在各个面板中定位
  Ctrl+P,可以显示参数信息
  Ctrl+Shift+Insert可以选择剪贴板内容并插入
  Alt+Insert可以生成构造器/Getter/Setter等
  Ctrl+Alt+V 可以引入变量。例如把括号内的SQL赋成一个变量
  Ctrl+Alt+T可以把代码包在一块内,例如try/catch
  Alt+Up and Alt+Down可在方法间快速移动

  2. 查询快捷键
  CTRL+N 查找类
  CTRL+SHIFT+N 查找文件
  CTRL+SHIFT+ALT+N 查找类中的方法或变量
  CIRL+B 找变量的来源
  CTRL+ALT+B 找所有的子类
  CTRL+SHIFT+B 找变量的类
  CTRL+G 定位行
  CTRL+F 在当前窗口查找文本
  CTRL+SHIFT+F 在指定窗口查找文本
  CTRL+R 在 当前窗口替换文本
  CTRL+SHIFT+R 在指定窗口替换文本
  ALT+SHIFT+C 查找修改的文件
  CTRL+E 最近打开的文件
  F3 向下查找关键字出现位置
  SHIFT+F3 向上一个关键字出现位置
  F4 查找变量来源
  CTRL+ALT+F7 选中的字符查找工程出现的地方
  CTRL+SHIFT+O 弹出显示查找内容

  3. 自动代码
  ALT+回车 导入包,自动修正
  CTRL+ALT+L 格式化代码
  CTRL+ALT+I 自动缩进
  CTRL+ALT+O 优化导入的类和包
  ALT+INSERT 生成代码(如GET,SET方法,构造函数等)
  CTRL+E 最近更改的代码
  CTRL+SHIFT+SPACE 自动补全代码
  CTRL+空格 代码提示
  CTRL+ALT+SPACE 类名或接口名提示
  CTRL+P 方法参数提示
  CTRL+J 自动代码
  CTRL+ALT+T 把选中的代码放在 TRY{} IF{} ELSE{} 里

  4. 复制快捷方式
  CTRL+D 复制行
  CTRL+X 剪切,删除行
  5. 其他快捷方式
  CIRL+U 大小写切换
  CTRL+Z 倒退
  CTRL+SHIFT+Z 向前
  CTRL+ALT+F12 资源管理器打开文件夹
  ALT+F1 查找文件所在目录位置
  SHIFT+ALT+INSERT 竖编辑模式
  CTRL+/ 注释//
  CTRL+SHIFT+/ 注释/*...*/
  CTRL+W 选中代码,连续按会有其他效果
  CTRL+B 快速打开光标处的类或方法
  ALT+ ←/→ 切换代码视图
  CTRL+ALT ←/→ 返回上次编辑的位置
  ALT+ ↑/↓ 在方法间快速移动定位
  SHIFT+F6 重构-重命名
  CTRL+H 显示类结构图
  CTRL+Q 显示注释文档
  ALT+1 快速打开或隐藏工程面板
  CTRL+SHIFT+UP/DOWN 代码向上/下移动。
  CTRL+UP/DOWN 光标跳转到第一行或最后一行下
  ESC 光标返回编辑框
  SHIFT+ESC 光标返回编辑框,关闭无用的窗口
  F1 帮助千万别按,很卡!
  CTRL+F4 非常重要下班都用

二、常用配置:
  1. IDEA内存优化
  因机器本身的配置而配置:
  \IntelliJ IDEA 8\bin\idea.exe.vmoptions
  -----------------------------------------
  -Xms64m
  -Xmx256m
  -XX:MaxPermSize=92m
  -ea
  -server
  -Dsun.awt.keepWorkingSetOnMinimize=true

posted @ 2015-09-26 11:38 管先飞 阅读(463) | 评论 (0)编辑 收藏

1、编写脚步:update.js
     /**
 * 时间对象的格式化;
 */
Date.prototype.format = function(format) {
    /*
     * eg:format="YYYY-MM-dd hh:mm:ss";
     */
    var o = {
        "M+" :this.getMonth() + 1, // month
        "d+" :this.getDate(), // day
        "h+" :this.getHours(), // hour
        "m+" :this.getMinutes(), // minute
        "s+" :this.getSeconds(), // second
        "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
        "S" :this.getMilliseconds()
    // millisecond
    }
 
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    }
 
    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                    : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
var date =new Date();
var createdate=date.format("yyyy-MM-dd hh:mm:ss");
date.setMinutes(date.getMinutes()+5);
var validtime=date.format("yyyy-MM-dd hh:mm:ss");
db.UserOnlineInfo.update(
{
  "uid" : "110000350"
},
{$set : {
  "uid" : "110000350", 
  "createtime" : createdate,
  "validtime" : validtime
}});
db.UserOnlineInfo.update(
{
  "uid" : "110000351"
},
{$set : {
  "uid" : "110000351", 
  "createtime" : createdate,
  "validtime" : validtime
}});

2、编写shell脚步:
 #/bin/bash
echo "update mongod begin"
cd /home/mongodb/mongodb-3.0.2/bin
./mongo  192.168.1.122:27108/YouLiao update.js;
echo "update mongod success"

3、 执行脚本:
/home/mongodb/mongodb-3.0.2/bin/mongo  192.168.1.122:27108/YouLiao /root/www/job/mongo-test/update.js

备注:
mongodb查询、删除类似

   
posted @ 2015-09-22 19:25 管先飞 阅读(3549) | 评论 (0)编辑 收藏

Java多线程技术  --作者:杨帆    文章连接:http://express.ruanko.com/ruanko-express_6/webpage/tech4.html
 
项目经理:杨帆

多线程编程一直是学员们比较头痛和心虚的地方,因为线程执行顺序的不可预知性和调试时候的困难,让不少人在面对多线程的情况下选择了逃避,采用单线程的方式,其实只要我们对线程有了明确的认识,再加上java内置的对多线程的天然支持,多线程编程不再是一道难以逾越的鸿沟。

进程、线程、并发执行

首先我们先来认识一下进程、线程、并发执行的概念:

  一般来说,当运行一个应用程序的时候,就启动了一个进程,当然有些会启动多个进程。启动进程的时候,操作系统会为进程分配资源,其中最主要的资源是内存空间,因为程序是在内存中运行的。

在进程中,有些程序流程块是可以乱序执行的,并且这个代码块可以同时被多次执行。实际上,这样的代码块就是线程体。线程是进程中乱序执行的代码流程。当多个线程同时运行的时候,这样的执行模式成为并发执行。

下面我以一个日常生活中简单的例子来说明进程和线程之间的区别和联系:

双向多车道道路图

这副图是一个双向多车道的道路图,假如我们把整条道路看成是一个“进程”的话,那么图中由白色虚线分隔开来的各个车道就是进程中的各个“线程”了。

  1. 这些线程(车道)共享了进程(道路)的公共资源(土地资源)。
  2. 这些线程(车道)必须依赖于进程(道路),也就是说,线程不能脱离于进程而存在(就像离开了道路,车道也就没有意义了)。
  3. 这些线程(车道)之间可以并发执行(各个车道你走你的,我走我的),也可以互相同步(某些车道在交通灯亮时禁止继续前行或转弯,必须等待其它车道的车辆通行完毕)。
  4. 这些线程(车道)之间依靠代码逻辑(交通灯)来控制运行,一旦代码逻辑控制有误(死锁,多个线程同时竞争唯一资源),那么线程将陷入混乱,无序之中。
  5. 这些线程(车道)之间谁先运行是未知的,只有在线程刚好被分配到CPU时间片(交通灯变化)的那一刻才能知道。

JVM与多线程

Java编写的程序都运行在Java虚拟机(JVM)中,在JVM的内部,程序的多任务是通过线程来实现的。

每用java命令启动一个java应用程序,就会启动一个JVM进程。在同一个JVM进程中,有且只有一个进程,就是它自己。在这个JVM环境中,所有程序代码的运行都是以线程来运行的。JVM找到程序的入口点main(),然后运行main()方法,这样就产生了一个线程,这个线程称之为主线程。当main方法结束后,主线程运行完成。JVM进程也随即退出。

操作系统将进程线程进行管理,轮流(没有固定的顺序)分配每个进程很短的一段时间(不一定是均分),然后在每个进程内部,程序代码自己处理该进程内部线程的时间分配,多个线程之间相互的切换去执行,这个切换时间也是非常短的。

Java语言对多线程的支持

Java语言对多线程的支持通过类Thread和接口Runnable来实现。这里就不多说了。这里重点强调两个地方:

// 主线程其它代码段
ThreadClass subThread = new ThreadClass();
subThread.start();
// 主线程其它代码段
subThread.sleep(1000);

有人认为以下的代码在调用start()方法后,肯定是先启动子线程,然后主线程继续执行。在调用sleep()方法后CPU什么都不做,就在那里等待休眠的时间结束。实际上这种理解是错误的。因为:

  1. start()方法的调用后并不是立即执行多线程代码,而是使得该线程变为可运行态(Runnable),什么时候运行是由操作系统决定的。
  2. Thread.sleep()方法调用目的是不让当前线程独自霸占该进程所获取的CPU资源,以留出一定时间给其他线程执行的机会(也就是靠内部自己协调)。

线程的状态切换

前面我们提到,由于线程何时执行是未知的,只有在CPU为线程分配到时间片时,线程才能真正执行。在线程执行的过程中,由可能会因为各种各样的原因而暂停(就像前面所举的例子一样:汽车只有在交通灯变绿的时候才能够通行,而且在行驶的过程中可能会出现塞车,等待其它车辆通行或转弯的状况)。

这样线程就有了“状态”的概念,下面这副图很好的反映了线程在不同情况下的状态变化。

线程在不同情况下的状态变化

  • 新建状态(New):新创建了一个线程对象。
  • 就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法。该状态的线程位于可运行线程池中,变得可运行,等待获取CPU的使用权。
  • 运行状态(Running):就绪状态的线程获取了CPU,执行程序代码。
  • 阻塞状态(Blocked):阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
    1. 等待阻塞:运行的线程执行wait()方法,JVM会把该线程放入等待池中。
    2. 同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被别的线程占用,则JVM把该线程放入锁。
    3. 其他阻塞:运行的线程执行sleep()或join()方法,或者发出了I/O请求时,JVM会把该线程置为阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
  • 死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

Java中线程的调度API

Java中关于线程调度的API最主要的有下面几个:

  1. 线程睡眠:Thread.sleep(long millis)方法
  2. 线程等待:Object类中的wait()方法
  3. 线程让步:Thread.yield() 方法
  4. 线程加入:join()方法
  5. 线程唤醒:Object类中的notify()方法

关于这几个方法的详细应用,可以参考SUN的API。这里我重点总结一下这几个方法的区别和使用。

sleep方法与wait方法的区别:

  1. sleep方法是静态方法,wait方法是非静态方法。
  2. sleep方法在时间到后会自己“醒来”,但wait不能,必须由其它线程通过notify(All)方法让它“醒来”。
  3. sleep方法通常用在不需要等待资源情况下的阻塞,像等待线程、数据库连接的情况一般用wait。

sleep/wait与yeld方法的区别:调用sleep或wait方法后,线程即进入block状态,而调用yeld方法后,线程进入runnable状态。

wait与join方法的区别:

  1. wait方法体现了线程之间的互斥关系,而join方法体现了线程之间的同步关系。
  2. wait方法必须由其它线程来解锁,而join方法不需要,只要被等待线程执行完毕,当前线程自动变为就绪。
  3. join方法的一个用途就是让子线程在完成业务逻辑执行之前,主线程一直等待直到所有子线程执行完毕。

通过上面的介绍相信同学们对java里面的多线程已经有了基本的了解和认识。其实多线程编程并没有大家想象中的那么难,只要在实际的学习,工作当中不断的加以练习和使用,相信大家很快就能掌握其中的奥妙,从而编写出赏心悦目的java程序。


posted @ 2015-04-11 17:31 管先飞 阅读(258) | 评论 (0)编辑 收藏

1、多表级联删除:
---DELETE---
DELETE from a_msg_push,a_announcement
using a_msg_push,a_announcement
where  a_msg_push.announcement_id=a_announcement.id and a_announcement.Create_time<'2014-11-19 23:59:59';

2、子查询删除:
-----------delete--------
DELETE From  t_repeat  where t_repeat.id in(
SELECT tb.id from (
SELECT *  from t_repeat   t 
where 
1=1
and 
(t.cid,t.uid ) in (select t1.cid,t1.uid from t_repeat t1 group by t1.cid,t1.uid having count(*) > 1) 
and 
t.id  not in (select min(t2.id) from t_repeat t2 group by t2.cid,t2.uid having count(*)>1) 
) as tb )

3、子表删除:
-----------delete--------
DELETE From  t_repeat  where t_repeat.id  not in
   SELECT tb.id from(
select  a.id from t_repeat a where a.id =(
select   max(b.id) from t_repeat b where a.cid=b.cid and a.uid=b.uid
   )as tb
)
posted @ 2015-03-01 22:52 管先飞 阅读(2543) | 评论 (0)编辑 收藏

感谢廖雪峰为大家提供这么好的免费教程,主要目录如下:
Git教程

posted @ 2014-10-20 10:59 管先飞 阅读(226) | 评论 (0)编辑 收藏

gooole浏览器内核已经有webkit内核移步到Bilnk开发属于Chromium Projects 的版本,下面为完整教程。

目录

  1. Blink's Mission:
  2. Participating
    1. 2.1 Discussions
    2. 2.2 Watching for new features
    3. 2.3 Committing and reviewing code
    4. 2.4 Developing Blink
    5. 2.5 How do I port Blink to my platform?
  3. Web Platform Changes: Guidelines
    1. 3.1 Scope
    2. 3.2 Policy for shipping and removing web platform API features
    3. 3.3 Trivial Changes
    4. 3.4 Vendor Prefixes
  4. Web Platform Changes: Process
    1. 4.1 Launch Process: New Features
    2. 4.2 Launch Process: Deprecation
    3. 4.3 API Owners
    4. 4.4 API Review
    5. 4.5 Feature Dashboard
    6. 4.6 Guiding Principles for Process
  5. Testing
  6. Architectural Changes
  7. Developer FAQ
  8. Subpage Listing
    友情连接:
    https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html
posted @ 2014-10-19 21:09 管先飞 阅读(323) | 评论 (0)编辑 收藏

如下两条常用sql,统计分类数据,你能说出区别吗?
一、常用sql一:
select 
r.cid,
r.depart_id,
r.employ_id,
r.create_by,
count(DISTINCT r.form_type) as dailyReportNum
FROM 
report r
where 
1=1 
GROUP BY 
r.employ_id

二、常用sql二:
select 
r.cid,
r.depart_id,
r.employ_id,
r.create_by,
sum(case WHEN df.form_type=1 then 1 else 0 end ) as dailyReportNum
FROM 
report r
where 
1=1 
GROUP BY 
r.employ_id


posted @ 2014-09-18 17:05 管先飞 阅读(3564) | 评论 (4)编辑 收藏

HSSF和XSSF的区别:
http://poi.apache.org/spreadsheet/index.html
POI官方详情教程:
http://poi.apache.org/spreadsheet/quick-guide.html

Index of Features

posted @ 2014-09-18 12:24 管先飞 阅读(3800) | 评论 (2)编辑 收藏

现阶段JAVA操作Excel的JAR主要有apache 的POI及jxl.Jxl方便快捷,POI用于对复杂Excel的操作。

Jxl官网:http://www.andykhan.com/jexcelapi/index.html


一、Jxl的API

Jxl的API主要有三个包,jxl,jxl.format,jxl.write。如果单独的分析API,可能对于更明确的了解此API没有太多的帮助,我们还是从Excel文件的层次来剥离此API吧。

一个excel文件由一个工作簿组成,一个工作簿又由n个工作表组成,每个工作表又由多个单元格组成。对应于Jxl中的结构为

读文件(包jxl)

写文件(包jxl.write)

说明

Workbook 

WritableWorkbook

工作簿

Sheet

WritableSheet

工作表

Cell/Image/Hyperlink

WritableCell/WritableImage//WritableHyperlink

单元格/图像/超链接

       单元格(此处指文本单元格,图像及链接和单元格做为一个层次)分为好多种,所以在API的设计中将Cell作为一个接口而存在。 对应的jxl中的结构为:

读文件(包jxl)

写文件(包jxl.write)

说明

Cell

WritableCell

单元格

BooleanCell

Boolean

布尔值单元格

DateCell

DateTime

时间单元格

ErrorCell

 

形式错误的单元格

LabelCell

Label

文本单元格

NumberCell

Number

数字单元格

FormualCedll

Formual

公式单元格

 

Blank

空格单元格

BooleanFormualCell

 

布尔公式单元格

DateFormualCell

 

时间公式单元格

ErrorFormualCell

 

错误公式单元格

StringFormualCell

 

文本公式单元格

NumberFormualCell

 

数字公式单元格

 

而有的时候,我们可能将几个单元格作为一个整体来处理,在API中对应的则是:

    jxl.Range 

 

    虽然数据是电子表格的核心,但是同时其也需要一些辅助类,比如文件格式设置,工作表设置与显示效果,单元格设置与显示效果等。按照其层次,则依次有以下接口或类。

读文件(包jxl)

写文件(包jxl.write)

说明

WorkbookSettings

WorkbookSettings(包jxl)

设置workbook属性的bean

SheetSettings

SheetSettings(包jxl)

设置具体sheet的属性的bean(比如表头表底等)

HeaderFooter

HeaderFooter(包jxl)

表示表头表底类

HeaderFooter.Contents

HeaderFooter.Contents(包jxl)

具体表头表底设置

CellFeatures

WritableCellFeautres

表格内容相关设置(验证)

CellReferenceHelper

 

得到引用单元格相关属性

CellType

 

表格相关类型

CellView

CellView(包jxl)

表格视图相关设置

CellFormat

WritableCellFormat

表格显示样式设置

 

BoldStyle

边框枚举

 

DateFormat

时间格式

 

DateFormats

时间格式枚举

 

NumbreFormat

数据格式

 

NumbreFormats

数字模式枚举

 

WritableFont

字体设置

 

WriteableFont.Fontname

静态字体内部类

 

最后,关于Jxl.format包,此包主要是一些与具体样式有关的接口和枚举,不进行具体描述。
文章摘自:http://blog.csdn.net/surgent/article/details/5836580

posted @ 2014-09-18 09:21 管先飞 阅读(1984) | 评论 (0)编辑 收藏

 网络盒子目前市面上主流的有小米盒子、乐视盒子、Uhost、天猫盒子,各种盒子的功能都差不多,现以小米盒子为列简单描述一下小米盒子。
一、小米盒子的最新功能:
1、观看各种大片电影、电视剧。
2、各种手游、教育培训。
二、小米盒子的缺陷:
1、用户直观搜索相关的视频太困难,搜索功能太局限。
2、网络电视不支持,不过现在可以安装其他视频软件来观看网络电视。
3、对手机端的安卓apk支持不好。
三、小米盒子的潜力:
1、小米盒子的操作系统采用andriod操作系统,以后可以包含手机上有的一切功能。
2、以后在游戏、教育、影院、购物比手机更有发展潜力。
四、小米盒子的使用技巧:
1、小米盒子最新miniui已经支持root,所以可以安装一切安卓应用(安装方法类似手机)。
2、小米盒子系统更新保持网络畅通。
4、可以将手机片源用电视播放,也可用手机玩游戏。
简单写几个小文字睡觉,希望帮电视盒子打打广告,以后希望盒子发展得更好,丰富用户余业观看在客厅的娱乐体验。
posted @ 2014-06-15 01:34 管先飞 阅读(1988) | 评论 (10)编辑 收藏

     摘要: package org.jeecgframework.core.util.excel;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.lang.reflect.Field;import...  阅读全文
posted @ 2014-05-29 11:14 管先飞 阅读(7815) | 评论 (0)编辑 收藏

JSON转换的四种各种情况:

1. //把java 对象列表转换为json对象数组,并转为字符串

    JSONArray array = JSONArray.fromObject(userlist);
    String jsonstr = array.toString();

2.//把java对象转换成json对象,并转化为字符串

  JSONObject object = JSONObject.fromObject(invite);
   String str=object.toString());

3.//把JSON字符串转换为JAVA 对象数组

  String personstr = getRequest().getParameter("persons");
  JSONArray json = JSONArray.fromObject(personstr);
  List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);
4.//把JSON字符串转换为JAVA 对象

  JSONObject jsonobject = JSONObject.fromObject(str);
  PassportLendsEntity passportlends = null;
  try {
   //获取一个json数组
   JSONArray array = jsonobject.getJSONArray("passports");
   //将json数组 转换成 List<PassPortForLendsEntity>泛型
   List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
   for (int i = 0; i < array.size(); i++) {   
            JSONObject object = (JSONObject)array.get(i);  
            PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
              PassPortForLendsEntity.class);
            if(passport != null){
             list.add(passport);
            }  
     }
   //转换PassportLendsEntity 实体类
  passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);

  str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",

  \"lenddate\":\"2010-07-19T00:00:00\",\"lendcounts\":4,\"
  passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
  {\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
  {\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
  {\"passportid\":\"K905199\",\"name\":\"贺明\",\"passporttype\":\"K\"}]}";
相关的jar包:

posted @ 2014-04-16 01:11 管先飞 阅读(2734) | 评论 (0)编辑 收藏


CriteriaQuery cq = new CriteriaQuery(MsgRecordEntity.class, datagrid);
cq.add(Restrictions.eq("cid", cid));
Criterion c1=cq.and(Restrictions.eq("sendEid", sendEid),Restrictions.eq("pointEid", pointEid)) ;
Criterion c2=cq.and(Restrictions.eq("sendEid",pointEid ),Restrictions.eq("pointEid", sendEid)) ;
cq.or(c1, c2);
cq.add(Restrictions.eq("flag",AilkConstant.FLAG_NOT_REMOVED));
cq.addOrder("sendDate", SortDirection.desc);
cq.add();
posted @ 2014-04-14 10:42 管先飞 阅读(2169) | 评论 (0)编辑 收藏

1、修改内联表
update a_locationservice al,t_kxt_executor_info t 
set al.objid= t.id
where al.location_id=t.end_location_id
and  al.objtype='8' and al.objid is null
2、修改级联表:
update t_kxt_executor_info_detail tid
LEFT JOIN 
   t_kxt_common_reports crep  
on 
 crep.id=tid.obj_id
set tid.flag='2'
where  (tid.obj_type='terminalPhotograph' or tid.obj_type='requestInfo' or tid.obj_type='terminalInfo')  and  crep.id is null
posted @ 2014-02-26 11:09 管先飞 阅读(232) | 评论 (0)编辑 收藏

     摘要: 关于Tomcat: 安装Tomcat:sudo apt-get install tomcat7 配置tomcat:http://wiki.ubuntu.org.cn/Tomcat 启动tomcat:my-instance/bin/startup.sh关闭tomcat:my-instance/bin/shutdown.sh关于系统进程:ps ax   显示当前...  阅读全文
posted @ 2014-02-25 10:17 管先飞 阅读(477) | 评论 (0)编辑 收藏

1.UNIX很简单。但需要有一定天赋的人才能理解这种简单。——Dennis Ritchie
2.软件在能够复用前必须先能用。——Ralph Johnson
3.优秀的判断力来自经验,但经验来自于错误的判断。——Fred Brooks
4.‘理论’是你知道是这样,但它却不好用。‘实践’是它很好用,但你不知道是为什么。程序员将理论和实践结合到一起:既不好用,也不知道是为什么。——佚名
5.当你想在你的代码中找到一个错误时,这很难;当你认为你的代码是不会有错误时,这就更难了。——Steve McConnell 《代码大全》
6.如果建筑工人盖房子的方式跟程序员写程序一样,那第一只飞来的啄木鸟就将毁掉人类文明。——Gerald Weinberg
7.项目开发的六个阶段:1. 充满热情 2. 醒悟 3. 痛苦 4. 找出罪魁祸首 5. 惩罚无辜 6. 褒奖闲人——佚名
8.优秀的代码是它自己最好的文档。当你考虑要添加一个注释时,问问自己,“如何能改进这段代码,以让它不需要注释?”——Steve McConnell 《代码大全》
9.我们这个世界的一个问题是,蠢人信誓旦旦,智人满腹狐疑。——Bertrand Russell
10.无论在排练中演示是如何的顺利(高效),当面对真正的现场观众时,出现错误的可能性跟在场观看的人数成正比。——佚名
11.罗马帝国崩溃的一个主要原因是,没有0,他们没有有效的方法表示他们的C程序成功的终止。——Robert Firth
12.C程序员永远不会灭亡。他们只是cast成了void。——佚名
13.如果debugging是一种消灭bug的过程,那编程就一定是把bug放进去的过程。——Edsger Dijkstra
14.你要么要软件质量,要么要指针算法;两者不可兼得。——(Bertrand Meyer)
15.有两种方法能写出没有错误的程序;但只有第三种好用。——Alan J. Perlis
16.用代码行数来测评软件开发进度,就相对于用重量来计算飞机建造进度。——比尔·盖茨
17.最初的90%的代码用去了最初90%的开发时间。余下的10%的代码用掉另外90%的开发时间。——Tom Cargill
18.程序员和上帝打赌要开发出更大更好——傻瓜都会用的软件。而上帝却总能创造出更大更傻的傻瓜。所以,上帝总能赢。——Anon

转自:http://www.zhishihai.net/diannaowangluo/biancheng/bianchengsixiang/145.html
posted @ 2013-11-10 18:54 管先飞 阅读(254) | 评论 (0)编辑 收藏

package com.exl.test;
import java.awt.Color;
import java.io.File;
import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.exl.utils.ColourUtil;
public class Test {
   public static void main(String[] args) throws Exception {
  String title="报表测试";
  String[] navTitle= {"第一行","第二行","第三行","第四行","第五行","第六行","第七行","第八行"};  
  String[][] content={
  {"1","2","第naionfdapfn三行","第四niaodnfoanfdas行","第noandfoasnjdf五行","第六sdfadsafas行","第afdadfasdfs七a行","第adfasfdasf八行"},
  {"2","2","第三行","第四行","第五行","第六行","第七行","sssssssssss第八sss行"},
  {"3","2","第三行","第四行","第五行","第六行","第七行","第八行sssssssssssss"},
  {"4","2","第三行","第四行","第sssssssssssssss五行","第ssssssssssssssssssss六行","第七行","第八行sssssssss"},
  {"5","2","第三行","第ddddddddddddddddddddddddddddddddddddddddddddddddddddddddd四行","第五行","第六行","第七行","第八行"},
  {"6","2","第三行","第四行","第五行","第六行","第七行","第八行"},
  {"7","2","第三行","第四ddddddddddddddddddddddddddddddd行","第五行","第六行","第七行","第八行"},
  {"8","2","第三行","第四行","第五行","第六行","第七行","第八行"},
  {"9","2","第三行","第ddddddddddddddddddddddddddddddd四行","第五行","第六行","第七行","第八行"},
  {"10","2","第三行","第四行","第五行","第六行","第七行","第八行"},
  {"11","2","第三行","第四行","第五行","第六dddddddddddddd行","第七行","第八行"},
  {"12","2","第三行","第四行","第五行","第六行","第七行","第八行"},
  {"13","2","第三行","第四行","第五行","dddddddddddddddddddddd第六行","第七行","第八行"},
  {"14","2","第三行","第四行","第五行","第dddddddddddddddddddddd六行","第七行","第八行"},
  };  
  String filePath="D:\\DesignSource\\tempT";
  String fileName="NewProject.xls";
  File dir=new  File(filePath);
  if(!dir.isDirectory()){
  dir.mkdirs();
  }
  
       File file = new File(filePath+"\\"+fileName);
       WritableWorkbook workbook = Workbook.createWorkbook(file);  
       WritableSheet sheet = workbook.createSheet("报表统计", 0);  //单元格
       /**
        * title
        */
       Label lab = null;  
       WritableFont   wf2   =   new   WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
       WritableCellFormat wcfTitle = new WritableCellFormat(wf2);
       wcfTitle.setBackground(jxl.format.Colour.IVORY);  //象牙白
       wcfTitle.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN,jxl.format.Colour.BLACK); //BorderLineStyle边框
       //       wcfTitle.setVerticalAlignment(VerticalAlignment.CENTRE); //设置垂直对齐
       wcfTitle.setAlignment(Alignment.CENTRE); //设置垂直对齐
       
       CellView navCellView = new CellView();  
       navCellView.setAutosize(true); //设置自动大小
       navCellView.setSize(18);
       
       lab = new Label(0,0,title,wcfTitle); //Label(col,row,str);   
       sheet.mergeCells(0,0,navTitle.length-1,0);
       sheet.setColumnView(0, navCellView); //设置col显示样式
       sheet.setRowView(0, 1600, false); //设置行高
       sheet.addCell(lab);  
       /**
        * status
        */
       
       
       /**
        * nav
        */
       jxl.write.WritableFont wfcNav =new jxl.write.WritableFont(WritableFont.ARIAL,12, WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.BLACK);
        WritableCellFormat wcfN=new WritableCellFormat(wfcNav);
        
        Color color = Color.decode("#0099cc"); // 自定义的颜色
workbook.setColourRGB(Colour.ORANGE, color.getRed(),color.getGreen(), color.getBlue());
       wcfN.setBackground(Colour.ORANGE);
       wcfN.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN,jxl.format.Colour.BLACK); //BorderLineStyle边框
       wcfN.setAlignment(Alignment.CENTRE); //设置水平对齐
       wcfN.setWrap(false); //设置自动换行
       for(int i=0;i<navTitle.length;i++){
      lab = new Label(i,1,navTitle[i],wcfN); //Label(col,row,str);   
      sheet.addCell(lab);  
      sheet.setColumnView(i, new String(navTitle[i]).length());  
       }
       
       /**
        * 内容
        */
       jxl.write.WritableFont wfcontent =new jxl.write.WritableFont(WritableFont.ARIAL,12, WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);
       WritableCellFormat wcfcontent = new WritableCellFormat(wfcontent);
       wcfcontent.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN,jxl.format.Colour.BLACK); //BorderLineStyle边框
       wcfcontent.setAlignment(Alignment.CENTRE);
       CellView cellView = new CellView();  
       cellView.setAutosize(true); //设置自动大小
       for(int i=0;i<content.length;i++){  
           for(int j=0;j<content[i].length;j++){  
          sheet.setColumnView(i, cellView);//根据内容自动设置列宽  
          lab = new Label(j,i+2,content[i][j],wcfcontent); //Label(col,row,str);  
               sheet.addCell(lab);  
//               sheet.setColumnView(j, new String(content[i][j]).length());  
           }  
       }  
       
       workbook.write();  
       workbook.close();  
}
}
posted @ 2013-10-17 01:18 管先飞 阅读(39916) | 评论 (1)编辑 收藏

1、请求下载地址:
try {
//执行检索
cmsSupSubmitSiteStatBeanList = cmsSupSubmitSiteInfoMngService.govStat(condition);
//根据条件查找
cmsSupSubmitSiteInfoMngBeanList = cmsSupSubmitSiteInfoMngService.findByConditionStat(condition);
//临时文件位置
String path=this.getServletConfig().getServletContext().getRealPath("\\upload\\temp");
File ftemp=new File(path);
if (!ftemp.exists()) {
ftemp.mkdirs();//不存在则创建
}
//生成临时文件名
String saveFilename = DateUtil.formatNowDateTime("yyyyMMddHHmmssSSS")+getNewName()+ ".csv";
WritableWorkbook book = Workbook.createWorkbook(new File(path + "\\"+saveFilename));// 创建excel文件
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet("网站信息统计表", 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//标题
String[] title1 = {"单位名称"
,"1月"
,"2月"
,"3月"
,"4月"
,"5月"
,"6月"
,"7月"
,"8月"
,"9月"
,"10月"
,"11月"
,"12月"
,"总报送量"
,"报送率"
,"分数"
,"加减分"
,"总分数"
};
//表头
for(int i=0;i<title1.length;i++){
//第n列第一行标识表头
Label label = new Label(i, 0, title1[i]);
sheet.addCell(label); //将定义好的单元格添加到工作表中 
}
//内容
for (int i = 0; i < cmsSupSubmitSiteStatBeanList.size(); i++) {
CmsSupSubmitSiteStatBean bean = cmsSupSubmitSiteStatBeanList.get(i);
//内容
String[] rs1 = {  bean.getDeptName()
,String.valueOf(bean.getUsed01()) + "/" + String.valueOf(bean.getSup01())
,String.valueOf(bean.getUsed02()) + "/" + String.valueOf(bean.getSup02())
,String.valueOf(bean.getUsed03()) + "/" + String.valueOf(bean.getSup03())
,String.valueOf(bean.getUsed04()) + "/" + String.valueOf(bean.getSup04())
,String.valueOf(bean.getUsed05()) + "/" + String.valueOf(bean.getSup05())
,String.valueOf(bean.getUsed06()) + "/" + String.valueOf(bean.getSup06())
,String.valueOf(bean.getUsed07()) + "/" + String.valueOf(bean.getSup07())
,String.valueOf(bean.getUsed08()) + "/" + String.valueOf(bean.getSup08())
,String.valueOf(bean.getUsed09()) + "/" + String.valueOf(bean.getSup09())
,String.valueOf(bean.getUsed10()) + "/" + String.valueOf(bean.getSup10())
,String.valueOf(bean.getUsed11()) + "/" + String.valueOf(bean.getSup11())
,String.valueOf(bean.getUsed12()) + "/" + String.valueOf(bean.getSup12())
,String.valueOf(bean.getTolUsed()) + "/" + String.valueOf(bean.getTolSup())
,String.valueOf(bean.getUsedRate()) + "%"
,String.valueOf(bean.getPoint())
,String.valueOf(bean.getPmPoint())
,String.valueOf(bean.getTolPoint())
};
//内容从第二行开始打印
for (int j = 0; j < rs1.length; j++) {
Label label = new Label(j, i+1, rs1[j]);
 sheet.addCell(label);
}
}
// 打印详细========================================================================================
String[] stDtl = {  "单位名称"
,"标题"
,"加减分"
,"报送时间"
};
WritableSheet sheet2 = book.createSheet("网站信息采用标题", 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//标题
//表头
for(int i=0;i<stDtl.length;i++){
//第n列第一行标识表头
Label labe2 = new Label(i, 0, stDtl[i]);
sheet2.addCell(labe2);
}
//内容
String titleVar="";
int flagNum=0;
for( int i = 0; i < cmsSupSubmitSiteInfoMngBeanList.size(); i ++ ){
CmsSupSubmitSiteInfoMngBean bean = cmsSupSubmitSiteInfoMngBeanList.get(i);
String[] rs2 = {bean.getSpDeptName()
,bean.getSupTitle()
,String.valueOf(bean.getMsgPmPoint())
,bean.getAddDate()
};
if(!titleVar.equals(rs2[0])){
for (int x =0; x < rs2.length; x++) {
Label labeVar2 = new Label(x, i+1, rs2[x]);
sheet2.addCell(labeVar2);
}
   }else{
    //内容从第二行开始打印
       //sheet.mergeCells(int col1,int row1,int col2,int row2);//左上角到右下角    
        sheet.mergeCells(0,1, 0,flagNum);//左上角到右下角     ,列,行,列,行
for (int j =1; j < rs2.length; j++) {
Label labe2 = new Label(j, i+1, rs2[j]);
sheet2.addCell(labe2);
}
   }
flagNum++;
titleVar=rs2[0];
}
// // 将定义好的单元格添加到工作表中
// /*
// * 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义 单元格位置是第二列,第一行,
// 值为789.123
// */
// // jxl.write.Number number = new jxl.write.Number( 1 , 0 , 555.12541 );
// // sheet.addCell(number);
// 写入数据并关闭文件
book.write();
book.close();
// 将生成的文件下载
AttUploadsServlet servlet=new AttUploadsServlet();
servlet.downLoadFile(req, resp, "网站信息统计.csv", path + "\\" + saveFilename);
} catch (Exception e) {
System.out.println(e);
}

2、下载附件:
/**
* 文档下载
* @param request 
* @param response
* @param fileName 文件名
* @param attachment -文件路径
* @return
*/
public boolean downLoadFile(HttpServletRequest request,HttpServletResponse response
,String fileName,String attachment) {
try
{
String filepath =attachment;
File file = new File(filepath);
if(!file.exists())
{
return false;
//throw new Exception(filepath+"文件未找到!");
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;
response.reset();                                            //非常重要
//纯下载方式
response.setContentType("application/x-msdownload"); 
response.setHeader("Content-Disposition", "attachment; filename=" 
+ (new String(fileName.getBytes("gb2312"),"ISO-8859-1"))); 
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) >0)
out.write(buf,0,len);
out.flush();
br.close();
return true;
}
catch(Exception ex)
{
log.info(ex.getMessage());
return false;
}
}

多学一点:划服务器下载附件
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.*"%>
<%@page import="java.io.File"%>
<%@page import="java.io.OutputStream"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.net.URL"%>
<%@page import="java.net.URLConnection"%>
<!-- 以上这行设定本网页为Word格式的网页 -->  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<%
   String refFilePath= request.getRealPath(new String(request.getParameter("fileSrc").getBytes("ISO-8859-1"),"UTF-8"));
   //String docName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
  request.setCharacterEncoding("UTF-8");
  String docName = request.getParameter("fileName");
  try{
        /* 创建输入流 */  
         InputStream is = this.getClass().getClassLoader().getResourceAsStream("project.properties"); 
        Properties p = new Properties();
      try {
     p.load(is);       //Properties 对象已生成,包括文件中的数据
      }catch(IOException e){
       e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
      }
      
      String refFp=p.getProperty("xzql.refFilePath");
        URL ul=new URL(refFp+new String(request.getParameter("fileSrc").getBytes("ISO-8859-1"),"UTF-8"));
        URLConnection conn=ul.openConnection();
        InputStream inStream = conn.getInputStream();
        String disName = java.net.URLEncoder.encode(docName, "UTF-8");  
        response.reset();  
        response.setContentType("application/x-msdownload");  
        response.addHeader("Content-Disposition",  
                "attachment; filename=\"" + disName + "\"");  
         
        
        byte[] buf = new byte[4096];  
        /* 创建输出流 */  
        ServletOutputStream servletOS = response.getOutputStream();  
        int readLength;
        int alllength=0;
        while (((readLength = inStream.read(buf)) != -1)) {  
            servletOS.write(buf, 0, readLength); 
            alllength+= readLength;
        }
        response.setContentLength(alllength); 
        inStream.close();  
        servletOS.flush();  
        servletOS.close();  
   }catch(Exception e){
  out.print("文件不存在! ");
  e.printStackTrace();
  %> 
  </html>

2).struts2下载Excel:
http://blog.csdn.net/weinianjie1/article/details/5941042





posted @ 2013-10-14 01:46 管先飞 阅读(594) | 评论 (0)编辑 收藏

myeclipse中的字体看上去比较舒服,但是忽然使用eclipse找不到该字体。具体介绍及解决办法如下:
myeclipse用Courier New这个字体,但是这个字体在Eclipse中默认是选不出来的。到Eclipse preference--->colors and fonts中 找到选择字体的地方(选择字体的下拉菜单中是找不到Courier New的),在左下方有一行蓝色的字“显示更多字体”,点击后会出现一个新的界面,这里会显示你机器上所有的字体。找到Courier New后点击右键选择[显示],然后关闭这个界面。回到更改字体的界面后你会发现下拉菜单中已经可以选择Courier New搜索这个字体了。然后将该字体默认即可!
posted @ 2013-09-15 23:51 管先飞 阅读(3213) | 评论 (0)编辑 收藏

mysql代码:
select sp.singer_name as singerName,sp.fans_value as fansValue

From singer_publish sp 
where 1=1   
order by  (case  when  (sp.fans_value is null or sp.fans_value='' or sp.fans_value<1) then 1 else 0 end ),sp.fans_value; 
posted @ 2013-09-10 15:11 管先飞 阅读(868) | 评论 (0)编辑 收藏

 /*
* 智能机浏览器版本信息:
*/
  var browser={
    versions:function(){
           var u = navigator.userAgent, app = navigator.appVersion;
           return {//移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部
            };
         }(),
         language:(navigator.browserLanguage || navigator.language).toLowerCase()
if(browser.versions.iPhone || browser.versions.iPad)
{
}
else
{
 
}
posted @ 2013-09-10 15:10 管先飞 阅读(260) | 评论 (0)编辑 收藏