OSDN Git Service

Add utility to pull image from an HTML URL and create a resource.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / utilities / ImageFetcher.java
1 /*\r
2  * This file is part of NixNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18  */\r
19 \r
20 package cx.fbn.nevernote.utilities;\r
21 \r
22 //Written by David Flanagan.  Copyright (c) 1996 O'Reilly & Associates.\r
23 //You may study, use, modify, and distribute this example for any purpose.\r
24 //This example is provided WITHOUT WARRANTY either expressed or implied.\r
25 \r
26 import java.io.BufferedInputStream;\r
27 import java.io.File;\r
28 import java.io.IOException;\r
29 import java.io.InputStream;\r
30 import java.net.MalformedURLException;\r
31 import java.net.URL;\r
32 import java.net.URLConnection;\r
33 import java.security.MessageDigest;\r
34 import java.security.NoSuchAlgorithmException;\r
35 \r
36 import com.evernote.edam.type.Data;\r
37 import com.evernote.edam.type.Resource;\r
38 import com.evernote.edam.type.ResourceAttributes;\r
39 import com.trolltech.qt.core.QUuid;\r
40 \r
41 import cx.fbn.nevernote.sql.DatabaseConnection;\r
42 \r
43 public class ImageFetcher {\r
44         \r
45         private Resource newResource;\r
46         private final ApplicationLogger logger;\r
47         private final DatabaseConnection conn;\r
48         private final String noteGuid;\r
49         \r
50         \r
51         public ImageFetcher(DatabaseConnection c, ApplicationLogger l, String g) {\r
52                 newResource = new Resource();\r
53                 logger = l;\r
54                 conn = c;\r
55                 noteGuid = g;\r
56         }\r
57         \r
58 \r
59  // Get the contents of a URL and return it as an image\r
60  public boolean fetch(String address) \r
61      throws MalformedURLException, IOException \r
62  {\r
63          URL u = new URL(address);\r
64          URLConnection uc = u.openConnection();\r
65          String contentType = uc.getContentType();\r
66          int contentLength = uc.getContentLength();\r
67          if (contentType.startsWith("text/") || contentLength == -1) {\r
68              throw new IOException("This is not a binary file.");\r
69          }\r
70          InputStream raw = uc.getInputStream();\r
71          InputStream in = new BufferedInputStream(raw);\r
72          byte[] data = new byte[contentLength];\r
73          int bytesRead = 0;\r
74          int offset = 0;\r
75          while (offset < contentLength) {\r
76            bytesRead = in.read(data, offset, data.length - offset);\r
77            if (bytesRead == -1)\r
78              break;\r
79            offset += bytesRead;\r
80          }\r
81          in.close();\r
82 \r
83          if (offset != contentLength) {\r
84            throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");\r
85          }\r
86         \r
87          newResource = createResource(data, address);\r
88          if (newResource != null)\r
89                  return true;\r
90          else\r
91                  return false;\r
92  }\r
93  \r
94  \r
95         // Convert the binary data to a resource\r
96         private Resource createResource(byte[] fileData, String address) {\r
97                 logger.log(logger.EXTREME, "Inside create resource");\r
98                 //These two lines are added to handle odd characters in the name like #.  Without it\r
99                 // toLocalFile() chokes and returns the wrong name.\r
100         MessageDigest md;\r
101         try {\r
102                 logger.log(logger.EXTREME, "Generating MD5");\r
103                 md = MessageDigest.getInstance("MD5");\r
104                 md.update(fileData);\r
105                 byte[] hash = md.digest();\r
106   \r
107                 Resource r = new Resource();\r
108                 r.setGuid(QUuid.createUuid().toString().replace("}", "").replace("{", ""));\r
109                 r.setNoteGuid(noteGuid);\r
110                 r.setMime("image/" +address.substring(address.lastIndexOf(".")+1));\r
111                 r.setActive(true);\r
112                 r.setUpdateSequenceNum(0);\r
113                 r.setWidth((short) 0);\r
114                 r.setHeight((short) 0);\r
115                 r.setDuration((short) 0);\r
116                                 \r
117                 Data d = new Data();\r
118                 d.setBody(fileData);\r
119                 d.setBodyIsSet(true);\r
120                 d.setBodyHash(hash);\r
121                 d.setBodyHashIsSet(true);\r
122                 r.setData(d);\r
123                 d.setSize(fileData.length);\r
124                 \r
125                 int fileNamePos = address.lastIndexOf(File.separator);\r
126                 if (fileNamePos == -1)\r
127                         fileNamePos = address.lastIndexOf("/");\r
128                         String fileName = address.substring(fileNamePos+1);\r
129                 ResourceAttributes a = new ResourceAttributes();\r
130                 a.setAltitude(0);\r
131                 a.setAltitudeIsSet(false);\r
132                 a.setLongitude(0);\r
133                 a.setLongitudeIsSet(false);\r
134                 a.setLatitude(0);\r
135                 a.setLatitudeIsSet(false);\r
136                 a.setCameraMake("");\r
137                 a.setCameraMakeIsSet(false);\r
138                 a.setCameraModel("");\r
139                 a.setCameraModelIsSet(false);\r
140                 a.setAttachment(false);\r
141                 a.setAttachmentIsSet(true);\r
142                 a.setClientWillIndex(false);\r
143                 a.setClientWillIndexIsSet(true);\r
144                 a.setRecoType("");\r
145                 a.setRecoTypeIsSet(false);\r
146                 a.setSourceURL(fileName);\r
147                 a.setSourceURLIsSet(true);\r
148                 a.setTimestamp(0);\r
149                 a.setTimestampIsSet(false);\r
150                 a.setFileName(fileName);\r
151                 a.setFileNameIsSet(true);\r
152                 r.setAttributes(a);\r
153                 \r
154                 //conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
155                 logger.log(logger.EXTREME, "Resource created");\r
156                 \r
157                 // Now write it out so someone else can look at it\r
158                 \r
159                 return r;\r
160         } catch (NoSuchAlgorithmException e1) {\r
161                 e1.printStackTrace();\r
162                 }\r
163         return null;\r
164         }\r
165 \r
166 }