shench3
2026-03-03 c90dd2da4cfa60c06099c4e66fba6b203bf90b59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.xiaopeng.map.service.serviceimpl;
 
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.xiaopeng.map.config.OssProperties;
import com.xiaopeng.map.service.RobotaxiOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * ROBOTAXI OSS 服务实现,使用阿里云官方 OSS SDK 上传 ODD 图层文件。
 * 路径格式:ROBOTAXI_ODD_layer/{区域编码}/{环境}/{车辆uuid}/{fileName}
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = "aliyun.oss.enabled", havingValue = "true")
public class RobotaxiOssServiceImpl implements RobotaxiOssService {
 
    private final OssProperties ossProperties;
 
    @Override
    public String uploadOddLayerFile(byte[] data, String fileName, String areaCode, String vehicleUuid) {
        if (data == null) {
            throw new IllegalArgumentException("data cannot be null");
        }
        return uploadOddLayerFile(new ByteArrayInputStream(data), data.length, fileName, areaCode, vehicleUuid);
    }
 
    @Override
    public String uploadOddLayerFile(InputStream inputStream, long contentLength, String fileName,
                                    String areaCode, String vehicleUuid) {
        validateParams(fileName, areaCode, vehicleUuid);
 
        String objectKey = buildObjectKey(areaCode, vehicleUuid, fileName);
        String bucketName = ossProperties.getBucketName();
 
        OSS ossClient = null;
        try {
            ossClient = createOssClient();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(contentLength);
 
            ossClient.putObject(bucketName, objectKey, inputStream, metadata);
            log.debug("Uploaded ODD layer file to OSS: {}", objectKey);
            return objectKey;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
 
    @Override
    public boolean deleteByObjectKey(String objectKey) {
        if (!StringUtils.hasText(objectKey)) {
            throw new IllegalArgumentException("objectKey cannot be empty");
        }
        String bucketName = ossProperties.getBucketName();
        OSS ossClient = null;
        try {
            ossClient = createOssClient();
            ossClient.deleteObject(bucketName, objectKey);
            log.debug("Deleted OSS object: {}", objectKey);
            return true;
        } catch (Exception e) {
            log.warn("Failed to delete OSS object: {}, error: {}", objectKey, e.getMessage());
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
 
    @Override
    public List<String> deleteByObjectKeys(List<String> objectKeys) {
        if (objectKeys == null || objectKeys.isEmpty()) {
            return new ArrayList<>();
        }
        String bucketName = ossProperties.getBucketName();
        OSS ossClient = null;
        List<String> deleted = new ArrayList<>();
        try {
            ossClient = createOssClient();
            for (String key : objectKeys) {
                if (!StringUtils.hasText(key)) {
                    continue;
                }
                try {
                    ossClient.deleteObject(bucketName, key);
                    deleted.add(key);
                    log.debug("Deleted OSS object: {}", key);
                } catch (Exception e) {
                    log.warn("Failed to delete OSS object: {}, error: {}", key, e.getMessage());
                }
            }
            return deleted;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
 
    @Override
    public List<String> deleteOddLayerFilesByPrefix(String areaCode, String vehicleUuid) {
        validateParamsForPrefix(areaCode, vehicleUuid);
 
        String prefix = buildObjectKeyPrefix(areaCode, vehicleUuid);
        String bucketName = ossProperties.getBucketName();
 
        OSS ossClient = null;
        try {
            ossClient = createOssClient();
            List<String> objectKeys = new ArrayList<>();
            String nextMarker = null;
 
            do {
                ListObjectsRequest request = new ListObjectsRequest(bucketName).withPrefix(prefix).withMarker(nextMarker);
                ObjectListing listing = ossClient.listObjects(request);
                for (OSSObjectSummary summary : listing.getObjectSummaries()) {
                    objectKeys.add(summary.getKey());
                }
                nextMarker = listing.isTruncated() ? listing.getNextMarker() : null;
            } while (nextMarker != null);
 
            if (objectKeys.isEmpty()) {
                return new ArrayList<>();
            }
            return deleteByObjectKeys(objectKeys);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
 
    @Override
    public String generatePresignedDownloadUrl(String objectKey, int expireSeconds) {
        if (!StringUtils.hasText(objectKey)) {
            throw new IllegalArgumentException("objectKey cannot be empty");
        }
        if (expireSeconds <= 0) {
            throw new IllegalArgumentException("expireSeconds must be positive");
        }
        String bucketName = ossProperties.getBucketName();
        OSS ossClient = null;
        try {
            ossClient = createOssClient();
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey, HttpMethod.GET);
            request.setExpiration(new Date(System.currentTimeMillis() + expireSeconds * 1000L));
            URL url = ossClient.generatePresignedUrl(request);
            return url != null ? url.toString() : null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
 
    private void validateParamsForPrefix(String areaCode, String vehicleUuid) {
        if (!StringUtils.hasText(areaCode)) {
            throw new IllegalArgumentException("areaCode cannot be empty");
        }
        if (!StringUtils.hasText(vehicleUuid)) {
            throw new IllegalArgumentException("vehicleUuid cannot be empty");
        }
    }
 
    private String buildObjectKeyPrefix(String areaCode, String vehicleUuid) {
        String pathPrefix = ossProperties.getPathPrefix();
        if (!StringUtils.hasText(pathPrefix)) {
            pathPrefix = "ROBOTAXI_ODD_layer";
        }
        String env = StringUtils.hasText(ossProperties.getEnv()) ? ossProperties.getEnv() : "test";
        return String.format("%s/%s/%s/%s/", pathPrefix, areaCode, env, vehicleUuid);
    }
 
    private void validateParams(String fileName, String areaCode, String vehicleUuid) {
        if (!StringUtils.hasText(fileName)) {
            throw new IllegalArgumentException("fileName cannot be empty");
        }
        if (!StringUtils.hasText(areaCode)) {
            throw new IllegalArgumentException("areaCode cannot be empty");
        }
        if (!StringUtils.hasText(vehicleUuid)) {
            throw new IllegalArgumentException("vehicleUuid cannot be empty");
        }
    }
 
    private String buildObjectKey(String areaCode, String vehicleUuid, String fileName) {
        String pathPrefix = ossProperties.getPathPrefix();
        if (!StringUtils.hasText(pathPrefix)) {
            pathPrefix = "ROBOTAXI_ODD_layer";
        }
        String env = StringUtils.hasText(ossProperties.getEnv()) ? ossProperties.getEnv() : "test";
        return String.format("%s/%s/%s/%s/%s", pathPrefix, areaCode, env, vehicleUuid, fileName);
    }
 
    private OSS createOssClient() {
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
 
        if (!StringUtils.hasText(endpoint) || !StringUtils.hasText(accessKeyId) || !StringUtils.hasText(accessKeySecret)) {
            throw new IllegalStateException("OSS config incomplete: endpoint, accessKeyId, accessKeySecret must be set");
        }
 
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
 
    /**
     * 构建 OSS 对象访问 URL:https://{bucket}.{endpoint}/{objectKey}
     */
    private String buildObjectUrl(String bucketName, String objectKey) {
        String endpoint = ossProperties.getEndpoint();
        if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
            int schemeEnd = endpoint.indexOf("://") + 3;
            endpoint = endpoint.substring(schemeEnd);
        }
        return String.format("https://%s.%s/%s", bucketName, endpoint, objectKey);
    }
}