Commit 2c49603c by HlQ

天气服务关联git

0 parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
*.log
.idea/
.settings/
ignore-*/
.mvn/
mvnw
mvnw.cmd
\ No newline at end of file \ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vion</groupId>
<artifactId>WeatherService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>postgresql</groupId> -->
<!-- <artifactId>postgresql</artifactId> -->
<!-- <version>9.1-901-1.jdbc4</version> -->
<!-- </dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package com.viontech;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = { "com.viontech.*"})
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
package com.viontech.configuration;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
public class DruidDBConfiguration {
private Logger logger = LoggerFactory.getLogger(DruidDBConfiguration.class);
@Value("${spring.datasource.url:127.0.0.1}")
private String dbUrl;
@Value("${spring.datasource.username:postgresql}")
private String username;
@Value("${spring.datasource.password:password}")
private String password;
@Value("${spring.datasource.driverClassName:driverClassName}")
private String driverClassName;
@Value("${spring.datasource.initialSize:0}")
private int initialSize;
@Value("${spring.datasource.minIdle:0}")
private int minIdle;
@Value("${spring.datasource.maxActive:1}")
private int maxActive;
@Value("${spring.datasource.maxWait:0}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis:0}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis:0}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery:0}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle:false}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow:false}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn:false}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements:false}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize:0}")
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
@Value("${spring.datasource.connectionProperties:connectionProperties}")
private String connectionProperties;
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
@ConditionalOnExpression("#{'${spring.datasource.driverClassName:false}'!='false'}")
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
if("driverClassName".equals(driverClassName)){
return null;
}
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
\ No newline at end of file \ No newline at end of file
package com.viontech.job;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import com.viontech.model.Mall;
import com.viontech.service.impl.CityService;
import com.viontech.service.impl.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.viontech.model.City;
import com.viontech.model.SimpleWeather;
import com.viontech.service.impl.JsonService;
/**
* @author zhaibolin
*/
@Component
public class SchedulerTask implements CommandLineRunner{
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private JsonService jsonService;
@Autowired
private CityService cityService;
@Autowired
private WeatherService weatherService;
@Scheduled(cron="0 0 8 * * ?")
private void process() throws IOException{
weatherService.getWeatherInfo();
// Date now = new Date();
// LocalDate localDate=now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// Date date=java.sql.Date.valueOf(localDate);
// long s=System.currentTimeMillis();
// System.out.println(new Timestamp(s));
// System.out.println(date+"天气服务调用开始");
//// RowMapper<City> rowMapper = new BeanPropertyRowMapper<>(City.class);
//// List<City> Citys = jdbcTemplate.query("select city_id,province_id,weather_code,city_name,province_name from b_city where weather_code is not null and weather_code!='';", rowMapper);
//
//// RowMapper<SimpleWeather> rowMappers = new BeanPropertyRowMapper<>(SimpleWeather.class);
//// List<SimpleWeather> Weathers=jdbcTemplate.query("select province_id,city_id,type,data_date,ltemp,htemp,aqi,wind_intensity from d_weather where data_date='"+date+"';", rowMappers);
//// List<Integer> cityIds = Weathers.stream().map(SimpleWeather::getCity_id).collect(Collectors.toList());
//
// if(cityList.isEmpty()){
// System.out.println("请先给您所在城市添加城市编码");
// }else{
// for (City bcity : cityList) {
// if(cityIds.contains(bcity.getCityId())){
// System.out.println(""+bcity.getProvinceName()+bcity.getCityName()+"天气已经存在");
// continue;
// }
// Integer weatherCode= null;
// try {
// weatherCode = new Integer(bcity.getWeatherCode().trim());
// } catch (NumberFormatException e) {
// continue;
// }
// SimpleWeather simpleWeather= jsonService.getWeatherInfo(weatherCode.intValue());
// if(simpleWeather == null){
// System.out.println(weatherCode.intValue());
// }
//
// jdbcTemplate.update(
// "insert into d_weather(province_id,city_id,type,data_date,ltemp,htemp,aqi,modify_time,create_time,wind_intensity) values(?,?,?,?,?,?,?,NOW(),NOW(),?);",
// bcity.getProvinceId(),
// bcity.getCityId(),
// String.valueOf(simpleWeather.getType()),
// date,
// Integer.parseInt(simpleWeather.getLtemp()),
// Integer.parseInt(simpleWeather.getHtemp()),
// Integer.parseInt(simpleWeather.getAqi()),
// Integer.parseInt(simpleWeather.getFengli().substring(0,1))
// );
// System.out.println(""+bcity.getProvinceName()+bcity.getCityName()+"天气插入成功");
// }
// }
// System.out.println("天气服务调用结束");
}
//@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
process();
}
}
\ No newline at end of file \ No newline at end of file
package com.viontech.model;
public class Aqi {
private String cityName;
private String co;
private String no2;
private String o3;
private String pm10;
private String pm25;
private String pubtime;
private String rank;
private String so2;
private String value;
public String getSo2() {
return so2;
}
public void setSo2(String so2) {
this.so2 = so2;
}
public String getValue() {
if(value==null){
value="0";
}
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCo() {
return co;
}
public void setCo(String co) {
this.co = co;
}
public String getNo2() {
return no2;
}
public void setNo2(String no2) {
this.no2 = no2;
}
public String getO3() {
return o3;
}
public void setO3(String o3) {
this.o3 = o3;
}
public String getPm10() {
return pm10;
}
public void setPm10(String pm10) {
this.pm10 = pm10;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
public String getPubtime() {
return pubtime;
}
public void setPubtime(String pubtime) {
this.pubtime = pubtime;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
// private String cityName;
// private String pubtime;
// private String value;
// public void setCityName(String cityName) {
// this.cityName = cityName;
// }
// public String getCityName() {
// return cityName;
// }
//
// public void setPubtime(String pubtime) {
// this.pubtime = pubtime;
// }
// public String getPubtime() {
// return pubtime;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// public String getValue() {
// return value;
// }
}
package com.viontech.model;
public class City {
private Integer cityId;
private String counname;
private String name;
private String pname;
private String timezone;
private Integer provinceId;
private String weatherCode;
private String cityName;
private String provinceName;
public Integer getProvinceId() {
return provinceId;
}
public void setProvinceId(Integer provinceId) {
this.provinceId = provinceId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public Integer getCityId() {
return cityId;
}
public void setCounname(String counname) {
this.counname = counname;
}
public String getCounname() {
return counname;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPname() {
return pname;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getTimezone() {
return timezone;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getWeatherCode() {
return weatherCode;
}
public void setWeatherCode(String weatherCode) {
this.weatherCode = weatherCode;
}
}
package com.viontech.model;
import java.util.List;
public class Data {
private Aqi aqi;
private City city;
private List<Forecast> forecast;
public void setCity(City city) {
this.city = city;
}
public City getCity() {
return city;
}
public void setForecast(List<Forecast> forecast) {
this.forecast = forecast;
}
public List<Forecast> getForecast() {
return forecast;
}
public Aqi getAqi() {
return aqi;
}
public void setAqi(Aqi aqi) {
this.aqi = aqi;
}
}
package com.viontech.model;
import java.util.Date;
public class Forecast {
private String conditionDay;
private String conditionIdDay;
private String conditionIdNight;
private String conditionNight;
private Date predictDate;
private String tempDay;
private String tempNight;
private Date updatetime;
private String windDirDay;
private String windDirNight;
private String windLevelDay;
private String windLevelNight;
public void setConditionDay(String conditionDay) {
this.conditionDay = conditionDay;
}
public String getConditionDay() {
return conditionDay;
}
public void setConditionIdDay(String conditionIdDay) {
this.conditionIdDay = conditionIdDay;
}
public String getConditionIdDay() {
return conditionIdDay;
}
public void setConditionIdNight(String conditionIdNight) {
this.conditionIdNight = conditionIdNight;
}
public String getConditionIdNight() {
return conditionIdNight;
}
public void setConditionNight(String conditionNight) {
this.conditionNight = conditionNight;
}
public String getConditionNight() {
return conditionNight;
}
public void setPredictDate(Date predictDate) {
this.predictDate = predictDate;
}
public Date getPredictDate() {
return predictDate;
}
public void setTempDay(String tempDay) {
this.tempDay = tempDay;
}
public String getTempDay() {
return tempDay;
}
public void setTempNight(String tempNight) {
this.tempNight = tempNight;
}
public String getTempNight() {
return tempNight;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setWindDirDay(String windDirDay) {
this.windDirDay = windDirDay;
}
public String getWindDirDay() {
return windDirDay;
}
public void setWindDirNight(String windDirNight) {
this.windDirNight = windDirNight;
}
public String getWindDirNight() {
return windDirNight;
}
public void setWindLevelDay(String windLevelDay) {
this.windLevelDay = windLevelDay;
}
public String getWindLevelDay() {
return windLevelDay;
}
public void setWindLevelNight(String windLevelNight) {
this.windLevelNight = windLevelNight;
}
public String getWindLevelNight() {
return windLevelNight;
}
}
package com.viontech.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "json")
public class Json {
private String host1;
private String path1;
private String host2;
private String path2;
private String appcode;
public String getHost1() {
return host1;
}
public void setHost1(String host1) {
this.host1 = host1;
}
public String getPath1() {
return path1;
}
public void setPath1(String path1) {
this.path1 = path1;
}
public String getHost2() {
return host2;
}
public void setHost2(String host2) {
this.host2 = host2;
}
public String getPath2() {
return path2;
}
public void setPath2(String path2) {
this.path2 = path2;
}
public String getAppcode() {
return appcode;
}
public void setAppcode(String appcode) {
this.appcode = appcode;
}
}
package com.viontech.model;
public class Mall {
private String name;
private Integer status;
private Integer province_id;
private Integer city_id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getProvince_id() {
return province_id;
}
public void setProvince_id(Integer province_id) {
this.province_id = province_id;
}
public Integer getCity_id() {
return city_id;
}
public void setCity_id(Integer city_id) {
this.city_id = city_id;
}
}
package com.viontech.model;
public class Rc {
private int c;
private String p;
public void setC(int c) {
this.c = c;
}
public int getC() {
return c;
}
public void setP(String p) {
this.p = p;
}
public String getP() {
return p;
}
}
package com.viontech.model;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class SimpleWeather {
private int province_id;
private int city_id;
private int type;
private Date data_date;
private String ltemp;
private String htemp;
//private int pm25;
private String aqi;
public String getFengli() {
return fengli;
}
public void setFengli(String fengli) {
this.fengli = fengli;
}
private String fengli;
public String getFengxiang() {
return fengxiang;
}
public void setFengxiang(String fengxiang) {
this.fengxiang = fengxiang;
}
private String fengxiang;
public int getProvince_id() {
return province_id;
}
public void setProvince_id(int province_id) {
this.province_id = province_id;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Date getData_date() {
return data_date;
}
public void setData_date(Date data_date) {
this.data_date = data_date;
}
public String getLtemp() {
return ltemp;
}
public void setLtemp(String ltemp) {
this.ltemp = ltemp;
}
public String getHtemp() {
return htemp;
}
public void setHtemp(String htemp) {
this.htemp = htemp;
}
public String getAqi() {
return aqi;
}
public void setAqi(String aqi) {
this.aqi = aqi;
}
}
package com.viontech.model;
public class WeatherMessage {
private int code;
private Data data;
private String msg;
private Rc rc;
public void setCode(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setRc(Rc rc) {
this.rc = rc;
}
public Rc getRc() {
return rc;
}
}
package com.viontech.service.impl;
import com.viontech.model.City;
import com.viontech.model.Mall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author zhaibolin
*/
@Service
public class CityService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
private JsonService jsonService;
private String SQL_SELECT_MALL="select name,status,province_id,city_id from b_mall";
private String SQL_SELECT_CITY="select area_name as cityName,province_id,weather_code,city_id from b_city where city_id in (:cityIds)";
private String SQL_SELECT_WEATHER="select city_id from d_weather where data_date=?";
public List<Mall> selectMallList(){
List<Mall> mallList= jdbcTemplate.query(SQL_SELECT_MALL,new BeanPropertyRowMapper<>(Mall.class));
return mallList;
}
public List<City> selectCityList(List<Mall> mallList){
if(mallList.isEmpty()){
System.out.println("获取不到商场列表");
return null;
}
List<Integer> cityIdList = mallList.stream().filter(x -> x.getCity_id() != null).map(Mall::getCity_id).collect(Collectors.toList());
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("cityIds", cityIdList);
return namedParameterJdbcTemplate.query(SQL_SELECT_CITY, paramMap, new BeanPropertyRowMapper<>(City.class));
}
public List<Integer> selectTodayWeather(Date date){
List<Integer> cityIdList=jdbcTemplate.queryForList(SQL_SELECT_WEATHER,new Object[]{date},Integer.class);
return cityIdList;
}
}
package com.viontech.service.impl;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import com.viontech.model.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.viontech.utils.HttpUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @author zhaibolin
*/
//@Configuration
@Service
public class JsonService {
@Resource
private JdbcTemplate jdbcTemplate;
@Autowired
private Json jsonclass;
public SimpleWeather getWeatherInfo(int cityId) throws IOException {
String json = getWeatherJson(cityId);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
WeatherMessage weatherMessage = mapper.readValue(json, WeatherMessage.class);
// if(!weatherMessage.getCode().equals("0")){
// throw new RuntimeException(weatherMessage.getMsg());
// }
String jsons = getAqiJson(cityId);
ObjectMapper mappers = new ObjectMapper();
mappers.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mappers.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
WeatherMessage weatherMessage2 = mappers.readValue(jsons, WeatherMessage.class);
SimpleWeather simpleWeather = weathers2SimpleWeather(weatherMessage,weatherMessage2);
return simpleWeather;
}
private String getWeatherJson(int cityId) throws IOException{
String host = jsonclass.getHost1();
String path = jsonclass.getPath1();
String method = "POST";
String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = null;
try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return response.toString();
return EntityUtils.toString(response.getEntity());
}
private String getAqiJson(int cityId) throws IOException{
String host = jsonclass.getHost2();
String path = jsonclass.getPath2();
String method = "POST";
String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = null;
try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return response.toString();
return EntityUtils.toString(response.getEntity());
}
private SimpleWeather weathers2SimpleWeather(WeatherMessage weatherMessage,WeatherMessage weatherMessage2){
Data data = weatherMessage.getData();
if(data == null){
return null;
}
data.getCity();
data.getForecast();
City city = data.getCity();
if(city == null){
return null;
}
Forecast forecast = data.getForecast().get(0);
if(forecast == null){
return null;
}
SimpleWeather simpleWeather = new SimpleWeather();
simpleWeather.setType(getWeatherCode(forecast.getConditionDay()));
simpleWeather.setData_date(forecast.getPredictDate());
simpleWeather.setHtemp(forecast.getTempDay());
simpleWeather.setLtemp(forecast.getTempNight());
if(weatherMessage2.getData().getAqi()==null){
simpleWeather.setAqi("0");
}else{
simpleWeather.setAqi(weatherMessage2.getData().getAqi().getValue());
}
simpleWeather.setFengli(forecast.getWindLevelDay());
simpleWeather.setFengxiang(forecast.getWindDirDay());
return simpleWeather;
}
private int getWeatherCode(String weather){
switch (weather) {
case "晴":
case "大部晴朗":
return 1;
case "多云":
case "少云":
return 2;
case "阴":
return 3;
case "阵雨":
case "局部阵雨":
case "小阵雨":
case "强阵雨":
return 4;
case "雷阵雨":
case "雷电":
case "雷暴":
return 5;
case "雷阵雨伴有冰雹":
case "冰雹":
case "冰粒":
case "冰针":
return 6;
case "雨夹雪":
return 7;
case "小雨":
case "小到中雨":
return 8;
case "中雨":
case "雨":
return 9;
case "大雨":
case "中到大雨":
return 10;
case "暴雨":
case "大暴雨":
case "特大暴雨":
case "大到暴雨":
return 11;
case "阵雪":
case "小阵雪":
return 12;
case "小雪":
return 13;
case "中雪":
case "小到中雪":
case "雪":
return 14;
case "大雪":
return 15;
case "暴雪":
return 16;
case "雾":
case "冻雾":
return 17;
case "冻雨":
return 18;
case "霾":
case "沙尘暴":
case "强沙尘暴":
return 19;
case "浮尘":
case "尘卷风":
case "扬沙":
return 20;
default:
return -1;
}
}
}
package com.viontech.service.impl;
import com.viontech.model.City;
import com.viontech.model.Mall;
import com.viontech.model.SimpleWeather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
/**
* @author zhaibolin
*/
@Service
public class WeatherService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private JsonService jsonService;
@Autowired
private CityService cityService;
public void getWeatherInfo() throws IOException {
Date now = new Date();
LocalDate localDate=now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Date date=java.sql.Date.valueOf(localDate);
long s=System.currentTimeMillis();
System.out.println(new Timestamp(s));
System.out.println(date+"天气服务调用开始");
List<Mall> mallList=cityService.selectMallList();
List<City> cityList=cityService.selectCityList(mallList);
List<Integer> cityIds=cityService.selectTodayWeather(date);
if(cityList != null) {
for (City bcity : cityList) {
if(cityIds.contains(bcity.getCityId())){
System.out.println(""+bcity.getCityName()+"天气已经存在");
continue;
}
Integer weatherCode= null;
try {
if (bcity.getWeatherCode() == null) {
continue;
}
weatherCode = new Integer(bcity.getWeatherCode().trim());
} catch (NumberFormatException e) {
continue;
}
SimpleWeather simpleWeather= jsonService.getWeatherInfo(weatherCode.intValue());
if(simpleWeather == null){
System.out.println(weatherCode.intValue());
}
jdbcTemplate.update(
"insert into d_weather(province_id,city_id,type,data_date,ltemp,htemp,aqi,modify_time,create_time,wind_intensity) values(?,?,?,?,?,?,?,NOW(),NOW(),?);",
bcity.getProvinceId(),
bcity.getCityId(),
String.valueOf(simpleWeather.getType()),
date,
Integer.parseInt(simpleWeather.getLtemp()),
Integer.parseInt(simpleWeather.getHtemp()),
Integer.parseInt(simpleWeather.getAqi()),
Integer.parseInt(simpleWeather.getFengli().substring(0,1))
);
System.out.println(""+bcity.getCityName()+"天气插入成功");
}
}
System.out.println("天气服务调用结束");
}
}
package com.viontech.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
/**
* @author zhaibolin
*/
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
// ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
\ No newline at end of file \ No newline at end of file
json:
host1: http://aliv14.data.moji.com
path1: /whapi/json/alicityweather/briefforecast6days
host2: http://aliv14.data.moji.com
path2: /whapi/json/alicityweather/aqi
appcode: 98261c0416a944aa812174cc312335bf
server:
port: 9797
spring:
datasource:
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://pgm-2ze197c18ro6p1r1fo.pg.rds.aliyuncs.com:3433/ShoppingMall_retail2.0
username: vion
password: cdmqYwBq9uAdvLJb
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select version();
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!