RESTful 工具:ContactConverter.java

package com.emprogria.rs.converter; import com.emprogria.jpa.Contact; import java.net.URI; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlAttribute; import javax.ws.rs.core.UriBuilder; import javax.persistence.EntityManager; @XmlRootElement(name = "contact") public class ContactConverter { private Contact entity; private URI uri; private int expandLevel; /** Creates a new instance of ContactConverter */ public ContactConverter() { entity = new Contact(); } /** * Creates a new instance of ContactConverter. * * @param entity associated entity * @param uri associated uri * @param expandLevel indicates the number of levels the entity graph should be expanded@param isUriExtendable indicates whether the uri can be extended */ public ContactConverter(Contact entity, URI uri, int expandLevel, boolean isUriExtendable) { this.entity = entity; this.uri = (isUriExtendable) ? UriBuilder.fromUri(uri).path(entity.getMsn() + "/").build() : uri; this.expandLevel = expandLevel; } /** * Creates a new instance of ContactConverter. * * @param entity associated entity * @param uri associated uri * @param expandLevel indicates the number of levels the entity graph should be expanded */ public ContactConverter(Contact entity, URI uri, int expandLevel) { this(entity, uri, expandLevel, false); } /** * Getter for msn. * * @return value for msn */ @XmlElement public String getMsn() { return (expandLevel > 0) ? entity.getMsn() : null; } /** * Setter for msn. * * @param value the value to set */ public void setMsn(String value) { entity.setMsn(value); } /** * Getter for realName. * * @return value for realName */ @XmlElement public String getRealName() { return (expandLevel > 0) ? entity.getRealName() : null; } /** * Setter for realName. * * @param value the value to set */ public void setRealName(String value) { entity.setRealName(value); } /** * Getter for tel. * * @return value for tel */ @XmlElement public String getTel() { return (expandLevel > 0) ? entity.getTel() : null; } /** * Setter for tel. * * @param value the value to set */ public void setTel(String value) { entity.setTel(value); } /** * Returns the URI associated with this converter. * * @return the uri */ @XmlAttribute public URI getUri() { return uri; } /** * Sets the URI for this reference converter. * */ public void setUri(URI uri) { this.uri = uri; } /** * Returns the Contact entity. * * @return an entity */ @XmlTransient public Contact getEntity() { if (entity.getMsn() == null) { ContactConverter converter = UriResolver.getInstance().resolve(ContactConverter.class, uri); if (converter != null) { entity = converter.getEntity(); } } return entity; } /** * Returns the resolved Contact entity. * * @return an resolved entity */ public Contact resolveEntity(EntityManager em) { return entity; } }