ï»??xml version="1.0" encoding="utf-8" standalone="yes"?> Blogged with Flock Blogged with Flock Tags: java Blogged with Flock Tags: java
  private long id;
  private List<WebSite> trustedSites;
  private List<WebSite> blockedSites;
 Â
  public CustomService() {
    this.trustedSites = new ArrayList<WebSite>();
    this.blockedSites = new ArrayList<WebSite>();
  }
  public List<WebSite> getBlockedSites() {
    return blockedSites;
  }
  public void setBlockedSites(List<WebSite> blockedSites) {
    this.blockedSites = blockedSites;
  }
  public long getId() {
    return id;
  }
  public void setId(long id) {
    this.id = id;
  }
  public List<WebSite> getTrustedSites() {
    return trustedSites;
  }
  public void setTrustedSites(List<WebSite> trustedSites) {
    this.trustedSites = trustedSites;
  }
 Â
  public void addTrustedSites(String site, boolean isNewData) {
    this.trustedSites.add(new WebSite(site, isNewData));
  }
 Â
  public void addBlockedSites(String site, boolean isNewData) {
    this.blockedSites.add(new WebSite(site, isNewData));
  }
}
  private String website;
  private boolean isNewData;
 Â
  public WebSite() {
   Â
  }
  public WebSite(String website) {
    this.website = website;
  }
  public WebSite(String website, boolean isNewData) {
    this.website = website;
    this.isNewData = isNewData;
  }
  public boolean isIsNewData() {
    return isNewData;
  }
  public void setIsNewData(boolean isNewData) {
    this.isNewData = isNewData;
  }
  public String getWebsite() {
    return website;
  }
  public void setWebsite(String website) {
    this.website = website;
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final WebSite other = (WebSite) obj;
    if (this.website == null || !this.website.equals(other.website)) {
      return false;
    }
    if (this.isNewData != other.isNewData) {
      return false;
    }
    return true;
  }
  @Override
  public int hashCode() {
    int hash = 7;
    hash = 13 * hash + (this.website != null ? this.website.hashCode() : 0);
    hash = 13 * hash + (this.isNewData ? 1 : 0);
    return hash;
  }
 Â
}
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="model.cnm.cf">
  <class name="CustomService" table="custom_services">
    <id name="id" column="id" type="long">
      <generator class="native"/>
    </id>
    <list name="trustedSites" table="cf_trusted_sites" cascade="all">
      <key column="service_id"/>
      <list-index column="pos"/>
      <composite-element class="WebSite">
        <property name="website" column="site" type="string"/>
        <property name="isNewData" column="isNewData" type="boolean"/>
      </composite-element>
    </list>
    <list name="blockedSites" table="cf_blocked_sites">
      <key column="service_id"/>
      <index column="pos"/>
      <composite-element class="WebSite">
        <property name="website" column="site" type="string"/>
        <property name="isNewData" column="isNewData" type="boolean"/>
      </composite-element>
    </list>
  </class>
</hibernate-mapping>
 2   private CustomService service;
 3   private long id;
 4  Â
 5   @Test
 6   public void save() {
 7     session = HibernateUtil.getSession();
 8     service = new CustomService();
 9     service.addBlockedSites("www.whitehouse.com", true);
10     service.addBlockedSites("www.whitehouse.com", false);
11Â Â Â Â Â
12     service.addTrustedSites("www.google.cn", true);
13     service.addTrustedSites("www.google.cn", false);
14Â Â Â Â Â
15Â Â Â Â Â
16Â Â Â Â Â session.save(service);
17     id = service.getId();
18Â Â Â Â Â session.flush();
19Â Â Â Â Â session.close();
20Â Â Â Â Â
21     session = HibernateUtil.getSession();
22     Transaction tr = null;
23     try {
24       tr = session.beginTransaction();
25Â Â Â Â Â Â Â session.save(service);
26     } catch (Exception e) {
27       if (tr != null) {
28Â Â Â Â Â Â Â Â Â tr.commit();
29Â Â Â Â Â Â Â }
30     } finally {
31Â Â Â Â Â Â Â session.close();
32Â Â Â Â Â }
33Â Â Â Â Â
34     session = HibernateUtil.getSession();
35     service = getService();
36     assertEquals(2, service.getBlockedSites().size());
37     assertEquals(2, service.getTrustedSites().size());
38Â Â Â }
39Â Â Â
40   private CustomService getService() {
41     return (CustomService) session.get(CustomService.class, id);
42Â Â Â }
43Â Â Â Â Â
44Â
45Â }
2Â session.save(service);
3Â session.flush();
4Â session.close();
åˆç»™CustomServiceåŠ äº†ä¸€ä¸ªnameå—æ®µ,¾l“果表明,在直接用session.flush()å’Œsession.close()的时å€?æ ÒŽœ¬ž®±æ²¡æœ‰æäº?ä¸è¿‡å¥‡æ€ªçš„æ˜?½W¬ä¸€‹Æ¡è¿™æ ·åšæ€Žä¹ˆä¼šæäº¤äº†.
优点åQ?br />
有空å¦ä¹ 一下manifest的其他的用é€?
Tags: java
Hibernate.groovy
Instead of interface, I use Closure for callback
Blogged with Flock
Tags: hibernategroovy
å‘é€soap message的代ç 如ä¸?
public class MessageSender {
/**
* Logger for this class
*/
private static final Log logger = LogFactory.getLog(MessageSender.class);
private HttpClient httpClient;
private PostMethod postMethod;
private MessageFactory messageFactory;
private String url;
private NameValuePair sessionId;
public MessageSender(String ip){
this.httpClient = new HttpClient();
try {
this.messageFactory = MessageFactory.newInstance();
} catch (SOAPException e) {
logger.error(e.getMessage());
}
this.url = generateRequestUrl(ip);
}
private String generateRequestUrl(String ip) {
return "http://" + ip + ":8080/vantage/TR069";
}
public SOAPMessage sendMessage(SOAPMessage input) throws IOException, SOAPException {
this.postMethod = new PostMethod(this.url);
byte[] dataAsBytes = null;
if (input == null) {
logger.debug("Send a empty post");
dataAsBytes = new byte[0];
} else {
ByteArrayOutputStream data = new ByteArrayOutputStream();
input.writeTo(data);
dataAsBytes = data.toByteArray();
}
RequestEntity entity = new ByteArrayRequestEntity(dataAsBytes);
this.postMethod.setRequestEntity(entity);
if (this.sessionId != null) {
this.postMethod.addParameter(this.sessionId);
}
this.httpClient.executeMethod(this.postMethod);
sessionId = this.postMethod.getParameter("SessionID");
InputStream in = this.postMethod.getResponseBodyAsStream();
if (null == in) {
return null;
}
return this.messageFactory.createMessage(null, in);
}
}
最åˆçš„code里é¢,åªæœ‰ä¸€ä¸ªPostMethod,˜q™æ ·æ¯æ¬¡ä¼šä¸€ç›´keep一个http˜qžæŽ¥.å› äØ“åœ¨serverç«?åªç›´æŽ¥ç”¨http sessionæ¥ä¿å˜server的状æ€çš„,所以必™å»è¦æ˜¯ä¿æŒæ˜¯ä¸€ä¸ªsession.用一个PostMethodå¯ä»¥åšåˆ°˜q™ç‚¹.ä¸è¿‡å¥‡æ€ªçš„æ˜?在命W¬äºŒ‹Æ¡è¯·æ±‚的时å€?怎么都拿ä¸åˆ°http connection.也ä¸çŸ¥é“æ˜¯ä¸æ˜¯httpclientçš„bug.åŽæ¥æ‰æ¯‹Æ¡è°ƒç”¨éƒ½é‡æ–°create一个PostMethod,但是把第一‹Æ¡å¾—到的sessionID add˜q›åŽ».
inverse会媄å“到saveæ—¶å€™çš„è¡ŒäØ“ã€‚å¦‚æžœä¸€ç«¯çš„inverseè®¾äØ“trueåQŒåˆ™save应该在å¦ä¸€ç«¯è¿›è¡?/p>
The Java language gives you all the room you need to write code that would be very difficult for others to understand. Java also permits you to write code that is very easy to understand. Most development teams would prefer the latter.
A style guide provides provides a map so that the code generated by a group of programmers will be consistent and, therefore, easier to read and maintain. Many people do not care for the style guide offered by Sun. This document is one alternative.
This document covers most areas where there could be confusion or difference of opinion. Areas that have never been a problem in our experience are undocumented.
if
, while
, for
, switch
, and catch
must be followed by a space.class Order
{
// fields
// constructors
// methods
}
All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0' through '9') only. No underscores, dollar signs or non-ascii characters.
All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case. (examples)
Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided. (examples)
do..while
.
(examples and reasoning)return
in the middle of a method.
(reasoning)continue
.
(reasoning)break
other than in a switch statement.
(reasoning)
Use a separate line for an increment or decrement. (examples and reasoning)
Never use pre-increment or pre-decrement (examples and reasoning)
"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."
--- Martin Fowler, Refactoring: Improving the Design of Existing Code
Rather than trying to document how you perform a complex algorithm, try to make the algorithm easier to read by introducing more identifiers. This helps in the future in case the algorithm changes but someone forgets to change the documentation. (examples and reasoning)
原文链接�http://www.javaranch.com/style.jsp
比如说有˜q™æ ·ä¸€ä¸ªç±»Server,è¦æ ¹æ®server.propertiesæ¥åˆå§‹åŒ–,ä¸€å¼€å§‹çš„ä»£ç æ˜¯è¿™æ ïLš„:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* @author sting
*/
public class Server {
private static final String FILE = "conf" + File.separator + "server.properties";
public void initial() throws IOException {
FileInputStream in = new FileInputStream(System.getProperty("APP_HOME") + File.separator + FILE);
Properties properties = new Properties();
properties.load(in);
// initial
}
}
æ–‡äšg路径和文件å都是hard code,很难‹¹‹è¯•. 我们首先把initial()釿ž„一ä¸?代ç 如下:
public void initial(InputStream in) throws IOException {
Properties properties = new Properties();
properties.load(in);
// initial
}
臛_°‘,‹¹‹è¯•æ—?我们å¯ä»¥ä¼ è¿›æ¥è‡ªå·Þqš„InputStream,也å¯ä»¥æ–¹ä¾¿çš„æ—¶å€™æµ‹è¯•用的server.properties,或者干脆ä‹É用内è”的文äšg,代ç 如下:
class ServerTest extends TestCase {
private Server server;
public void setUp() throws Exception {
this.server = new Server();
}
public void testInitial() throws Exception {
String serverProperties = "port=8080\n" +
"run_mode=normal";
InputStream in = new ByteArrayInputStream(serverProperties.getBytes());
this.server.initial(in);
// assert
}
}
但是,在实际工作的代ç ä¸?æ–‡äšgå和路径ä¾ç„¶è¦hard code˜q›ä»£ç ä¸.˜q™æ—¶,我们å¯ä»¥ä½¿ç”¨springä¸çš„ResourceæŽ¥å£æ¥è¿›ä¸€æ¥æ”¹˜q›æˆ‘们的代ç .
public class Server {
private Resource resource;
public void setResource(Resource r) {
this.resource = r;
}
public void initial() throws IOException {
Properties properties = new Properties();
properties.load(this.resource.getInputStream());
// initial
}
}
å†åР䏀ŒDµspring的酾|®æ–‡ä»?
<beans>
<bean id="server" class="Server">
<property name="resource" value="classpath:server.properties"/>
</bean>
</beans>
˜q™æ ·,Server的代ç 完全与文äšg的具体èµ\径和文äšgåæ— å…?仅仅用酾|®æ–‡ä»¶å°±å¯ä»¥æŒ‡å®š,表达更清æ¥?也更易于‹¹‹è¯•.
当然,ä»…é™äºŽå·²¾lä‹É用spring的项ç›?