Java tutorial
/** * Copyright (c) 2014 Marta Nabozny, Maciej Nabozny * * This file is part of OverCluster project. * * OverCluster 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/>. */ package JavaCloud; import com.google.api.client.http.*; import org.json.simple.*; import com.google.api.client.http.javanet.NetHttpTransport; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.MessageDigest; public class Utils { public static Object request(String address, String function, final JSONObject params) throws CoreException { try { GenericUrl url = new GenericUrl(address + "/" + function); NetHttpTransport transport = new NetHttpTransport(); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new HttpContent() { @Override public long getLength() throws IOException { return params.toString().length(); } @Override public String getType() { return "text/json"; } @Override public boolean retrySupported() { return false; } @Override public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(params.toString().getBytes()); } }); HttpResponse response = request.execute(); JSONParser parser = new JSONParser(); JSONObject object = (JSONObject) parser.parse(response.parseAsString()); if (!object.get("status").equals("ok")) { throw new CoreException(object.get("status").toString()); } if (object.containsKey("data") && object.get("data") != null) return parser.parse(object.get("data").toString()); else return null; } catch (ParseException e) { System.out.println("Error parsing response: " + e.toString()); throw new CoreException("json_malformed"); } catch (IOException e) { System.out.println("Error connecting to server: " + e.toString()); throw new CoreException("connection_failed"); } } public static String calcHash(String password, String seed) { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); String tuple = password + seed; crypt.update(tuple.getBytes("UTF-8")); return new BigInteger(1, crypt.digest()).toString(16); } catch (Exception e) { return null; } } }