Apache Eagle代码逻辑分析--后台REST接口代码逻辑

  1. SiteResource.java相当于 Dropwizard框架里的Resource类。
  2. SiteEntity.java相当于Dropwizard框架里的Representation类,用来定义返回的结果的数据字段。
  3. 在JDBCMetadataStore.java里面绑定的SiteEntityServiceJDBCImpl和SiteEntityService相当于封装的底层数据库查询类。然后在SiteResource里被调用。
  4. SiteResource在ServerApplication的run函数中注册,不需要在指定文件中注册,由程序启动时对org.apache.eagle这个package下的所有进行注册。

(Dropwizard简单入门https://www.cnblogs.com/sunfie/p/6831517.html)

 

SiteResource

Resource有两个声明:@Path和@Produces。@Path("/sites")告诉Jersey这个resource可以通过 "/sites"URL被访问。

@Produces(MediaType.APPLICATION_JSON)让Jersey的内容协商代码知道这个资源产生的是application/json.

E:\code\eagle\eagle-master-0.5.0-SNAPSHOT\eagle-core\eagle-metadata\eagle-metadata-base\src\main\java\org\apache\eagle\metadata\resource\SiteResource.java

@Path("/sites")
@Singleton
public class SiteResource {
    private final SiteEntityService siteEntityService;
    private final ApplicationEntityService entityService;

    @Inject
    public SiteResource(SiteEntityService siteEntityService,
                        ApplicationEntityService applicationEntityService) {
        this.siteEntityService = siteEntityService;
        this.entityService = applicationEntityService;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public RESTResponse<Collection<SiteEntity>> getAllSites() {
        return RESTResponse.async(siteEntityService::findAll).get();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> createSite(SiteEntity siteEntity) {
        return RESTResponse.<SiteEntity>async((builder) -> {
            SiteEntity entity = siteEntityService.create(siteEntity);
            builder.message("Successfully created site (siteId:" + entity.getSiteId() + ", uuid: " + entity.getUuid() + ")");
            builder.data(entity);
        }).get();
    }

    @GET
    @Path("/{siteId}")
    @Produces(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> getSiteBySiteId(@PathParam("siteId") String siteId) {
        return RESTResponse.async(() -> siteEntityService.getBySiteId(siteId)).get();
    }

    @DELETE
    @Path("/{siteId}")
    @Produces(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> deleteSiteBySiteId(@PathParam("siteId") String siteId) {
        return RESTResponse.async(() -> {
            int appCount = entityService.findBySiteId(siteId).size();
            if (appCount > 0) {
                throw new SiteDeleteException("This site has enabled applications, remove them first");
            }
            return siteEntityService.deleteBySiteId(siteId);
        }).get();
    }

    @DELETE
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> deleteSiteByUUID(UUIDRequest uuidRequest) {
        return RESTResponse.async(() -> {
            int appCount = entityService.findBySiteId(siteEntityService.getByUUID(uuidRequest.getUuid()).getSiteId()).size();
            if (appCount > 0) {
                throw new SiteDeleteException("This site has enabled applications, remove them first");
            }
            return siteEntityService.deleteByUUID(uuidRequest.getUuid());
        }).get();
    }

    @PUT
    @Path("/{siteId}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> updateSite(@PathParam("siteId") String siteId, SiteEntity siteEntity) {
        return RESTResponse.async(() -> {
            siteEntity.setSiteId(siteId);
            return siteEntityService.update(siteEntity);
        }).get();
    }

    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public RESTResponse<SiteEntity> updateSite(SiteEntity siteEntity) {
        return RESTResponse.async(() -> {
            return siteEntityService.update(siteEntity);
        }).get();
    }
}
 

 

JDBCMetadataStore

public class JDBCMetadataStore extends MetadataStore {
    @Override
    protected void configure() {
        bind(IMetadataDao.class).to(JdbcMetadataDaoImpl.class).in(Singleton.class);
        bind(DataSource.class).toProvider(JDBCDataSourceProvider.class).in(Singleton.class);
        bind(JDBCDataSourceConfig.class).toProvider(JDBCMetadataStoreConfigProvider.class).in(Singleton.class);
        bind(JDBCMetadataQueryService.class).to(JDBCMetadataMetadataStoreServiceImpl.class).in(Singleton.class);
        bind(ApplicationEntityService.class).to(ApplicationEntityServiceJDBCImpl.class).in(Singleton.class);
        bind(SiteEntityService.class).to(SiteEntityServiceJDBCImpl.class).in(Singleton.class);
        bind(DashboardEntityService.class).to(DashboardEntityServiceJDBCImpl.class).in(Singleton.class);
        bind(PolicyEntityService.class).to(PolicyEntityServiceJDBCImpl.class).in(Singleton.class);
    }
}

 

SiteEntityServiceJDBCImpl:定义了所有的site的数据库操作函数

E:\code\eagle\eagle-master-0.5.0-SNAPSHOT\eagle-core\eagle-metadata\eagle-metadata-jdbc\src\main\java\org\apache\eagle\metadata\store\jdbc\service\SiteEntityServiceJDBCImpl.java

public class SiteEntityServiceJDBCImpl implements SiteEntityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SiteEntityServiceJDBCImpl.class);
    private static final String insertSql = "INSERT INTO sites (siteid, sitename, description, createdtime, modifiedtime, uuid) VALUES (?, ?, ?, ?, ?, ?)";
    private static final String selectSql = "SELECT * FROM sites";
    private static final String selectSqlByUUID = "SELECT * FROM sites where uuid = ?";
    private static final String selectSqlBySiteId = "SELECT * FROM sites where siteid = ?";
    private static final String deleteSqlByUUID = "DELETE FROM sites where uuid = ?";
    private static final String deleteSqlBySiteId = "DELETE FROM sites where siteid = ?";
    private static final String updateSqlByUUID = "UPDATE sites SET siteid = ? , sitename = ? , description = ? , createdtime = ? , modifiedtime = ?  where uuid = ?";
    @Inject
    JDBCMetadataQueryService queryService;

    @Override
    public SiteEntity getBySiteId(String siteId) throws EntityNotFoundException {
        List<SiteEntity> results;
        SiteEntity siteEntity = new SiteEntity("", siteId);
        try {
            results = queryService.queryWithCond(selectSqlBySiteId, siteEntity, new SiteEntityToRelation(), new RelationToSiteEntity());
        } catch (SQLException e) {
            LOGGER.error("Error to getBySiteId SiteEntity: {}", e);
            throw new EntityNotFoundException(e);
        }
        if (results.isEmpty()) {
            throw new EntityNotFoundException("getBySiteId " + siteId + " Not Found");
        }
        return results.get(0);
    }

    @Override
    public SiteEntity deleteBySiteId(String siteId) throws EntityNotFoundException {
        SiteEntity siteEntity = new SiteEntity("", siteId);
        int result;
        try {
            result = queryService.update(deleteSqlBySiteId, siteEntity, new SiteEntityToRelation());
        } catch (SQLException e) {
            LOGGER.error("Error to deleteBySiteId SiteEntity: {}", siteEntity, e);
            throw new EntityNotFoundException(e);
        }
        if (result == 0) {
            throw new EntityNotFoundException("deleteBySiteId " + siteEntity + "Not Found");
        }
        return siteEntity;
    }

    @Override
    public SiteEntity deleteByUUID(String uuid) throws EntityNotFoundException {
        SiteEntity siteEntity = new SiteEntity(uuid, "");
        int result;
        try {
            result = queryService.update(deleteSqlByUUID, siteEntity, new SiteEntityToRelation());
        } catch (SQLException e) {
            LOGGER.error("Error to deleteByUUID SiteEntity: {}", siteEntity, e);
            throw new EntityNotFoundException(e);
        }
        if (result == 0) {
            throw new EntityNotFoundException("deleteByUUID " + siteEntity + "Not Found");
        }
        return siteEntity;
    }

    @Override
    public SiteEntity update(SiteEntity siteEntity) throws EntityNotFoundException {

        if (siteEntity.getSiteId() == null && siteEntity.getUuid() == null) {
            throw new IllegalArgumentException("siteId and UUID are both null, don't know how to update");
        }
        int result;
        try {
            SiteEntity oldEntity = getBySiteId(siteEntity.getSiteId());
            siteEntity.setUuid(oldEntity.getUuid());
            siteEntity.setCreatedTime(oldEntity.getCreatedTime());
            siteEntity.ensureDefault();
            result = queryService.update(updateSqlByUUID, siteEntity, new SiteEntityToRelation());
        } catch (SQLException e) {
            LOGGER.error("Error to update SiteEntity: {}", siteEntity, e);
            throw new EntityNotFoundException(e);
        }
        if (result == 0) {
            throw new EntityNotFoundException("update " + siteEntity + "Not Found");
        }

        return siteEntity;
    }

    @Override
    public Collection<SiteEntity> findAll() {
        List<SiteEntity> results = new ArrayList<>();
        try {
            results = queryService.query(selectSql, new RelationToSiteEntity());
        } catch (SQLException e) {
            LOGGER.error("Error to findAll SiteEntity: {}", e);
        }
        return results;
    }

    @Override
    public SiteEntity getByUUID(String uuid) throws EntityNotFoundException {
        List<SiteEntity> results;
        SiteEntity siteEntity = new SiteEntity(uuid, "");
        try {
            results = queryService.queryWithCond(selectSqlByUUID, siteEntity, new SiteEntityToRelation(), new RelationToSiteEntity());
        } catch (SQLException e) {
            LOGGER.error("Error to getByUUID SiteEntity: {}", e);
            throw new EntityNotFoundException(e);
        }
        if (results.isEmpty()) {
            throw new EntityNotFoundException("getByUUID " + uuid + " Not Found");
        }
        return results.get(0);
    }

    @Override
    public SiteEntity create(SiteEntity entity) {
        Preconditions.checkNotNull(entity.getSiteId(), "SiteId is null: " + entity.getSiteId());
        List<SiteEntity> entities = new ArrayList<>(1);
        entity.ensureDefault();
        entities.add(entity);
        try {
            queryService.insert(insertSql, entities, new SiteEntityToRelation());
        } catch (SQLException e) {
            LOGGER.error("Error to insert SiteEntity: {}", entity, e);
            throw new IllegalArgumentException("Error to insert SiteEntity: " + entity + e);
        }
        return entity;
    }
}

 

SiteEntity.java

E:\code\eagle\eagle-master-0.5.0-SNAPSHOT\eagle-core\eagle-metadata\eagle-metadata-base\src\main\java\org\apache\eagle\metadata\model\SiteEntity.java

public class SiteEntity extends PersistenceEntity {
    private String siteId;
    private String siteName;
    private String description;
    private Map<String, String> context;

    public SiteEntity() {
    }

    public SiteEntity(String uuid, String siteId) {
        super.setUuid(uuid);
        this.siteId = siteId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return String.format("SiteEntity[siteId = %s, siteName =%s, description = %s, uuid = %s]", getSiteId(), getSiteName(), getDescription(), getUuid());
    }

    public String getSiteId() {
        return siteId;
    }

    public void setSiteId(String siteId) {
        this.siteId = siteId;
    }

    public String getSiteName() {
        return siteName;
    }

    public void setSiteName(String siteName) {
        this.siteName = siteName;
    }

    public Map<String, String> getContext() {
        return context;
    }

    public void setContext(Map<String, String> context) {
        this.context = context;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值