华为云Demo 示例

DEW 加解密服务

import com.huawei.cloud.utils.TokenUtils;
import com.huawei.cloud.vo.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author liuwenxue
 * @date 2020-08-01
 */
public class KMSTest {

    static String region = "cn-east-3";
    static String endPoint = "kms." + region + ".myhuaweicloud.com";

    public String encrypt(String projectId, KmsEncryptRequest body) {
        String url = new StringBuilder("https://").append(endPoint).append("/v1.0/").append(projectId).append("/kms/encrypt-datakey")
                .toString();

        String token = TokenUtils.getToken(region);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Auth-Token", token);
        httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
        HttpEntity<KmsEncryptRequest> entity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<KmsEncryptResponse> response = restTemplate.postForEntity(url, entity, KmsEncryptResponse.class);
        return response.getBody().getCipher_text();
    }

    public String decrypt(String projectId, KmsDecryptRequest body) {
        String url = new StringBuilder("https://").append(endPoint).append("/v1.0/").append(projectId).append("/kms/decrypt-datakey")
                .toString();
        RestTemplate restTemplate = new RestTemplate();
        String token = TokenUtils.getIamToken();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Auth-Token", token);
        httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
        HttpEntity<KmsDecryptRequest> entity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<KmsDecryptResponse> response = restTemplate.postForEntity(url, entity, KmsDecryptResponse.class);
        return response.getBody().getDatakey_dgst();
    }


    public void test() {
        String projectId = "";
        String keyId = "5270433a-426b-4822-9da1-0a137ac00cf5";

        String originKey = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000F5A5FD42D16A20302798EF6ED309979B43003D2320D9F0E8EA9831A92759FB4B";
        KmsEncryptRequest request = new KmsEncryptRequest();
        request.setKey_id(keyId);
        request.setPlain_text(originKey);
        request.setDatakey_plain_length(String.valueOf(64));
        String encryptKey = encrypt(projectId, request);
        System.out.println(encryptKey);

        KmsDecryptRequest request1 = new KmsDecryptRequest();
        request1.setCipher_text(encryptKey);
        request1.setDatakey_cipher_length(String.valueOf(64));
        request1.setKey_id(keyId);
        String decryptKey = decrypt(projectId, request1);
        System.out.println("originKey == decryptKey" + decryptKey.equals(originKey));
    }

    public static void main(String[] args) {
        new KMSTest().test();
    }

OBS 服务

import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 *
 *
 * 1. 平台使用一个桶
 * 2. 不同工具分配不同的桶
 * @author liuwenxue
 * @date 2020-08-01
*/
public class OBSTest {

    String endPoint = "https://obs.cn-east-3.myhuaweicloud.com";
    String ak = "";
    String sk = "";

    ObsConfiguration config = new ObsConfiguration();
    {
        config.setEndPoint(endPoint);
        config.setSocketTimeout(30000);
        config.setMaxErrorRetry(1);
    }


    public PutObjectResult upload(String bucketName, String userId, String fileName, String srcPath) {
        // 创建ObsClient实例
        try (ObsClient obsClient = new ObsClient(ak, sk, config)) {
            String prefix = userId + "/";
            String path = prefix + fileName;
            obsClient.putObject(bucketName, prefix, new ByteArrayInputStream(new byte[0]));
            PutObjectResult result = obsClient.putObject(bucketName, path, new File(srcPath));
            return result;
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new IllegalStateException(ex);
        }
    }

    public void download(String bucketName, String userId, String fileName, String destPath) {
        // 创建ObsClient实例
        try (ObsClient obsClient = new ObsClient(ak, sk, config)) {
            String prefix = userId + "/";
            String path = prefix + fileName;
            ObsObject obj = obsClient.getObject(bucketName, path);
            FileUtils.copyInputStreamToFile(obj.getObjectContent(), new File(destPath));
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new IllegalStateException(ex);
        }
    }

    public void delete(String bucketName, String userId, String fileName) {
        // 创建ObsClient实例
        try (ObsClient obsClient = new ObsClient(ak, sk, config)) {
            String prefix = userId + "/";
            String path = prefix + fileName;
            obsClient.deleteObject(bucketName, path);
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new IllegalStateException(ex);
        }
    }

    public void test() {
        upload("testhw123", "liuwenxue", "test1", "/tmp/test1");
        download("testhw123", "liuwenxue", "test1", "/tmp/test2");
        delete("testhw123", "liuwenxue", "test1");
        upload("testhw123", "liuwenxue", "test1", "/tmp/test3");
    }
}

Redis 服务

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


/**
 * @author liuwenxue
 * @date 2020-08-01
 */
public class RedisTest {
    static final int PRODUCT_KINDS = 30;

    String host = "192.168.0.166";
    int port = 6379;
    String passwd = "Image0@HW123";

    public void redisTest() {
        //实例连接地址,从控制台获取
        //Redis端口
        Jedis jedisClient = new Jedis(host, port);
        try {
            //实例密码
            String authMsg = jedisClient.auth(passwd);
            if (!authMsg.equals("OK")) {
                System.out.println("AUTH FAILED: " + authMsg);
                return;
            }

            //键
            String key = "商品热销排行榜";
            jedisClient.del(key);
            //随机生成产品数据
            List<String> productList = new ArrayList<>();
            for (int i = 0; i < PRODUCT_KINDS; i++) {
                productList.add("product-" + UUID.randomUUID().toString());
            }

            //随机生成销量
            for (int i = 0; i < productList.size(); i++) {
                int sales = (int) (Math.random() * 20000);
                String product = productList.get(i);
                //插入Redis的SortedSet中
                jedisClient.zadd(key, sales, product);
            }

            System.out.println();
            System.out.println("                   " + key);
            //获取所有列表并按销量顺序输出
            Set<Tuple> sortedProductList = jedisClient.zrevrangeWithScores(key, 0, -1);
            for (Tuple product : sortedProductList) {
                System.out.println("产品ID: " + product.getElement() + ", 销量: "
                        + Double.valueOf(product.getScore()).intValue());
            }

            System.out.println();
            System.out.println("                   " + key);
            System.out.println("                   前五大热销产品");

            //获取销量前五列表并输出
            Set<Tuple> sortedTopList = jedisClient.zrevrangeWithScores(key, 0, 4);
            for (Tuple product : sortedTopList) {
                System.out.println("产品ID: " + product.getElement() + ", 销量: "
                        + Double.valueOf(product.getScore()).intValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedisClient.quit();
            jedisClient.close();
        }
    }
}

SMN 服务

import com.huawei.cloud.utils.TokenUtils;
import com.huawei.cloud.vo.MailBody;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuwenxue
 * @date 2020-08-01
 */
public class SMNTest {

    static String region = "cn-east-3";
    static String endPoint = "smn." +  region + ".myhuaweicloud.com";
    static String projectId = "09617658b28026b12fc9c009cc3f223c";

    public void sendMail(String projectId, String topicUrn, MailBody body) {
        String url = new StringBuilder("https://").append(endPoint).append("/v2/").append(projectId).append("/notifications/topics/")
                .append(topicUrn).append("/publish").toString();

        String token = TokenUtils.getToken(region);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Auth-Token", token);
        httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
        HttpEntity<MailBody> entity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<MailBody> resp = restTemplate.postForEntity(url, entity, MailBody.class);
    }

    public void test() {
        String topicUrn = "urn:smn:cn-east-3:09617658b28026b12fc9c009cc3f223c:cloud_migration";
        MailBody mailBody = new MailBody();
        mailBody.setSubject("test mail");
        mailBody.setMessage_template_name("welcome_travel");
        Map<String, List<String>> tags = new HashMap<>();
        List<String> values = new ArrayList<>();
        values.add("lwx");
        tags.put("name", values);
        tags.put("city", values);
        mailBody.setTags(tags);
        sendMail(projectId, topicUrn, mailBody);
    }

    public static void main(String[] args) {
        new SMNTest().test();
    }
}

工具类


import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


/**
* @author liuwenxue
* @date 2020-08-01
*/
public class TokenUtils {

    static String userName = "";
    static String password = "";
    static String domainId = "";
    static String projectId = "";

    static public String getToken(String region) {
        String endpoint = "iam." + region + ".myhuaweicloud.com";
        String url = "https://" + endpoint + "/v3/auth/tokens";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
        httpHeaders.add("X-Auth-Token", "***");
        String body = "{" +
            "\"auth\": {" +
            "\"identity\": {" +
                "\"methods\": [" +
                "\"password\" ]," +
                "\"password\": {" +
                    "\"user\": { "+
                        "\"domain\": {" +
                            "\"name\": \"" + userName + "\"" +
                        "}," +
                        "\"name\": \"" + userName + "\", " +
                                "\"password\": \"" + password + "\"" +
                    "}" +
                "}" +
            "}," +
            "\"scope\": { " +
                "\"project\": {" +
                    "\"name\": \"" + region + "\"" +
                "}" +
            "}" +
        "}" +
        "}";
        HttpEntity<String> httpEntity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<Object> resp = restTemplate.postForEntity(url, httpEntity, Object.class);
        if (resp.getStatusCode().equals(HttpStatus.CREATED)) {
            return resp.getHeaders().get("X-Subject-Token").get(0);
        } else {
            throw new IllegalStateException("get token error");
        }
    }

    static public String getIamToken() {
        return getToken("cn-east-3");
    }

    public static void main(String[] args) {
        System.out.println(getIamToken());
        //System.out.println(getSmnToken());
    }
}
import lombok.Data;

/**
 * @author liuwenxue
 * @date 2020-08-01
 */
@Data
public class AuthBody {
    IdentityBody identity;
    ScopeBody scope;
}

import lombok.Data;

/**
 * @author liuwenxue
 * @date 2020-08-01
 */
@Data
public class KmsDecryptRequest {
    String key_id;

    String cipher_text;

    String datakey_cipher_length;
}

import lombok.Data;

/**
* @author liuwenxue
* @date 2020-08-01
*/
@Data
public class KmsDecryptResponse {
    String data_key;

    String datakey_length;

    String datakey_dgst;
}

import lombok.Data;

/**
* @author liuwenxue
* @date 2020-08-01
*/
@Data
public class KmsEncryptRequest {
    String key_id;

    String plain_text;

    String datakey_plain_length;
}

import lombok.Data;

/**
* @author liuwenxue
* @date 2020-08-01
*/
@Data
public class KmsEncryptResponse {
    String key_id;

    String cipher_text;

    String datakey_length;
}

import lombok.Data;

import java.util.List;
import java.util.Map;

/**
* @author liuwenxue
* @date 2020-08-01
*/
@Data
public class MailBody {
    String subject;

    String message_template_name;

    Map<String, List<String>> tags;
}

/**
* @author liuwenxue
* @date 2020-08-01
*/
@Data
public class ScopeBody {
    ProjectBody project;
}

你可能感兴趣的:(java)