Skip to content
This repository
Browse code

reverted HTTP Server commit (b135774)

  • Loading branch information...
commit d36d4470ff786aadc2e70a36e689882d0bce4cc0 1 parent 83b2be2
Stoyan stoyan authored
2  ant.properties
@@ -3,6 +3,6 @@ lib.dir = lib
3 3 doc.dir = doc
4 4 build.dir = build
5 5 product.name = yuicompressor
6   -version.number = 2.4.5pre
  6 +version.number = 2.4.4
7 7 jar.name = ${product.name}-${version.number}.jar
8 8 dist.package.name = ${product.name}-${version.number}
6 build.xml
@@ -20,10 +20,9 @@
20 20 includes="**/*.java"
21 21 deprecation="off"
22 22 debug="on"
23   - source="6">
  23 + source="1.4">
24 24 <classpath>
25 25 <pathelement location="${lib.dir}/jargs-1.0.jar"/>
26   - <pathelement location="${lib.dir}/json.jar"/>
27 26 <pathelement location="${lib.dir}/rhino-1.6R7.jar"/>
28 27 </classpath>
29 28 </javac>
@@ -35,7 +34,6 @@
35 34 (some of our own classes will override the Rhino classes) -->
36 35 <unjar src="${lib.dir}/jargs-1.0.jar" dest="${build.dir}/jar"/>
37 36 <unjar src="${lib.dir}/rhino-1.6R7.jar" dest="${build.dir}/jar"/>
38   - <unjar src="${lib.dir}/json.jar" dest="${build.dir}/jar"/>
39 37 <copy todir="${build.dir}/jar">
40 38 <fileset dir="${build.dir}/classes" includes="**/*.class"/>
41 39 </copy>
@@ -65,4 +63,4 @@
65 63 includes="${dist.package.name}/**/*"/>
66 64 </target>
67 65
68   -</project>
  66 +</project>
BIN  lib/json.jar
Binary file not shown
BIN  src/com/yahoo/platform/yui/compressor/CompressorErrorReporter.java
Binary file not shown
240 src/com/yahoo/platform/yui/compressor/CompressorHttpHandler.java
... ... @@ -1,240 +0,0 @@
1   -package com.yahoo.platform.yui.compressor;
2   -
3   -import com.sun.net.httpserver.HttpExchange;
4   -import com.sun.net.httpserver.HttpHandler;
5   -import org.json.JSONArray;
6   -import org.json.JSONException;
7   -import org.json.JSONString;
8   -import org.json.JSONStringer;
9   -import org.mozilla.javascript.EvaluatorException;
10   -
11   -import java.io.BufferedReader;
12   -import java.io.ByteArrayInputStream;
13   -import java.io.ByteArrayOutputStream;
14   -import java.io.IOException;
15   -import java.io.InputStream;
16   -import java.io.InputStreamReader;
17   -import java.io.OutputStream;
18   -import java.io.OutputStreamWriter;
19   -import java.io.Reader;
20   -import java.io.Writer;
21   -import java.net.HttpURLConnection;
22   -import java.net.URLDecoder;
23   -import java.util.LinkedList;
24   -import java.util.Map;
25   -
26   -public class CompressorHttpHandler implements HttpHandler {
27   -
28   - Configuration config;
29   -
30   - class Response implements JSONString {
31   - private LinkedList<String> errors = new LinkedList<String>();
32   - private LinkedList<String> warnings = new LinkedList<String>();
33   - private ByteArrayOutputStream result = new ByteArrayOutputStream();
34   -
35   - public LinkedList<String> getErrors() {
36   - return errors;
37   - }
38   -
39   - public void setErrors(LinkedList<String> errors) {
40   - this.errors = errors;
41   - }
42   -
43   - public LinkedList<String> getWarnings() {
44   - return warnings;
45   - }
46   -
47   - public void setWarnings(LinkedList<String> warnings) {
48   - this.warnings = warnings;
49   - }
50   -
51   - public ByteArrayOutputStream getResult() {
52   - return result;
53   - }
54   -
55   - public void setResult(ByteArrayOutputStream result) {
56   - this.result = result;
57   - }
58   -
59   - public String toJSONString() {
60   - try {
61   - JSONArray warnings = new JSONArray(getWarnings());
62   - JSONArray errors = new JSONArray(getErrors());
63   - String result = new String(getResult().toByteArray());
64   - return new JSONStringer()
65   - .object().key("result").value(result)
66   - .key("warnings").value(warnings)
67   - .key("errors").value(errors)
68   - .endObject().toString();
69   - } catch (JSONException ex) {
70   - return "JSON Failure: " + ex.getMessage();
71   - }
72   - }
73   - }
74   -
75   - public CompressorHttpHandler (Configuration config) {
76   - config.setOutputRaw("json");
77   - this.config = config;
78   - }
79   -
80   - public void handle (HttpExchange t) throws IOException {
81   - // Inherit configuration defaults from the command line.
82   - // Make a clone for this request.
83   - Configuration config = this.config.clone();
84   -
85   - try {
86   - config = parseOptions(config, t); // get desired response format first
87   - if (!t.getRequestMethod().toUpperCase().equals("PUT")) {
88   - throw new ConfigurationException("You must PUT JavaScript or CSS to this endpoint.");
89   - }
90   - } catch (ConfigurationException ex) {
91   - abort("Bad request", ex, HttpURLConnection.HTTP_BAD_REQUEST, config, t);
92   - return;
93   - }
94   -
95   - // Theory of operation:
96   - // InputStream to String
97   - // Decode
98   - // String to InputStream
99   -
100   - InputStream requestBody = t.getRequestBody();
101   - Reader in = new InputStreamReader(requestBody, config.getCharset());
102   - BufferedReader br = new BufferedReader(in);
103   - StringBuilder sb = new StringBuilder();
104   - String tmp = br.readLine();
105   - while (tmp != null) {
106   - sb.append(tmp);
107   - sb.append("\n");
108   - tmp = br.readLine();
109   - }
110   - String incoming = sb.toString();
111   - // incoming = URLDecoder.decode(incoming, config.getCharset());
112   -
113   - // System.err.print(incoming.toCharArray());
114   -
115   - in = new InputStreamReader(new ByteArrayInputStream(incoming.getBytes()));
116   -
117   - Response response;
118   -
119   - try {
120   - response = compress(in, config);
121   - } catch (EvaluatorException ex) {
122   - // Your fault.
123   - abort("Syntax error", ex, HttpURLConnection.HTTP_BAD_REQUEST, config, t);
124   - return;
125   - } catch (IOException ex) {
126   - // My fault.
127   - abort("Compressor failed", ex, HttpURLConnection.HTTP_INTERNAL_ERROR, config, t);
128   - return;
129   - }
130   -
131   - respond(HttpURLConnection.HTTP_OK, response, config, t);
132   - }
133   -
134   - private void respond (int httpCode, Response response, Configuration config, HttpExchange t) {
135   - try {
136   -
137   - OutputStream body = t.getResponseBody();
138   -
139   - String outputFormat = config.getOutput();
140   -
141   - boolean json = false;
142   - if (outputFormat.equals("json")) json = true;
143   -
144   - byte[] resultBytes;
145   - String str;
146   - if (json) {
147   - str = response.toJSONString();
148   - resultBytes = str.getBytes();
149   - } else {
150   - if (httpCode != HttpURLConnection.HTTP_OK) {
151   - str = "Error: " + response.getErrors().getFirst();
152   - resultBytes = str.getBytes();
153   - } else {
154   - resultBytes = response.getResult().toByteArray();
155   - str = new String(resultBytes);
156   - }
157   - }
158   -
159   - t.sendResponseHeaders(httpCode, str.length());
160   -
161   - body.write(resultBytes);
162   - body.close();
163   -
164   - } catch (Exception ex) {
165   - // We can't really recover.
166   - System.err.println("Fatal error in HTTP server while responding to the request.");
167   - ex.printStackTrace();
168   - }
169   - }
170   -
171   - private void abort (String message, Exception ex, int httpCode, Configuration config, HttpExchange t)
172   - throws IOException {
173   - String error = message + ": " + ex.getMessage();
174   - // System.err.println(error);
175   -
176   - Response response = new Response();
177   - LinkedList<String> errors = new LinkedList<String>();
178   - errors.add(error);
179   - response.setErrors(errors);
180   -
181   - respond(httpCode, response, config, t);
182   - }
183   -
184   - private Configuration parseOptions (Configuration config, HttpExchange t)
185   - throws ConfigurationException, IOException {
186   - Map<String, String> query = (Map<String, String>) t.getAttribute("query");
187   -
188   - for (String key : query.keySet()) {
189   - String value = query.get(key);
190   - key = key.toLowerCase();
191   - value = value.toLowerCase();
192   - // System.err.println("parseOptions: " + key + " = " + value);
193   - if (key.equals("charset")) {
194   - config.setCharset(value);
195   - } else if (key.equals("output")) {
196   - config.setOutput(value);
197   - } else if (key.equals("type")) {
198   - config.setInputType(value);
199   - } else if (key.equals("lineBreak")) {
200   - config.setLineBreak(value);
201   - } else if (key.equals("semicolons")) {
202   - config.setPreserveSemicolons(value.equals(""));
203   - } else if (key.equals("munge")) {
204   - config.setMunge(value.equals("1") || value.equals("true"));
205   - } else if (key.equals("optimize")) {
206   - config.setOptimize(value.equals("1") || value.equals("true"));
207   - }
208   - }
209   -
210   - return config;
211   - }
212   -
213   - private Response compress (Reader in, Configuration config) throws IOException {
214   - ByteArrayOutputStream result = new ByteArrayOutputStream();
215   - Writer streamWriter = new OutputStreamWriter(result, config.getCharset());
216   -
217   - Response response = new Response();
218   -
219   - if (config.isCss()) {
220   -
221   - CssCompressor compressor = new CssCompressor(in);
222   - compressor.compress(streamWriter, config.getLineBreak());
223   -
224   - } else { // config.isJavascript() may also be unset. assume JS anyway.
225   -
226   - CompressorErrorReporter reporter = new CompressorErrorReporter();
227   - JavaScriptCompressor compressor = new JavaScriptCompressor(in, reporter);
228   - compressor.compress(streamWriter, config);
229   - response.setErrors(reporter.getErrors());
230   - response.setWarnings(reporter.getWarnings());
231   -
232   - }
233   -
234   - streamWriter.close();
235   - response.setResult(result);
236   -
237   - return response;
238   - }
239   -
240   -}
235 src/com/yahoo/platform/yui/compressor/Configuration.java
... ... @@ -1,235 +0,0 @@
1   -package com.yahoo.platform.yui.compressor;
2   -
3   -import jargs.gnu.CmdLineParser;
4   -
5   -import java.nio.charset.Charset;
6   -import java.util.List;
7   -
8   -public class Configuration implements Cloneable {
9   -
10   - protected String inputType;
11   - protected boolean javascript;
12   - protected boolean css;
13   -
14   - protected boolean verbose;
15   - protected boolean munge;
16   - protected int lineBreak;
17   - protected boolean preserveSemicolons;
18   - protected boolean optimize;
19   - protected boolean help;
20   - protected String charset;
21   -
22   - protected int serverPort;
23   -
24   - protected String output;
25   - protected List files;
26   -
27   - public Configuration (String args[]) throws ConfigurationException {
28   - CmdLineParser cliParser = new CmdLineParser();
29   -
30   - CmdLineParser.Option typeOpt = cliParser.addStringOption("type");
31   - CmdLineParser.Option verboseOpt = cliParser.addBooleanOption('v', "verbose");
32   - CmdLineParser.Option nomungeOpt = cliParser.addBooleanOption("nomunge");
33   - CmdLineParser.Option linebreakOpt = cliParser.addStringOption("line-break");
34   - CmdLineParser.Option preserveSemiOpt = cliParser.addBooleanOption("preserve-semi");
35   - CmdLineParser.Option disableOptimizationsOpt = cliParser.addBooleanOption("disable-optimizations");
36   - CmdLineParser.Option helpOpt = cliParser.addBooleanOption('h', "help");
37   - CmdLineParser.Option charsetOpt = cliParser.addStringOption("charset");
38   - CmdLineParser.Option serverOpt = cliParser.addStringOption("server");
39   - CmdLineParser.Option outputFilenameOpt = cliParser.addStringOption('o', "output");
40   -
41   - try {
42   - cliParser.parse(args);
43   - } catch (CmdLineParser.OptionException ex) {
44   - throw new ConfigurationException("Command line parse failed.");
45   - }
46   -
47   - setInputType((String) cliParser.getOptionValue(typeOpt));
48   - setVerbose(cliParser.getOptionValue(verboseOpt) != null);
49   - setMunge(cliParser.getOptionValue(nomungeOpt) == null);
50   - setLineBreak((String) cliParser.getOptionValue(linebreakOpt));
51   - setPreserveSemicolons(cliParser.getOptionValue(preserveSemiOpt) != null);
52   - setOptimize(cliParser.getOptionValue(disableOptimizationsOpt) == null);
53   - setHelp(cliParser.getOptionValue(helpOpt) != null);
54   - setCharset((String) cliParser.getOptionValue(charsetOpt));
55   - setServerPort((String) cliParser.getOptionValue(serverOpt));
56   - setOutput((String) cliParser.getOptionValue(outputFilenameOpt));
57   - setFiles(cliParser.getRemainingArgs());
58   - }
59   -
60   - // Used by CompressorHttpHandler to provide a request-level
61   - // Configuration object that inherits defaults from the CLI config.
62   - public Configuration clone () {
63   - try {
64   - return (Configuration) super.clone();
65   - } catch (CloneNotSupportedException e) {
66   - return null;
67   - }
68   - }
69   -
70   - public String getInputType() {
71   - return inputType;
72   - }
73   -
74   - public void setInputType(String inputType) throws ConfigurationException {
75   - if (inputType != null) {
76   - inputType = inputType.toLowerCase();
77   - if (inputType.equals("js")) {
78   - setJavascript(true);
79   - setCss(false);
80   - } else if (inputType.equals("css")) {
81   - setCss(true);
82   - setJavascript(false);
83   - } else {
84   - throw new ConfigurationException("Bad type option.");
85   - }
86   - }
87   - this.inputType = inputType;
88   - }
89   -
90   - public boolean isJavascript() {
91   - return javascript;
92   - }
93   -
94   - public void setJavascript(boolean javascript) {
95   - this.javascript = javascript;
96   - }
97   -
98   - public boolean isCss() {
99   - return css;
100   - }
101   -
102   - public void setCss(boolean css) {
103   - this.css = css;
104   - }
105   -
106   - public boolean isVerbose() {
107   - return verbose;
108   - }
109   -
110   - public void setVerbose(boolean verbose) {
111   - this.verbose = verbose;
112   - }
113   -
114   - public boolean isMunge() {
115   - return munge;
116   - }
117   -
118   - public void setMunge(boolean munge) {
119   - this.munge = munge;
120   - }
121   -
122   - public int getLineBreak() {
123   - return lineBreak;
124   - }
125   -
126   - public void setLineBreak(int lineBreak) {
127   - this.lineBreak = lineBreak;
128   - }
129   -
130   - public void setLineBreak(String lineBreak) throws ConfigurationException {
131   - if (lineBreak == null) {
132   - setLineBreak(-1);
133   - } else {
134   - try {
135   - setLineBreak(Integer.parseInt(lineBreak, 10));
136   - } catch (NumberFormatException ex) {
137   - throw new ConfigurationException("Line break option is not a number.");
138   - }
139   - }
140   - }
141   -
142   - public boolean isPreserveSemicolons() {
143   - return preserveSemicolons;
144   - }
145   -
146   - public void setPreserveSemicolons(boolean preserveSemicolons) {
147   - this.preserveSemicolons = preserveSemicolons;
148   - }
149   -
150   - public boolean isOptimize() {
151   - return optimize;
152   - }
153   -
154   - public void setOptimize(boolean optimize) {
155   - this.optimize = optimize;
156   - }
157   -
158   - public boolean isHelp() {
159   - return help;
160   - }
161   -
162   - public void setHelp(boolean help) {
163   - this.help = help;
164   - }
165   -
166   - public String getCharset() {
167   - return charset;
168   - }
169   -
170   - public void setCharset(String charset) {
171   - if (charset == null || !Charset.isSupported(charset)) {
172   - charset = "UTF-8";
173   - // System.err.println("Using UTF-8");
174   - if (this.isVerbose()) {
175   - // TODO Log!
176   - }
177   - }
178   - this.charset = charset;
179   - }
180   -
181   - public void setServerPort(String serverPort) throws ConfigurationException {
182   - if (serverPort == null) return;
183   - try {
184   - setServerPort(Integer.parseInt(serverPort, 10));
185   - } catch (NumberFormatException ex) {
186   - throw new ConfigurationException("Server port is not a number.");
187   - }
188   - }
189   -
190   - public void setServerPort(int serverPort) {
191   - this.serverPort = serverPort;
192   - }
193   -
194   - public int getServerPort() {
195   - return serverPort;
196   - }
197   -
198   - public String getOutput() {
199   - return output;
200   - }
201   -
202   - public void setOutputRaw(String output) {
203   - this.output = output;
204   - }
205   -
206   - public void setOutput(String output) throws ConfigurationException {
207   - if (output != null) {
208   - output = output.toLowerCase();
209   - if (
210   - !( output.equals("json") || output.equals("raw") )
211   - && (getServerPort() > 0)
212   - ) {
213   - throw new ConfigurationException("In server mode, only json or raw output types are allowed.");
214   - }
215   - }
216   - setOutputRaw(output);
217   - }
218   -
219   - public List getFiles() {
220   - return files;
221   - }
222   -
223   - public void setFiles(List files) {
224   - if (files.isEmpty()) {
225   - files = new java.util.ArrayList();
226   - files.add("-"); // read from stdin
227   - }
228   - this.files = files;
229   - }
230   -
231   - public void setFiles(String[] files) {
232   - setFiles(java.util.Arrays.asList(files));
233   - }
234   -
235   -}
11 src/com/yahoo/platform/yui/compressor/ConfigurationException.java
... ... @@ -1,11 +0,0 @@
1   -package com.yahoo.platform.yui.compressor;
2   -
3   -public class ConfigurationException extends Exception {
4   - public ConfigurationException() {
5   - super();
6   - }
7   -
8   - public ConfigurationException(String message) {
9   - super(message);
10   - }
11   -}
64 src/com/yahoo/platform/yui/compressor/HttpQueryFilter.java
... ... @@ -1,64 +0,0 @@
1   -package com.yahoo.platform.yui.compressor;
2   -
3   -import com.sun.net.httpserver.Filter;
4   -import com.sun.net.httpserver.HttpExchange;
5   -
6   -import java.io.IOException;
7   -import java.io.UnsupportedEncodingException;
8   -import java.net.URI;
9   -import java.net.URLDecoder;
10   -import java.util.HashMap;
11   -import java.util.Map;
12   -import java.util.StringTokenizer;
13   -
14   -public class HttpQueryFilter extends Filter {
15   -
16   - public static final String ENCODING = "UTF-8";
17   -
18   - public String description () {
19   - return "Parses the query from a request.";
20   - }
21   -
22   - public void doFilter (HttpExchange t, Chain chain) throws IOException {
23   - try {
24   - parseGET(t);
25   - } catch (UnsupportedEncodingException ex) {
26   - // No UTF-8? Um, ok.
27   - throw new IOException(ENCODING + " is not supported.", ex);
28   - }
29   - chain.doFilter(t);
30   - }
31   -
32   - public void parseGET (HttpExchange t) throws UnsupportedEncodingException {
33   - URI request = t.getRequestURI();
34   - String rawQuery = request.getRawQuery();
35   - Map<String, String> query = parser(rawQuery);
36   - t.setAttribute("query", query);
37   - }
38   -
39   - public Map<String, String> parser (String rawQuery) throws UnsupportedEncodingException {
40   - Map<String, String> query = new HashMap<String, String>();
41   - if (rawQuery == null) return query;
42   -
43   - StringTokenizer pairs = new StringTokenizer(rawQuery, "&");
44   -
45   - while (pairs.hasMoreTokens()) {
46   - StringTokenizer pair = new StringTokenizer(pairs.nextToken(), "=");
47   -
48   - String key = null;
49   - String val = "";
50   -
51   - if (pair.hasMoreTokens()) {
52   - key = URLDecoder.decode(pair.nextToken(), ENCODING);
53   - }
54   - if (pair.hasMoreTokens()) {
55   - val = URLDecoder.decode(pair.nextToken(), ENCODING);
56   - }
57   -
58   - query.put(key, val);
59   - }
60   -
61   - return query;
62   - }
63   -
64   -}
11 src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
@@ -533,17 +533,6 @@ public JavaScriptCompressor(Reader in, ErrorReporter reporter)
533 533 this.tokens = parse(in, reporter);
534 534 }
535 535
536   - public void compress(Writer out, Configuration config) throws IOException {
537   - int linebreakpos = config.getLineBreak();
538   - boolean munge = config.isMunge();
539   - boolean preserveSemicolons = config.isPreserveSemicolons();
540   - boolean disableOptimizations = !config.isOptimize();
541   - boolean verbose = config.isVerbose();
542   -
543   - compress(out, linebreakpos, munge, verbose,
544   - preserveSemicolons, disableOptimizations);
545   - }
546   -
547 536 public void compress(Writer out, int linebreak, boolean munge, boolean verbose,
548 537 boolean preserveAllSemiColons, boolean disableOptimizations)
549 538 throws IOException {
292 src/com/yahoo/platform/yui/compressor/YUICompressor.java
... ... @@ -1,148 +1,184 @@
1 1 /*
2 2 * YUI Compressor
3 3 * Author: Julien Lecomte - http://www.julienlecomte.net/
4   - * Copyright (c) 2010 Yahoo! Inc. All rights reserved.
  4 + * Copyright (c) 2009 Yahoo! Inc. All rights reserved.
5 5 * The copyrights embodied in the content of this file are licensed
6 6 * by Yahoo! Inc. under the BSD (revised) open source license.
7 7 */
8 8
9 9 package com.yahoo.platform.yui.compressor;
10 10
11   -import com.sun.net.httpserver.HttpContext;
12   -import com.sun.net.httpserver.HttpHandler;
13   -import com.sun.net.httpserver.HttpServer;
  11 +import jargs.gnu.CmdLineParser;
14 12 import org.mozilla.javascript.ErrorReporter;
15 13 import org.mozilla.javascript.EvaluatorException;
16 14
17   -import java.io.FileInputStream;
18   -import java.io.FileOutputStream;
19   -import java.io.IOException;
20   -import java.io.InputStreamReader;
21   -import java.io.OutputStreamWriter;
22   -import java.io.Reader;
23   -import java.io.Writer;
24   -import java.net.InetSocketAddress;
25   -import java.util.List;
  15 +import java.io.*;
  16 +import java.nio.charset.Charset;
26 17
27 18 public class YUICompressor {
28 19
29 20 public static void main(String args[]) {
  21 +
  22 + CmdLineParser parser = new CmdLineParser();
  23 + CmdLineParser.Option typeOpt = parser.addStringOption("type");
  24 + CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
  25 + CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
  26 + CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
  27 + CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
  28 + CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
  29 + CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
  30 + CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
  31 + CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
  32 +
  33 + Reader in = null;
  34 + Writer out = null;
  35 +
30 36 try {
31 37
32   - Configuration config = new Configuration(args);
  38 + parser.parse(args);
33 39
34   - if (config.isHelp()) {
  40 + Boolean help = (Boolean) parser.getOptionValue(helpOpt);
  41 + if (help != null && help.booleanValue()) {
35 42 usage();
36 43 System.exit(0);
37 44 }
38 45
39   - if (config.getServerPort() > 0) {
40   - server(config);
41   - } else if (config.getFiles().isEmpty()) {
42   - throw new ConfigurationException("Filename or server option required.");
43   - } else {
44   - compress(config);
45   - }
  46 + boolean verbose = parser.getOptionValue(verboseOpt) != null;
46 47
47   - } catch (ConfigurationException e) {
48   - System.err.println("Error: " + e.getMessage());
49   - usage();
50   - System.exit(1);
51   - } catch (IOException e) {
52   - System.err.println("IO Error: " + e.getMessage());
53   - System.exit(1);
54   - }
55   - }
56   -
57   - private static void server(Configuration config) throws IOException {
58   - System.err.println("Server starting on port " + config.getServerPort() + ".");
59   - HttpHandler compressor = new CompressorHttpHandler(config);
60   - HttpServer server = HttpServer.create(new InetSocketAddress(config.getServerPort()), 0);
61   - HttpContext context = server.createContext("/compress", compressor);
62   - context.getFilters().add(0, new HttpQueryFilter());
63   - server.setExecutor(null);
64   - server.start();
65   - }
66   -
67   - private static void compress(Configuration config) {
68   - Reader in = null;
69   - Writer out = null;
  48 + String charset = (String) parser.getOptionValue(charsetOpt);
  49 + if (charset == null || !Charset.isSupported(charset)) {
  50 + // charset = System.getProperty("file.encoding");
  51 + // if (charset == null) {
  52 + // charset = "UTF-8";
  53 + // }
70 54
71   - String charset = config.getCharset();
  55 + // UTF-8 seems to be a better choice than what the system is reporting
  56 + charset = "UTF-8";
72 57
73   - int linebreakpos = config.getLineBreak();
74 58
75   - String type = config.getInputType();
  59 + if (verbose) {
  60 + System.err.println("\n[INFO] Using charset " + charset);
  61 + }
  62 + }
76 63
77   - List files = config.getFiles();
  64 + int linebreakpos = -1;
  65 + String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
  66 + if (linebreakstr != null) {
  67 + try {
  68 + linebreakpos = Integer.parseInt(linebreakstr, 10);
  69 + } catch (NumberFormatException e) {
  70 + usage();
  71 + System.exit(1);
  72 + }
  73 + }
78 74
79   - String output = config.getOutput();
80   - String pattern[] = output != null ? output.split(":") : new String[0];
  75 + String type = (String) parser.getOptionValue(typeOpt);
  76 + if (type != null && !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
  77 + usage();
  78 + System.exit(1);
  79 + }
81 80
82   - java.util.Iterator filenames = files.iterator();
  81 + String[] fileArgs = parser.getRemainingArgs();
  82 + java.util.List files = java.util.Arrays.asList(fileArgs);
  83 + if (files.isEmpty()) {
  84 + files = new java.util.ArrayList();
  85 + files.add("-"); // read from stdin
  86 + }
83 87
84   - while(filenames.hasNext()) {
  88 + String output = (String) parser.getOptionValue(outputFilenameOpt);
  89 + String pattern[] = output != null ? output.split(":") : new String[0];
85 90
86   - String inputFilename = (String)filenames.next();
  91 + java.util.Iterator filenames = files.iterator();
  92 + while(filenames.hasNext()) {
  93 + String inputFilename = (String)filenames.next();
87 94
88   - try {
89   - if (inputFilename.equals("-")) {
  95 + try {
  96 + if (inputFilename.equals("-")) {
90 97
91   - in = new InputStreamReader(System.in, charset);
  98 + in = new InputStreamReader(System.in, charset);
92 99
93   - } else {
  100 + } else {
94 101
95   - if (type == null) {
96   - int idx = inputFilename.lastIndexOf('.');
97   - if (idx >= 0 && idx < inputFilename.length() - 1) {
98   - try {
99   - config.setInputType(inputFilename.substring(idx + 1));
100   - } catch (ConfigurationException e) {
101   - usage();
102   - System.exit(1);
  102 + if (type == null) {
  103 + int idx = inputFilename.lastIndexOf('.');
  104 + if (idx >= 0 && idx < inputFilename.length() - 1) {
  105 + type = inputFilename.substring(idx + 1);
103 106 }
104 107 }
  108 +
  109 + if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
  110 + usage();
  111 + System.exit(1);
  112 + }
  113 +
  114 + in = new InputStreamReader(new FileInputStream(inputFilename), charset);
105 115 }
106 116
107   - in = new InputStreamReader(new FileInputStream(inputFilename), charset);
108   - }
  117 + String outputFilename = output;
  118 + // if a substitution pattern was passed in
  119 + if (pattern.length > 1 && files.size() > 1) {
  120 + outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
  121 + }
109 122
110   - String outputFilename = output;
111   - // if a substitution pattern was passed in
112   - if (pattern.length > 1 && files.size() > 1) {
113   - outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
114   - }
  123 + if (type.equalsIgnoreCase("js")) {
115 124
116   - if (config.isJavascript()) {
  125 + try {
117 126
118   - try {
  127 + JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
119 128
120   - JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
  129 + public void warning(String message, String sourceName,
  130 + int line, String lineSource, int lineOffset) {
  131 + if (line < 0) {
  132 + System.err.println("\n[WARNING] " + message);
  133 + } else {
  134 + System.err.println("\n[WARNING] " + line + ':' + lineOffset + ':' + message);
  135 + }
  136 + }
121 137
122   - public void warning(String message, String sourceName,
123   - int line, String lineSource, int lineOffset) {
124   - if (line < 0) {
125   - System.err.println("\n[WARNING] " + message);
126   - } else {
127   - System.err.println("\n[WARNING] " + line + ':' + lineOffset + ':' + message);
  138 + public void error(String message, String sourceName,
  139 + int line, String lineSource, int lineOffset) {
  140 + if (line < 0) {
  141 + System.err.println("\n[ERROR] " + message);
  142 + } else {
  143 + System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
  144 + }
128 145 }
129   - }
130 146
131   - public void error(String message, String sourceName,
132   - int line, String lineSource, int lineOffset) {
133   - if (line < 0) {
134   - System.err.println("\n[ERROR] " + message);
135   - } else {
136   - System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
  147 + public EvaluatorException runtimeError(String message, String sourceName,
  148 + int line, String lineSource, int lineOffset) {
  149 + error(message, sourceName, line, lineSource, lineOffset);
  150 + return new EvaluatorException(message);
137 151 }
138   - }
  152 + });
139 153
140   - public EvaluatorException runtimeError(String message, String sourceName,
141   - int line, String lineSource, int lineOffset) {
142   - error(message, sourceName, line, lineSource, lineOffset);
143   - return new EvaluatorException(message);
  154 + // Close the input stream first, and then open the output stream,
  155 + // in case the output file should override the input file.
  156 + in.close(); in = null;
  157 +
  158 + if (outputFilename == null) {
  159 + out = new OutputStreamWriter(System.out, charset);
  160 + } else {
  161 + out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
144 162 }
145   - });
  163 +
  164 + boolean munge = parser.getOptionValue(nomungeOpt) == null;
  165 + boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
  166 + boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
  167 +
  168 + compressor.compress(out, linebreakpos, munge, verbose,
  169 + preserveAllSemiColons, disableOptimizations);
  170 +
  171 + } catch (EvaluatorException e) {
  172 +
  173 + e.printStackTrace();
  174 + // Return a special error code used specifically by the web front-end.
  175 + System.exit(2);
  176 +
  177 + }
  178 +
  179 + } else if (type.equalsIgnoreCase("css")) {
  180 +
  181 + CssCompressor compressor = new CssCompressor(in);
146 182
147 183 // Close the input stream first, and then open the output stream,
148 184 // in case the output file should override the input file.
@@ -154,60 +190,37 @@ public EvaluatorException runtimeError(String message, String sourceName,
154 190 out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
155 191 }
156 192
157   - boolean munge = !config.isMunge();
158   - boolean preserveSemicolons = config.isPreserveSemicolons();
159   - boolean disableOptimizations = config.isOptimize();
160   - boolean verbose = config.isVerbose();
161   - compressor.compress(out, linebreakpos, munge, verbose,
162   - preserveSemicolons, disableOptimizations);
163   -
164   - } catch (EvaluatorException e) {
165   -
166   - e.printStackTrace();
167   - // Return a special error code used specifically by the web front-end.
168   - System.exit(2);
169   -
  193 + compressor.compress(out, linebreakpos);
170 194 }
171 195
172   - } else if (config.isCss()) {
173   -
174   - CssCompressor compressor = new CssCompressor(in);
175   -
176   - // Close the input stream first, and then open the output stream,
177   - // in case the output file should override the input file.
178   - in.close(); in = null;
179   -
180   - if (outputFilename == null) {
181   - out = new OutputStreamWriter(System.out, charset);
182   - } else {
183   - out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
184   - }
  196 + } catch (IOException e) {
185 197
186   - compressor.compress(out, linebreakpos);
187   - }
188   - } catch (IOException e) {
  198 + e.printStackTrace();
  199 + System.exit(1);
189 200
190   - e.printStackTrace();
191   - System.exit(1);
  201 + } finally {
192 202
193   - } finally {
194   -
195   - if (in != null) {
196   - try {
197   - in.close();
198   - } catch (IOException e) {
199   - e.printStackTrace();
  203 + if (in != null) {
  204 + try {
  205 + in.close();
  206 + } catch (IOException e) {
  207 + e.printStackTrace();
  208 + }
200 209 }
201   - }
202 210
203   - if (out != null) {
204   - try {
205   - out.close();
206   - } catch (IOException e) {
207   - e.printStackTrace();
  211 + if (out != null) {
  212 + try {
  213 + out.close();
  214 + } catch (IOException e) {
  215 + e.printStackTrace();
  216 + }
208 217 }
209 218 }
210 219 }
  220 + } catch (CmdLineParser.OptionException e) {
  221 +
  222 + usage();
  223 + System.exit(1);
211 224 }
212 225 }
213 226
@@ -220,7 +233,6 @@ private static void usage() {
220 233 + " --type <js|css> Specifies the type of the input file\n"
221 234 + " --charset <charset> Read the input file using <charset>\n"
222 235 + " --line-break <column> Insert a line break after the specified column number\n"
223   - + " --server <port> Start a server on <port>.\n"
224 236 + " -v, --verbose Display informational messages and warnings\n"
225 237 + " -o <file> Place the output into <file>. Defaults to stdout.\n"
226 238 + " Multiple files can be processed using the following syntax:\n"

0 comments on commit d36d447

Please sign in to comment.
Something went wrong with that request. Please try again.