summaryrefslogtreecommitdiff
path: root/blaconvert.java
blob: 9fcb26bdd2b225d80431e1a58ee401814c9219fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
    blaconvert - Java program for converting units of measurement and currency using Google APIs
    by blatech
        
    Copyright 2011 Joe Robinson <joe@lc8n.com>
    based on code by Jamie Walters <jagw@jagw.co.uk>
    based on code by  Joe Robinson <joe@lc8n.com>
    
    Version 1.42
    This code is now a terrible mess of hacks on top of hacks. I'm sorry.
    
    CHANGELOG
    1.0 - First version
    1.1 - Allow units with more than one word eg "light year"
        - Added "same unit" error
        - Ensure standard imperial measurements are used for some units - google defaults to US
    1.2 - Replace crazy non unicode spaces with commas
    1.21 - Added quart to imperial measurements
    1.3 - Added support for currency symbols
    1.31 - Trying to add euro (probably won't work)
    1.32 - Changed currency to unicode
    1.33 - More euro fixing (maybe)
    1.34 - Fixed output of negative numbers
    1.4 - Added bitcoin conversion
    1.41 - Allowed "bitcoin"(s) in translation string as well as BTC
    1.42 - Added litecoin conversion
    TODO
    - Raw output option - result only with no spaces/commas/units

    TESTING
*/


import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class blaconvert {

	public static void main(String[] args) throws IOException
	{
        String sourceUnit = "";
        String targetUnit = "";
        String amount = "";
	String version = "1.42";
	
		/* Build query from query or arguments, depending on whether
		   arguments were given. */
		if (args.length == 0) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String[] split = br.readLine().split(" ");
			int start = 0;
			int to = 0;
			int output = 0;
			if (split[0].startsWith("-"))
			{
				if (split[0].equals("-v") || split[0].equals("--version"))
				{
					System.out.println("v"+version);
					System.exit(0);
				} else if (split[0].charAt(1) == 'r')
				{
					//reserved for raw output option
					output = 1;
					start = 1;
				}
			}
			
			for(int i = 0; i < split.length; i++)
			{
				if (split[i].toLowerCase().equals("to") || split[i].toLowerCase().equals("in"))
				{
					to = i;
				}
			}
			amount = split[start];
			
			for (int i = start+1; i < to-1; i++)
			{
				sourceUnit += split[i]+"%20";
			}
            sourceUnit += split[to-1];
			for (int i = to+1; i < split.length-1; i++)
			{
				targetUnit += split[i]+"%20";
			}
            targetUnit += split[split.length-1];
			} catch (Exception e) {
				System.err.println("Error:" + e.getMessage());
				System.exit(1);
			}
		} else {
			
			if (args[0].equals("-v") || args[0].equals("--version"))
			{
				System.out.println("v"+version);
				System.exit(0);
			}
			amount = args[0];
			sourceUnit = args[1];
			targetUnit = args[2];
		}
		
		String[] imperial = {"pint", "gallon", "gal", "cup", "teaspoon", "tablespoon", "fl oz", "fluid ounce", "quart"};
		
		for(int i = 0; i < imperial.length; i++)
		{
			if (sourceUnit.startsWith(imperial[i]))
			{
				sourceUnit = "Imperial%20"+sourceUnit;
			}
			
			if (targetUnit.startsWith(imperial[i]))
			{
				targetUnit = "Imperial%20"+targetUnit;
			}
		}
        boolean currency = false;
		if(amount.contains("\u00A3") || amount.contains("\u0024") || amount.contains("\u20AC") || 
            amount.contains("\u00A5") || amount.contains("\u0080"))
        {
            amount.replaceAll("\u00A3","%A3");
            amount.replaceAll("\u0024","%24");
            amount.replaceAll("\u20AC","%80");
            amount.replaceAll("\u0080","%80");
            amount.replaceAll("\u00A5","%A5");
            
            currency = true;
        }
        String response = "";
        BufferedReader br;
        double dresult = 0.0;
        URL url;
        URLConnection urlc;
        //Bitcoin conversion
        if (sourceUnit.trim().toUpperCase().equals("BTC") || sourceUnit.trim().toUpperCase().contains("BITCOIN")
          || sourceUnit.trim().toUpperCase().equals("LTC") || sourceUnit.trim().toUpperCase().contains("LITECOIN")) {
            if (targetUnit.trim().toUpperCase().equals("LTC") || targetUnit.trim().toUpperCase().contains("LITECOIN")) {
                dresult = Double.parseDouble(amount);
                url = new URL("http://www.lc8n.com/upload/ltc");
          	    urlc = url.openConnection();
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                String ltcresponse = br.readLine();
                double value = Double.parseDouble(ltcresponse);
                dresult = (dresult*(1/value));
            
            } else {
            url = new URL("https://blockchain.info/tobtc?currency="+targetUnit.toUpperCase()+"&value=1");
            try {
    		    urlc = url.openConnection();
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                response = br.readLine();
                dresult = Double.parseDouble(response);
                double value = Double.parseDouble(amount);
                dresult = ((1/dresult)*value);
            } catch (Exception e) {
                if(e.toString().contains("500")) {
                    System.out.println("500 Error: Probably unknown currency");
                } else if (e.toString().contains("404")) {
                    System.out.println("404 Error: Bitcoin converter unavailable");
                }
                System.exit(1);
            }
            
            if (sourceUnit.trim().toUpperCase().equals("LTC") || sourceUnit.trim().toUpperCase().contains("LITECOIN")) {
                url = new URL("http://www.lc8n.com/upload/ltc");
          	    urlc = url.openConnection();
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                String ltcresponse = br.readLine();
                double value = Double.parseDouble(ltcresponse);
                dresult = (dresult*value);

            }
            }
            response = String.format("%.6f", dresult);
            System.out.println(amount+" "+sourceUnit+" = "+response+" "+targetUnit);
            System.exit(0);


        } else if (targetUnit.trim().toUpperCase().equals("BTC") || targetUnit.trim().toUpperCase().contains("BITCOINS")
          || targetUnit.trim().toUpperCase().equals("LTC") || targetUnit.trim().toUpperCase().contains("LITECOIN")) {
            if (sourceUnit.trim().toUpperCase().equals("LTC") || sourceUnit.trim().toUpperCase().contains("LITECOIN")) {            
                url = new URL("http://www.lc8n.com/upload/ltc");
          	    urlc = url.openConnection();
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                String ltcresponse = br.readLine();
                double value = Double.parseDouble(ltcresponse);
                dresult = (dresult*value);
            } else {
            url = new URL("https://blockchain.info/tobtc?currency="+sourceUnit.toUpperCase()+"&value="+amount);
    		urlc = url.openConnection();
            try {
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                response = br.readLine();
                dresult = Double.parseDouble(response);
            } catch (Exception e) {
                if(e.toString().contains("500")) {
                    System.out.println("500 Error: Probably unknown currency");
                } else if (e.toString().contains("404")) {
                    System.out.println("404 Error: Bitcoin converter unavailable");
                }
                System.exit(1);
            }
            if (targetUnit.trim().toUpperCase().equals("LTC") || targetUnit.trim().toUpperCase().contains("LITECOIN")) {
                url = new URL("http://www.lc8n.com/upload/ltc");
          	    urlc = url.openConnection();
	    	    br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                String ltcresponse = br.readLine();
                double value = Double.parseDouble(ltcresponse);
                dresult = (dresult*(1/value));

            }
            }
            response = String.format("%.6f", dresult);
            System.out.println(amount+" "+sourceUnit+" = "+response+" "+targetUnit);
            System.exit(0);
        }

		//URL which provides XML response
		url = new URL("http://www.google.com/ig/calculator?hl=en&q="+amount+sourceUnit+"=?"+targetUnit);
		//System.out.println("http://www.google.com/ig/calculator?hl=en&q="+amount+sourceUnit+"=?"+targetUnit);
		urlc = url.openConnection();

		br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
		String line;
		String[] lines;
		String tempString = "";
		String lhs = "";
		String rhs = "";
		String error = "";
		//Read every line
		while ((line = br.readLine()) != null)
		{
			// Splits the google output by the commas
			lines = line.split(",");
			
			for(int i=0; i<lines.length; i++){
				//System.out.println(lines[i]);
				// Get the useful information (the urls!)
				if(lines[i].trim().startsWith("{lhs")){
					tempString = lines[i];
					// Blat the non-url information
					lhs = tempString.substring(7, tempString.length()-1);
				}
               			else if(lines[i].trim().startsWith("rhs")){
					tempString = lines[i];
					// Blat the non-url information
					rhs = tempString.substring(6, tempString.length()-1);
				}
				else if(lines[i].trim().startsWith("error")){
					tempString = lines[i];
					// Blat the non-url information
					error = tempString.substring(8, tempString.length()-1);
				}

			}

		}
		
		String[] parts = rhs.split(" ");
		String result = fixCrazySpaces(parts[0]) + " ";
		//Convert weird output into something that makes sense
		for (int i = 1; i < parts.length; i++)
		{
			//System.out.println(parts[i]);
			if (parts[i].equals("\\x26#215;"))
			{
				parts[i] = "*";
			} else if (parts[i].startsWith("10\\"))
			{
				String[] exp = parts[i].split("\\\\");
				parts[i] = "10^"+exp[2].substring(3, exp[2].length());
			}
			
			result += parts[i] + " ";
		}
		
		parts = lhs.split(" ");
		lhs = "";
        if(!currency) {
            parts[0] = fixCrazySpaces(parts[0]);
        } else {
            parts[1] = fixCrazySpaces(parts[1]);
        }
		for (int i = 0; i < parts.length; i ++)
		{
			lhs += parts[i]+" ";
		}
		


		// Print results
		if(error.isEmpty()) {	
			System.out.println(lhs+"= "+result);

			System.exit(0);
			
		} else {
			if(error.equals("4"))
			{
				error = "Unknown unit";
			} else if (error.equals("0"))
			{
				error = "Both units are the same";
			}
			System.out.print("Error: "+error);
			System.out.println("\n");
			System.exit(1);
		}

	}
	
	private static String fixCrazySpaces(String string)
	{
		char[] chars = string.toCharArray();
		String fixed = "";
		for (int i = 0; i < chars.length; i++)
		{
			if (Character.getNumericValue(chars[i]) < 0 && chars[i] != '.' && chars[i] != '-')
			{
				fixed += ",";
			} else {
				fixed += chars[i];
			}
		}
		
		return fixed;
	}
	

}