com.baidu.rigel.biplatform.ma.ds.service.impl.DataSourceServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.baidu.rigel.biplatform.ma.ds.service.impl.DataSourceServiceImpl.java

Source

/**
 * Copyright (c) 2014 Baidu, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baidu.rigel.biplatform.ma.ds.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;

import com.baidu.rigel.biplatform.ac.util.AesUtil;
import com.baidu.rigel.biplatform.ma.ds.exception.DataSourceOperationException;
import com.baidu.rigel.biplatform.ma.ds.service.DataSourceService;
import com.baidu.rigel.biplatform.ma.file.client.service.FileService;
import com.baidu.rigel.biplatform.ma.file.client.service.FileServiceException;
import com.baidu.rigel.biplatform.ma.model.ds.DataSourceDefine;
import com.baidu.rigel.biplatform.ma.model.utils.DBInfoReader;
import com.baidu.rigel.biplatform.ma.model.utils.DBUrlGeneratorUtils;
import com.baidu.rigel.biplatform.ma.report.utils.ContextManager;

/**
 * 
 * ???
 * 
 * @author david.wang
 *
 */
@Service("dsService")
public class DataSourceServiceImpl implements DataSourceService {

    /**
     * logger 
     */
    private Logger logger = LoggerFactory.getLogger(DataSourceService.class);

    /**
     * ??
     */
    @Resource(name = "fileService")
    private FileService fileService;

    @Value("${biplatform.ma.ds.location}")
    private String dsFileBaseDir;

    /**
     * 
     * 
     * @param productLine
     */
    public DataSourceServiceImpl() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized DataSourceDefine saveOrUpdateDataSource(DataSourceDefine ds, String securityKey)
            throws DataSourceOperationException {

        checkDataSourceDefine(ds, securityKey);
        try {
            // ??????????
            DataSourceDefine oldDs = getDsDefine(ds.getId());
            String oldDsFileName = null;
            if (oldDs != null && !oldDs.getName().equals(ds.getName())) { // ????
                oldDsFileName = getDsFileName(oldDs);
                if (this.isNameExist(ds.getName())) {
                    throw new DataSourceOperationException("name already exist : " + ds.getName());
                }
            }
            String fileName = getDsFileName(ds);
            boolean rmOperResult = false;
            if (oldDsFileName != null) { // ????????
                rmOperResult = fileService.rm(oldDsFileName);
            }
            if (oldDsFileName == null || rmOperResult) { // ??
                fileService.write(fileName, SerializationUtils.serialize(ds));
            }
        } catch (Exception e) {
            // ? ?
            logger.error(e.getMessage(), e);
            throw new DataSourceOperationException("Error Happend for save or update datasource :" + e);
        }
        return ds;
    }

    /**
     * ??? ??
     * 
     * @param ds
     * @throws DataSourceOperationException
     */
    private void checkDataSourceDefine(DataSourceDefine ds, String securityKey)
            throws DataSourceOperationException {
        if (ds == null) {
            logger.error("datasource can not be null");
            throw new DataSourceOperationException("datasource can not be null");
        }
        if (StringUtils.isBlank(ds.getProductLine())) {
            logger.error("product line can not be null");
            throw new DataSourceOperationException("product line can not be null");
        }
        // ??id?????????id????
        if (isNameExist(ds.getName()) && !isNameExist(ds.getId())) {
            logger.debug("ds name alread exist");
            throw new DataSourceOperationException("ds name alread exist");
        }
        /*
         * modified by jiangyichao ?? 2014-08-12
         */
        if (!isValidateConn(ds, securityKey)) {
            logger.debug("db connection info not correct");
            throw new DataSourceOperationException("db connection info not correct");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isNameExist(String name) throws DataSourceOperationException {

        String dir = getDsFileStoreDir(ContextManager.getProductLine());
        try {
            String[] fileList = fileService.ls(dir);
            if (fileList == null || fileList.length == 0) {
                return false;
            }
            for (String fileName : fileList) {
                if (fileName.contains(name)) {
                    return true;
                }
            }
            return false;
        } catch (FileServiceException e) {
            logger.debug(e.getMessage(), e);
            throw new DataSourceOperationException(e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isValidateConn(DataSourceDefine ds, String securityKey) {
        DBInfoReader dBInfoReader = null; // new DBInfoReader();
        try {
            // ??true
            dBInfoReader = DBInfoReader.build(ds.getType(), ds.getDbUser(), ds.getDbPwd(),
                    DBUrlGeneratorUtils.getConnUrl(ds), securityKey);
            return true;

        } catch (Exception e) {
            try {
                String pwd = AesUtil.getInstance().encryptAndUrlEncoding(ds.getDbPwd(), securityKey);
                dBInfoReader = DBInfoReader.build(ds.getType(), ds.getDbUser(), pwd,
                        DBUrlGeneratorUtils.getConnUrl(ds), securityKey);
                // dirty solution ?? 
                ds.setDbPwd(pwd);
                return true;
            } catch (Exception e1) {
                logger.error(e1.getMessage());
                throw new RuntimeException(e1);
            }
        } finally {
            // ?
            if (dBInfoReader != null) {
                dBInfoReader.closeConn();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DataSourceDefine[] listAll() throws DataSourceOperationException {
        String[] listFile = null;
        try {
            listFile = fileService.ls(getDsFileStoreDir(ContextManager.getProductLine()));
        } catch (FileServiceException e) {
            logger.error(e.getMessage(), e);
            throw new DataSourceOperationException(e);
        }
        if (listFile == null || listFile.length == 0) {
            return new DataSourceDefine[0];
        }
        final List<DataSourceDefine> rs = buildResult(listFile);
        if (rs.size() != listFile.length) {
            return new DataSourceDefine[0];
        }
        return rs.toArray(new DataSourceDefine[0]);
    }

    /**
     * 
     * ???
     * 
     * @param productLine
     * @param listFile
     * @return
     */
    private List<DataSourceDefine> buildResult(final String[] listFile) {
        final List<DataSourceDefine> rs = new ArrayList<DataSourceDefine>();
        for (final String f : listFile) {
            try {
                DataSourceDefine ds = buildResult(f);
                rs.add(ds);
            } catch (FileServiceException e) {
                logger.debug(e.getMessage(), e);
            }
        }
        logger.info("read file successfully");
        return rs;
    }

    /**
     * 
     * ???
     * 
     * @param productLine
     * @param listFile
     * @return
     * @throws FileManageOperationException
     * @throws UnsupportedEncodingException
     */
    private DataSourceDefine buildResult(String file) throws FileServiceException {

        byte[] content = (byte[]) fileService.read(genDsFilePath(file));
        return (DataSourceDefine) SerializationUtils.deserialize(content);
    }

    /**
     * @param file
     * @return
     */
    private String genDsFilePath(String file) {
        return getDsFileStoreDir(ContextManager.getProductLine()) + File.separator + file;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DataSourceDefine getDsDefine(String id) throws DataSourceOperationException {
        String fileName = getDatasourceDefineNameByIdOrName(ContextManager.getProductLine(), id);
        if (fileName == null) {
            return null;
        }
        try {
            return buildResult(fileName);
        } catch (FileServiceException e) {
            logger.error("error : " + e.getMessage());
            throw new DataSourceOperationException("???", e);
        }
    }

    /**
     * ????idname???
     * 
     * @param idOrName
     * @return
     */
    private String getDatasourceDefineNameByIdOrName(String productLine, String idOrName) {
        String dir = getDsFileStoreDir(productLine);
        String[] ds = null;
        try {
            ds = fileService.ls(dir);
        } catch (FileServiceException e1) {
            logger.debug(e1.getMessage(), e1);
        }
        if (ds == null || ds.length == 0) {
            String msg = "can not get ds define by id : " + idOrName;
            logger.error(msg);
            return null;
        }
        Set<String> tmp = new HashSet<String>();
        Collections.addAll(tmp, ds);
        Set<String> dict = new HashSet<String>();
        tmp.stream().forEach((String s) -> {
            dict.add(s.substring(0, s.indexOf("_")));
            dict.add(s.substring(s.indexOf("_") + 1));
        });
        if (!dict.contains(idOrName)) {
            return null;
        }

        String fileName = null;
        for (String dsFileName : ds) {
            if (dsFileName.contains(idOrName)) {
                fileName = dsFileName;
                break;
            }
        }
        return fileName;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean removeDataSource(String id) throws DataSourceOperationException {
        DataSourceDefine ds = getDsDefine(id);
        if (ds == null) {
            String msg = "cant't get ds define info by id : " + id;
            logger.error(msg);
            throw new DataSourceOperationException(
                    "???id?? id ? " + id);
        }
        try {
            return fileService
                    .rm(genDsFilePath(getDatasourceDefineNameByIdOrName(ContextManager.getProductLine(), id)));
        } catch (FileServiceException e) {
            logger.error(e.getMessage(), e);
            throw new DataSourceOperationException(e);
        }
    }

    /**
     * ??????
     * 
     * @param ds
     * @return ?????
     */
    private String getDsFileName(DataSourceDefine ds) {
        return getDsFileStoreDir(ContextManager.getProductLine()) + File.separator + ds.getId() + "_"
                + ds.getName();
    }

    /**
     * ???
     * @param productLine
     * @return String
     */
    private String getDsFileStoreDir(String productLine) {
        //        String productLine = ContextManager.getProductLine();
        String basePath = productLine + File.separator + dsFileBaseDir;
        return basePath;
    }

    public FileService getFileService() {
        return fileService;
    }

    /**
     * 
     * @param fileService
     * 
     */
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DataSourceDefine getDsDefine(String productLine, String dsName) throws DataSourceOperationException {
        String fileName = getDatasourceDefineNameByIdOrName(productLine, dsName);
        if (fileName == null) {
            return null;
        }
        try {
            return buildResult(fileName);
        } catch (FileServiceException e) {
            logger.error("error : " + e.getMessage());
            throw new DataSourceOperationException("???", e);
        }

    }

}