JAL-3691 patch toUpper/toLower to use Locale.ROOT for 2.11.2 src
[jalview.git] / src / org / stackoverflowusers / file / WindowsShortcut.java
1 package org.stackoverflowusers.file;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.text.ParseException;
9 import java.util.Locale;
10
11 /**
12  * Represents a Windows shortcut (typically visible to Java only as a '.lnk' file).
13  *
14  * Retrieved 2011-09-23 from http://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java/672775#672775
15  * Originally called LnkParser
16  *
17  * Written by: (the stack overflow users, obviously!)
18  *   Apache Commons VFS dependency removed by crysxd (why were we using that!?) https://github.com/crysxd
19  *   Headerified, refactored and commented by Code Bling http://stackoverflow.com/users/675721/code-bling
20  *   Network file support added by Stefan Cordes http://stackoverflow.com/users/81330/stefan-cordes
21  *   Adapted by Sam Brightman http://stackoverflow.com/users/2492/sam-brightman
22  *   Based on information in 'The Windows Shortcut File Format' by Jesse Hager <jessehager@iname.com>
23  *   And somewhat based on code from the book 'Swing Hacks: Tips and Tools for Killer GUIs'
24  *     by Joshua Marinacci and Chris Adamson
25  *     ISBN: 0-596-00907-0
26  *     http://www.oreilly.com/catalog/swinghks/
27  */
28 public class WindowsShortcut
29 {
30     private boolean isDirectory;
31     private boolean isLocal;
32     private String real_file;
33
34     /**
35      * Provides a quick test to see if this could be a valid link !
36      * If you try to instantiate a new WindowShortcut and the link is not valid,
37      * Exceptions may be thrown and Exceptions are extremely slow to generate,
38      * therefore any code needing to loop through several files should first check this.
39      *
40      * @param file the potential link
41      * @return true if may be a link, false otherwise
42      * @throws IOException if an IOException is thrown while reading from the file
43      */
44     public static boolean isPotentialValidLink(File file) throws IOException {
45         final int minimum_length = 0x64;
46         InputStream fis = new FileInputStream(file);
47         boolean isPotentiallyValid = false;
48         try {
49             isPotentiallyValid = file.isFile()
50                 && file.getName().toLowerCase(Locale.ROOT).endsWith(".lnk")
51                 && fis.available() >= minimum_length
52                 && isMagicPresent(getBytes(fis, 32));
53         } finally {
54             fis.close();
55         }
56         return isPotentiallyValid;
57     }
58
59     public WindowsShortcut(File file) throws IOException, ParseException {
60         InputStream in = new FileInputStream(file);
61         try {
62             parseLink(getBytes(in));
63         } finally {
64             in.close();
65         }
66     }
67
68     /**
69      * @return the name of the filesystem object pointed to by this shortcut
70      */
71     public String getRealFilename() {
72         return real_file;
73     }
74
75     /**
76      * Tests if the shortcut points to a local resource.
77      * @return true if the 'local' bit is set in this shortcut, false otherwise
78      */
79     public boolean isLocal() {
80         return isLocal;
81     }
82
83     /**
84      * Tests if the shortcut points to a directory.
85      * @return true if the 'directory' bit is set in this shortcut, false otherwise
86      */
87     public boolean isDirectory() {
88         return isDirectory;
89     }
90
91     /**
92      * Gets all the bytes from an InputStream
93      * @param in the InputStream from which to read bytes
94      * @return array of all the bytes contained in 'in'
95      * @throws IOException if an IOException is encountered while reading the data from the InputStream
96      */
97     private static byte[] getBytes(InputStream in) throws IOException {
98         return getBytes(in, null);
99     }
100     
101     /**
102      * Gets up to max bytes from an InputStream
103      * @param in the InputStream from which to read bytes
104      * @param max maximum number of bytes to read
105      * @return array of all the bytes contained in 'in'
106      * @throws IOException if an IOException is encountered while reading the data from the InputStream
107      */
108     private static byte[] getBytes(InputStream in, Integer max) throws IOException {
109         // read the entire file into a byte buffer
110         ByteArrayOutputStream bout = new ByteArrayOutputStream();
111         byte[] buff = new byte[256];
112         while (max == null || max > 0) {
113             int n = in.read(buff);
114             if (n == -1) {
115                 break;
116             }
117             bout.write(buff, 0, n);
118             if (max != null)
119                 max -= n;
120         }
121         in.close();
122         return bout.toByteArray();
123     }
124
125     private static boolean isMagicPresent(byte[] link) {
126         final int magic = 0x0000004C;
127         final int magic_offset = 0x00;
128         return link.length >= 32 && bytesToDword(link, magic_offset) == magic;
129     }
130
131     /**
132      * Gobbles up link data by parsing it and storing info in member fields
133      * @param link all the bytes from the .lnk file
134      */
135     private void parseLink(byte[] link) throws ParseException {
136         try {
137             if (!isMagicPresent(link))
138                 throw new ParseException("Invalid shortcut; magic is missing", 0);
139
140             // get the flags byte
141             byte flags = link[0x14];
142
143             // get the file attributes byte
144             final int file_atts_offset = 0x18;
145             byte file_atts = link[file_atts_offset];
146             byte is_dir_mask = (byte)0x10;
147             if ((file_atts & is_dir_mask) > 0) {
148                 isDirectory = true;
149             } else {
150                 isDirectory = false;
151             }
152
153             // if the shell settings are present, skip them
154             final int shell_offset = 0x4c;
155             final byte has_shell_mask = (byte)0x01;
156             int shell_len = 0;
157             if ((flags & has_shell_mask) > 0) {
158                 // the plus 2 accounts for the length marker itself
159                 shell_len = bytesToWord(link, shell_offset) + 2;
160             }
161
162             // get to the file settings
163             int file_start = 0x4c + shell_len;
164
165             final int file_location_info_flag_offset_offset = 0x08;
166             int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];
167             isLocal = (file_location_info_flag & 2) == 0;
168             // get the local volume and local system values
169             //final int localVolumeTable_offset_offset = 0x0C;
170             final int basename_offset_offset = 0x10;
171             final int networkVolumeTable_offset_offset = 0x14;
172             final int finalname_offset_offset = 0x18;
173             int finalname_offset = link[file_start + finalname_offset_offset] + file_start;
174             String finalname = getNullDelimitedString(link, finalname_offset);
175             if (isLocal) {
176                 int basename_offset = link[file_start + basename_offset_offset] + file_start;
177                 String basename = getNullDelimitedString(link, basename_offset);
178                 real_file = basename + finalname;
179             } else {
180                 int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;
181                 int shareName_offset_offset = 0x08;
182                 int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]
183                     + networkVolumeTable_offset;
184                 String shareName = getNullDelimitedString(link, shareName_offset);
185                 real_file = shareName + "\\" + finalname;
186             }
187         } catch (ArrayIndexOutOfBoundsException e) {
188             throw new ParseException("Could not be parsed, probably not a valid WindowsShortcut", 0);
189         }
190     }
191
192     private static String getNullDelimitedString(byte[] bytes, int off) {
193         int len = 0;
194         // count bytes until the null character (0)
195         while (true) {
196             if (bytes[off + len] == 0) {
197                 break;
198             }
199             len++;
200         }
201         return new String(bytes, off, len);
202     }
203
204     /*
205      * convert two bytes into a short note, this is little endian because it's
206      * for an Intel only OS.
207      */
208     private static int bytesToWord(byte[] bytes, int off) {
209         return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
210     }
211
212     private static int bytesToDword(byte[] bytes, int off) {
213         return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off);
214     }
215
216 }