1 /*
2  * Copyright 2014-2020 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.springframework.data.jpa.repository.query;
17
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.sql.Blob;
22 import java.sql.SQLException;
23
24 import org.springframework.core.convert.converter.Converter;
25 import org.springframework.dao.CleanupFailureDataAccessException;
26 import org.springframework.dao.DataRetrievalFailureException;
27 import org.springframework.lang.Nullable;
28 import org.springframework.util.StreamUtils;
29
30 /**
31  * Container for additional JPA result {@link Converter}s.
32  *
33  * @author Thomas Darimont
34  * @author Mark Paluch
35  * @since 1.6
36  */

37 final class JpaResultConverters {
38
39     /**
40      * {@code private} to prevent instantiation.
41      */

42     private JpaResultConverters() {}
43
44     /**
45      * Converts the given {@link Blob} into a {@code byte[]}.
46      *
47      * @author Thomas Darimont
48      */

49     enum BlobToByteArrayConverter implements Converter<Blob, byte[]> {
50
51         INSTANCE;
52
53         @Nullable
54         @Override
55         public byte[] convert(@Nullable Blob source) {
56
57             if (source == null) {
58                 return null;
59             }
60
61             InputStream blobStream = null;
62             try {
63
64                 blobStream = source.getBinaryStream();
65
66                 if (blobStream != null) {
67
68                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
69                     StreamUtils.copy(blobStream, baos);
70                     return baos.toByteArray();
71                 }
72
73             } catch (SQLException | IOException e) {
74                 throw new DataRetrievalFailureException("Couldn't retrieve data from blob.", e);
75             } finally {
76                 if (blobStream != null) {
77                     try {
78                         blobStream.close();
79                     } catch (IOException e) {
80                         throw new CleanupFailureDataAccessException("Couldn't close binary stream for given blob.", e);
81                     }
82                 }
83             }
84
85             return null;
86         }
87     }
88 }
89