package org.pegadi.server.article;
import org.pegadi.model.ArticleStatus;
import org.pegadi.server.ArticleStatusServer;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
@Service
public class ArticleStatusServerImpl implements ArticleStatusServer {
private NamedParameterJdbcTemplate template;
private ArticleStatusRowMapper articleStatusMapper = new ArticleStatusRowMapper();
/**
* Returns the articlestatus with the given ID
*
* @param ID the ID of the articlestatus
* @return an articlestatus, or null if no articlestatus found
*/
@Cacheable("ArticleStatus")
public ArticleStatus getArticleStatus(int ID) {
if (ID == 0) {
return null;
}
try {
return template.queryForObject("SELECT * FROM ArticleStatus WHERE ID=:id", Collections.singletonMap("id", ID), articleStatusMapper);
} catch (EmptyResultDataAccessException e) {
return null;
}
}
private class ArticleStatusRowMapper implements RowMapper<ArticleStatus> {
public ArticleStatus mapRow(ResultSet rs, int rowNum) throws SQLException {
ArticleStatus articleStatus = new ArticleStatus(rs.getInt("ID"));
articleStatus.setName(rs.getString("name"));
articleStatus.setDescription(rs.getString("description"));
java.awt.Color color;
// Try to set the color
try {
color = java.awt.Color.decode(rs.getString("color"));
}
catch (NumberFormatException e) {
color = java.awt.Color.gray;
}
articleStatus.setColor(color);
return articleStatus;
}
}
/**
* Returns all available article statuses.
*
* @return an array of <code>ArticleStatus</code>s.
*/
@Cacheable("ArticleStatus")
public List<ArticleStatus> getArticleStatuses() {
return template.query("SELECT * FROM ArticleStatus", Collections.<String, Object>emptyMap(), articleStatusMapper);
}
public void setDataSource(DataSource dataSource) {
template = new NamedParameterJdbcTemplate(dataSource);
}
}