1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 package httpserv;
23 
24 import com.sun.net.httpserver.Headers;
25 import com.sun.net.httpserver.HttpExchange;
26 import com.sun.net.httpserver.HttpHandler;
27 import com.sun.net.httpserver.HttpServer;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.net.InetSocketAddress;
33 
34 /**
35  *
36  * @author jochen
37  */
38 public class Main {
39 
40     /**
41      * @param args the command line arguments
42      */
43     public static void main(String[] args) {
44         try {
45 
46             Option[] opts = new Option[2];
47             opts[0] = new Option("--help", "-h", false);
48             opts[1] = new Option("--accept", "-a", true);
49             if (!parseOptions(args, opts)) {
50                 return;
51             }
52             HttpServer server = HttpServer.create(
53                     new InetSocketAddress((Integer) opts[1].value), 0);
54             server.createContext("/", new MyHandler());
55             server.setExecutor(null);
56             server.start();
57         } catch (Exception e) {
58             e.printStackTrace();
59         }
60     }        // TODO code application logic here
61 
62     static boolean parseOptions(String[] args, Option[] inout_options) {
63         if (args.length == 0) {
64             printUsage();
65             return false;
66         }
67 
68         boolean bWrongArgs = true;
69         Option currentOpt = null;
70 
71         for (String s : args) {
72             // get the value for an option
73             if (currentOpt != null && currentOpt.bHasValue) {
74                 //now we expect the value for the option
75                 //check the type
76                 try {
77                     if (currentOpt.sLong.equals("--accept")) {
78                         currentOpt.value = Integer.decode(s);
79                     }
80                 } catch (Exception e ) {
81                     printUsage();
82                     return false;
83                 }
84                 currentOpt = null;
85                 continue;
86             } else {
87                 currentOpt = null;
88             }
89 
90 
91             // get the option
92             for (Option o : inout_options) {
93                 if (s.equals(o.sLong) || s.equals(o.sShort)) {
94                     bWrongArgs = false;
95                     //special handling for --help
96                     if (o.sLong.equals("--help")) {
97                         printUsage();
98                         return false;
99                     }
100                     else
101                     {
102                         currentOpt = o;
103                         if (!o.bHasValue) {
104                             o.bSet = true;
105                         }
106                         break;
107                     }
108                 }
109             }
110         }
111 
112         if (bWrongArgs) {
113             printUsage();
114             return false;
115         }
116         return true;
117     }
118 
119     static void printUsage() {
120         String usage = new String(
121                 "Usage: \n" +
122                 "java -jar httpserv [options] \n" +
123                 "\n" +
124                 "Options are: \n" +
125                 "-h --help \t this help \n" +
126                 "-a --accept port \t the port number to which this server listens \n");
127         System.out.println(usage);
128     }
129 }
130 
131 class MyHandler implements HttpHandler {
132 
133     public void handle(HttpExchange xchange) throws IOException {
134         try {
135             //First get the path to the file
136             File fileCurrent = new File(".");
137             String sRequestPath = xchange.getRequestURI().getPath();
138             System.out.println("requested: " + sRequestPath);
139             File fileRequest = new File(new File(".").getCanonicalPath(), sRequestPath);
140             if (!fileRequest.exists()) {
141                 throw new Exception("The file " + fileRequest.toString() + " does not exist!\n");
142             }
143             else if (fileRequest.isDirectory()) {
144                 throw new Exception(fileRequest.toString() + " is a directory!\n");
145             }
146 
147 
148             //Read the file into a byte array
149             byte[] data = new byte[(int) fileRequest.length()];
150             FileInputStream fr = new FileInputStream(fileRequest);
151             int count = fr.read(data);
152 
153             //set the Content-type header
154             Headers h = xchange.getResponseHeaders();
155             String canonicalPath = fileRequest.getCanonicalPath();
156             int lastIndex = canonicalPath.lastIndexOf(".");
157             String fileExtension = canonicalPath.substring(lastIndex + 1);
158 
159             if (fileExtension.equalsIgnoreCase("crl"))
160             {
161                 //h.set("Content-Type","application/x-pkcs7-crl");
162                 h.set("Content-Type","application/pkix-crl");
163             }
164             else if (fileExtension.equalsIgnoreCase("crt")
165                     || fileExtension.equalsIgnoreCase("cer")
166                     || fileExtension.equalsIgnoreCase("der"))
167             {
168                 h.set("Content-Type", "application/x-x509-ca-cert");
169             }
170 
171             //write out the requested file
172             xchange.sendResponseHeaders(200, data.length);
173             OutputStream os = xchange.getResponseBody();
174             os.write(data);
175             os.close();
176             System.out.println("delivered: " + fileRequest.toString());
177 
178         } catch (Exception e) {
179             xchange.sendResponseHeaders(404, e.getMessage().length());
180             OutputStream os = xchange.getResponseBody();
181             os.write(e.getMessage().getBytes());
182             os.close();
183             System.out.println("Error: " + e.getMessage());
184         }
185     }
186 }
187 
188 class Option {
189 
190     Option(String _sLong, String _sShort, boolean _bHasValue) {
191         sLong = _sLong;
192         sShort = _sShort;
193         bHasValue = _bHasValue;
194     }
195     String sLong;
196     String sShort;
197     boolean bHasValue;
198     Object value;
199     //indicates if this option was set if it does not need a value. Otherwise value
200     //is set.
201     boolean bSet;
202 }
203 
204 
205