当前位置:首页 >> 农林牧渔 >>

Cecily's Tatiana Zoe


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforg

e.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="beans.DateLookup" table="notable"> <composite-id> <key-property name="id" /> </composite-id> <property name="date" /> </class> <sql-query name="select_updated_date" callable="true"> <return alias="updatedDate" class="beans.DateLookup"> <return-property name="id" column="code" /> <return-property name="date" column="latest_date" /> </return> select code,max(trade_date) as latest_date from trades where code=? group by code </sql-query> </hibernate-mapping> ==============================================================================p ackage beans; import java.io.Serializable; import java.util.Date; import dao.DateLookupDao; public class DateLookup implements Serializable { private static final long serialVersionUID = 1L; private String id; private Date date; private DateLookupDao latestDateDao; public DateLookup() {} public void setLatestDateDao(DateLookupDao latestDateDao) { this.latestDateDao=latestDateDao; } public DateLookup(String id, Date date) { this.id=id;

this.date=date; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public DateLookup getLastUpdateDate(String id) { return latestDateDao.getLastUpdateDate(id); } } ==============================================================================< ?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="beans.Share" table="trades"> <composite-id> <key-property name="id" column="code" type="string" /> <key-property name="date" column="trade_date" type="date" /> </composite-id> <property name="openPrice" type="double"> <column name="open_price" sql-type="money" /> </property> <property name="closePrice" type="double"> <column name="close_price" sql-type="money" /> </property> <property name="highestPrice" type="double"> <column name="highest" sql-type="money" /> </property>

<property name="lowestPrice" type="double"> <column name="lowest" sql-type="money" /> </property> <property name="amount" column="amount" type="double" /> <property name="total" type="double"> <column name="total_money" sql-type="money" /> </property> <property name="price940" type="double"> <column name="time940" sql-type="money" /> </property> <property name="price950" type="double"> <column name="time950" sql-type="money" /> </property> <property name="price100" type="double"> <column name="time100" sql-type="money" /> </property> <property name="url" type="string" column="day_line"/> <property name="urlBar" type="string" column="day_k"/> </class> </hibernate-mapping> ==============================================================================p ackage beans; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import exceptions.GetShareException; import exceptions.GetShareFileException;

import exceptions.GetShareTimeException; public class Share implements Serializable { private static final long serialVersionUID = 1L; private String id; private double openPrice; private double closePrice; private double highestPrice; private double lowestPrice; private double amount; private double total; private Date date; private double price940; private double price950; private double price100; private String url; private String urlBar; public double getPrice940() { return price940; } public void setPrice940(double price940) { this.price940 = price940; } public double getPrice950() { return price950; } public void setPrice950(double price950) { this.price950 = price950; } public double getPrice100() { return price100; } public void setPrice100(double price100) { this.price100 = price100; }

public String getUrl() { return url; } public void setUrl(String url) { this.url = url; }

public String getUrlBar() { return urlBar; } public void setUrlBar(String urlBar) { this.urlBar = urlBar; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Share() {} public Share(String id, double open, double close, double highest, double lowest, double amount ,double total, Date date) { this.id=id; this.openPrice=open; this.closePrice=close; this.highestPrice=highest; this.lowestPrice=lowest; this.amount=amount; this.total=total; this.date=date; } public void setId(String id) { this.id = id; } public void setOpenPrice(double openPrice) {

this.openPrice = openPrice; } public void setClosePrice(double closePrice) { this.closePrice = closePrice; } public void setHighestPrice(double highestPrice) { this.highestPrice = highestPrice; } public void setLowestPrice(double lowestPrice) { this.lowestPrice = lowestPrice; } public void setAmount(double amount) { this.amount = amount; } public void setTotal(double total) { this.total = total; } public String getId() { return id; } public double getOpenPrice() { return openPrice; } public double getClosePrice() { return closePrice; } public double getHighestPrice() { return highestPrice; } public double getLowestPrice() { return lowestPrice; } public double getAmount() { return amount; } public double getTotal() { return total; }

private static final String URLBASE = "http://hq.sinajs.cn/list=sh"; private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); public static Share formatShareFromStdURL(String id) throws GetShareException { try { URL url = new URL(URLBASE + id); BufferedReader reader = new BufferedReader(new InputStreamReader( url.openStream())); String result = reader.readLine(); String[] tokens = result.substring(result.indexOf("\"") + 1).split( ","); Share share; if(id.equals("000001")) { share = new Share(id, Double.parseDouble(tokens[1]), Double .parseDouble(tokens[3]), Double.parseDouble(tokens[4]), Double.parseDouble(tokens[5]), Long.parseLong(tokens[8]) / 10000, Double.parseDouble(tokens[9]) / 10000, DATEFORMAT.parse(tokens[30]+" "+tokens[31])); } else { share = new Share(id, Double.parseDouble(tokens[1]), Double .parseDouble(tokens[3]), Double.parseDouble(tokens[4]), Double.parseDouble(tokens[5]), Long.parseLong(tokens[8]) / 1000000, Double.parseDouble(tokens[9]) / 10000, DATEFORMAT.parse(tokens[30]+" "+tokens[31])); } return share; } catch (MalformedURLException e) { throw new GetShareFileException("Cannot get share info from " + URLBASE + id, e); } catch (IOException e) { throw new GetShareFileException("Cannot get share info from " + URLBASE + id, e); }

catch (RuntimeException e) { throw new GetShareFileException("Content from " + URLBASE + id + " is invalid.", e); } catch (ParseException e) { throw new GetShareTimeException( "Parse time error when comparing last update time", e); } } } ==============================================================================< ?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>sun.jdbc.odbc.JdbcOdbcDriver</value> </property> <property name="url"> <value>jdbc:odbc:stock</value> </property> </bean> <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"><ref bean="dataSource"/></property> </bean> <bean id="latestDateDao" class="dao.DateLookupDaoImpl"> <property name="template"> <ref bean="template" /> </property> </bean> <bean id="latestDate" class="beans.DateLookup"> <property name="latestDateDao"><ref bean="latestDateDao"/></property> </bean> </beans> ==============================================================================p ackage dao; import beans.DateLookup;

public interface DateLookupDao { public DateLookup getLastUpdateDate(String id); } ==============================================================================p ackage dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import beans.DateLookup; public class DateLookupDaoImpl implements DateLookupDao { private JdbcTemplate template; @Override public DateLookup getLastUpdateDate(String id) { String sql="select code,max(trade_date) as latest_date from trades where code=? group by code"; /* User user = (User) jdbcTemplate.queryForObject( "select * from user where id=?", new Object[] {id}, new RowMapperResultSetExtractor(rowMapper, 1));*/ //template.query(sql, new RowMapperResultSetExtractor(new DateLookupRowMapper())); DateLookup lookup=(DateLookup)template.queryForObject(sql, new Object[] {id},new DateLookupRowMapper()); return lookup; } public void setTemplate(JdbcTemplate template) { this.template = template; } class DateLookupRowMapper implements RowMapper { {

public Object mapRow(ResultSet rs, int index) throws SQLException DateLookup u = new DateLookup(); u.setId(rs.getString("code"));

u.setDate(rs.getDate("latest_date")); return u; } } } ==============================================================================p ackage exceptions;

@SuppressWarnings("serial") public abstract class GetShareException extends Exception { public GetShareException(String msg, Throwable cause) { super(msg,cause); }

public GetShareException(String msg) { super(msg); } } ==============================================================================p ackage exceptions;

@SuppressWarnings("serial") public class GetShareFileException extends GetShareException { public GetShareFileException(String msg) { super(msg); } public GetShareFileException(String msg, Throwable cause) {

super(msg, cause); } } ==============================================================================p ackage exceptions; @SuppressWarnings("serial") public class GetShareImageException extends GetShareException { public GetShareImageException(String msg) { super(msg); } public GetShareImageException(String msg, Throwable cause) { super(msg,cause); } } ==============================================================================p ackage exceptions;

@SuppressWarnings("serial") public class GetShareTimeException extends GetShareException { public GetShareTimeException(String msg) { super(msg); } public GetShareTimeException(String msg, Throwable cause) { super(msg, cause); } } ==============================================================================p ackage getters; import java.util.Date; import java.util.List; import org.hibernate.Session;

import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import beans.DateLookup; import beans.Share; public class DBPersistence { private static DBPersistence instance; private Session session; private BeanFactory factory; private DBPersistence() { //hibernate init Configuration config=new Configuration().configure(); SessionFactory hibernate_factory=config.buildSessionFactory(); session=hibernate_factory.openSession(); //spring jdbc template init Resource resource=new ClassPathResource("beans.xml"); factory = new XmlBeanFactory(resource); } public Date getLastUpdateDate(String id) { DateLookup lookup=(DateLookup)factory.getBean("latestDate"); return lookup.getLastUpdateDate(id).getDate(); } public void updateShare(List<Share> list) { Transaction tx=session.beginTransaction(); for(Share s:list) { session.save(s); } session.flush(); session.clear(); tx.commit(); } public static DBPersistence instance() { if(instance==null) {

instance=new DBPersistence(); } return instance; } } ==============================================================================p ackage getters; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.imageio.ImageIO; import beans.Share; import exceptions.GetShareException; import exceptions.GetShareImageException; public class ImagePersistenter { private static final int PIXEL = -16745272; private static final int LOWER = 16;// if height <= 16, it's not in the // price range private static final int START = 51; private static final int END = 491; private static final double RANGE = (double) (END - START + 1) / 210; private static String URLBASE = "http://image.sinajs.cn/newchart/min/n/sh"; private static String KURLBASE = "http://image.sinajs.cn/newchart/daily/n/sh"; private static String dir = "C:/Users/Lin Jiang/Documents/stock_trend/sh"; private static DateFormat FORMAT = new SimpleDateFormat("yyyyMMdd"); public static void updateShareImage(Share share) throws GetShareException { BufferedInputStream input = null; FileOutputStream output = null; BufferedInputStream input_k = null; FileOutputStream output_k = null; try {

String fileBase = dir + share.getId() + "_" + FORMAT.format(share.getDate()); // 日间走势图 URL url = new URL(URLBASE + share.getId() + ".gif"); input = new BufferedInputStream(url.openStream()); output = new FileOutputStream(fileBase + ".gif"); byte[] buf = new byte[1024]; int size = 0; while ((size = input.read(buf)) != -1) { output.write(buf, 0, size); } output.flush(); share.setUrl(fileBase + ".gif"); updateFirst30Data(share, ImageIO.read(url)); // K 线图 url = new URL(KURLBASE + share.getId() + ".gif"); input_k = new BufferedInputStream(url.openStream()); output_k = new FileOutputStream(fileBase + "_k.gif"); while ((size = input_k.read(buf)) != -1) { output_k.write(buf, 0, size); } output_k.flush(); share.setUrlBar(fileBase + "_k.gif"); } catch (MalformedURLException e) { throw new GetShareImageException("URL to image is invalid", e); } catch (IOException e) { throw new GetShareImageException("IOException to read/write image", e); } finally { try { output.close(); input.close(); input_k.close(); output_k.close(); } catch (Exception ex) { } } } private static void updateFirst30Data(Share share, BufferedImage img) { double[] line = new double[img.getWidth() + 1];

int max = START; int min = START; for (int i = START; i <= END; i++) { int total = 0; int num = 0; for (int j = LOWER + 1; j < img.getHeight(); j++) { if (img.getRGB(i, j) == PIXEL) { total += j; num++; } } if (num == 0) { line[i] = 0; assert (i > START); line[i] = line[i - 1]; // remedy blanks } else { line[i] = ((double) total) / num; if (line[i] > line[max]) { max = i; } else if (line[i] < line[min]) { min = i; } } } double highest = share.getHighestPrice(); double lowest = share.getLowestPrice(); share.setPrice940((line[max] - line[(int) (RANGE * 10) + START]) * (highest - lowest) / (line[max] - line[min]) + lowest); share.setPrice950((line[max] - line[(int) (RANGE * 20) + START]) * (highest - lowest) / (line[max] - line[min]) + lowest); share.setPrice100((line[max] - line[(int) (RANGE * 30) + START]) * (highest - lowest) / (line[max] - line[min]) + lowest); } } ==============================================================================p ackage getters; import exceptions.GetShareException; import exceptions.GetShareFileException; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException;

import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import utils.TimeUtil; import beans.Share; public class ShareGetter { private String shareConfig = "shares"; private DBPersistence persister=DBPersistence.instance(); private static final Logger log=LoggerFactory.getLogger(ShareGetter.class); private static ShareGetter getter; public static ShareGetter instance() { if (getter == null) { getter = new ShareGetter(); } return getter; } public ShareGetter instance(String shareConfig) { if (getter == null) { getter = new ShareGetter(); } getter.shareConfig = shareConfig; return getter; } private ShareGetter() {} public void persist() throws GetShareException { String[] ids = loadShareIdFromFile(); List<Share> list = new ArrayList<Share>(ids.length); for (String id : ids) { Share share=getShare(id); if(share!=null) {

list.add(getShare(id)); } } if(list.size()>0) { log.info("Persisting shares to database, {} shares are updated.",list.size()); DBPersistence.instance().updateShare(list); } else { log.info("No data need update"); } log.info("Persist suceeded!"); } private String[] loadShareIdFromFile() throws GetShareFileException { BufferedReader reader; try { reader = new BufferedReader(new FileReader(shareConfig)); List<String> ids = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { ids.add(line.trim()); } String[] arr = new String[ids.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = ids.get(i); } return arr; } catch (FileNotFoundException e) { log.error("Share config file {} is not found, {}",new Object[]{shareConfig,e}); throw new GetShareFileException("Share config file " + shareConfig + " is not found", e); } catch (IOException e) { log.error("IOException in reading {}, {}",new Object[]{shareConfig,e}); throw new GetShareFileException("IOException in reading " + shareConfig, e); } } private Share getShare(String id) throws GetShareException { Share share = Share.formatShareFromStdURL(id); //check time while(TimeUtil.whenMarketOver(share.getDate()) > 0) {

try { Thread.sleep(TimeUtil.whenMarketOver(share.getDate())); } catch (InterruptedException e) { log.info("Thread is interripted, {}",e); } } //check date Date date=persister.getLastUpdateDate(id); if(TimeUtil.isNewData(share.getDate(), date)) { ImagePersistenter.updateShareImage(share); return share; } else { return null; } } public static void main(String args[]) throws Exception { instance().persist(); } } ==============================================================================< ?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">sun.jdbc.odbc.JdbcOdbcDriver</property> <property name="hibernate.connection.url">jdbc:odbc:stock</property> <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>

<property name="show_sql">false</property> <mapping resource="beans/Share.hbm.xml"/> <mapping resource="beans/DateLookup.hbm.xml"/> </session-factory> </hibernate-configuration> ==============================================================================p ackage test; import getters.DBPersistence; import java.util.Date; import junit.framework.Assert; import org.junit.Test; public class DaoTest { @Test public void testGetLatestTrade() { DBPersistence persister=DBPersistence.instance(); Date date=persister.getLastUpdateDate("000001"); Assert.assertNotNull(date); } } ==============================================================================p ackage test; import java.util.Date; import junit.framework.Assert; import org.junit.Test; import utils.TimeUtil; public class TimeUtilTest { @SuppressWarnings("deprecation") @Test public void testMarketTime() { try {

Date date=new Date(110,9,20,15,00); //2010-10-20 15:00 Assert.assertEquals("Testing first",0,TimeUtil.whenMarketOver(date)); date=new Date(110,9,20,14,59); Assert.assertEquals("Testing second",60000,TimeUtil.whenMarketOver(date)); date=new Date(110,9,20,15,20); Assert.assertEquals("Testing third",-1200000,TimeUtil.whenMarketOver(date)); } catch(Exception ex) { Assert.fail(ex.getMessage()); } } @SuppressWarnings("deprecation") @Test public void testIsNewData() { try { Date date=new Date(110,10,21);//2010-11-21 Date date2=new Date(110,10,21); Date date3=new Date(110,9,31); Assert.assertEquals("Testing first",false, TimeUtil.isNewData(date, date2)); Assert.assertEquals("Tesing second",true,TimeUtil.isNewData(date, date3)); Assert.assertEquals("Testing third", false,TimeUtil.isNewData(date3, date)); } catch(Exception ex) { Assert.fail(ex.getMessage()); } }

} ==============================================================================p ackage utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import exceptions.GetShareTimeException; public class TimeUtil { private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");

private static final DateFormat TIMEFORMAT= new SimpleDateFormat("kk:mm:ss");

public static boolean isNewData(final Date newDate,final Date latest) throws GetShareTimeException { try { Date t=DATEFORMAT.parse(DATEFORMAT.format(latest)); Date t2=DATEFORMAT.parse(DATEFORMAT.format(newDate)); if(t.before(t2)) { return true; } else { return false; } } catch(ParseException ex) { throw new GetShareTimeException("Parse time error when deciding whether it is new trade day",ex); } } public static long whenMarketOver(final Date d) throws GetShareTimeException { try { final Date finish=TIMEFORMAT.parse("15:00:00"); Date t=TIMEFORMAT.parse(TIMEFORMAT.format(d)); long milliseconds = finish.getTime()-t.getTime(); return milliseconds; } catch(ParseException ex) { throw new GetShareTimeException("Parse time error when deciding market end time",ex); } } } ==============================================================================


相关文章:
美国常用人名姓氏
39 Elijah 40 Jason 41 Luis 42 Aaron 43 Caleb ...Zoe Alexa Christina Ariana Caitlin Michelle Brooke ...[Catherine 的昵称] 塞西莉亚 Cecily[’sisili]((f...
更多相关标签:
cecily s | zoe s red | zoe s fancy cakes | cecily strong | cecily | cecily brown | cecily作英文名好吗 | cecily strong男友 |