id
stringlengths
36
36
text
stringlengths
1
1.25M
a4090076-63ad-4df4-b917-bcd15c1968af
public ShortUrl() { }
a61a1d10-68d7-44fd-b3a3-9a9e9778c00e
public ShortUrl(String originalURL, String shortURL) { this.originalURL = originalURL; this.shortURL = shortURL; }
365f99c7-28af-444a-88e7-b7946c09dc4e
@JsonProperty public String getOriginalURL() { return originalURL; }
71639d9d-0555-459e-86f8-623cc3614458
@JsonProperty public String getShortURL() { return shortURL; }
bf7d02cf-47f9-4a0e-9353-e7599975a889
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShortUrl shortUrl = (ShortUrl) o; if (!originalURL.equals(shortUrl.originalURL)) return false; if (!shortURL.equals(shortUrl.shortURL)) return false; return true; }
da662d14-ff06-4270-bee4-0ce0cd6fad29
@Override public int hashCode() { int result = originalURL.hashCode(); result = 31 * result + shortURL.hashCode(); return result; }
acc17b6d-ea77-45d1-b7d1-856b1db9f05a
public GetHealthCheck(String checkURL) { this.checkString = checkURL; }
c8bc6eee-54d3-4eaa-9378-a80f2f57d542
@Override protected Result check() throws Exception { return Result.healthy(); }
8b7b95e8-2f64-4674-92d1-57564d2b2a44
public static void init(UrlShortenerConfiguration configuration){ String access_key_id = configuration.getAwsAccessKeyId(); String secret_access_key = configuration.getSecretAccessKey(); BasicAWSCredentials awsCreds = new BasicAWSCredentials(access_key_id, secret_access_key); tableName = configuration.getAwsTableName(); dynamoDB = new AmazonDynamoDBClient(awsCreds); dynamoDB.setRegion(Region.getRegion(Regions.fromName(configuration.getAwsRegion()))); }
e66b380d-1447-4952-841b-1bda91666760
public static void putNewEncodedURL(String shortURL, String originalURL){ // Add an item Map<String, AttributeValue> item = newItem(shortURL,originalURL); PutItemRequest putItemRequest = new PutItemRequest(tableName, item); PutItemResult putItemResult = dynamoDB.putItem(putItemRequest); System.out.println("Result: " + putItemResult); }
01f656c7-7121-453a-83fc-cc3b8e968a4c
public static Map<String, AttributeValue> getOriginalURL(String shorturl){ Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put("shorturl", new AttributeValue(shorturl)); GetItemRequest getItemRequest = new GetItemRequest() .withTableName(tableName) .withKey(key) .withAttributesToGet(Arrays.asList("originalurl")); GetItemResult result = dynamoDB.getItem(getItemRequest); // Check the response. System.out.println("Printing item after retrieving it...."); printItem(result.getItem()); return result.getItem(); }
c1182618-6d6d-4168-97b6-f9c2407666e4
private static Map<String, AttributeValue> newItem(String shorturl, String originalurl) { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put("shorturl", new AttributeValue(shorturl)); item.put("originalurl", new AttributeValue(originalurl)); return item; }
91f2ba59-0682-4ebf-87b0-44984fc6421f
private static void printItem(Map<String, AttributeValue> attributeList) { if(attributeList!=null) { for (Map.Entry<String, AttributeValue> item : attributeList.entrySet()) { String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.println(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); } } }
e2a88452-17cc-470b-a7d6-6e26ffb66a51
public static String encodeURL(String URL) { String encodedURL =""; try { byte[] bytesOfMessage = URL.getBytes("UTF-8"); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] digestedBytes = messageDigest.digest(bytesOfMessage); byte[] MD5LowerBytes = getLowerBytes(digestedBytes); byte[] encoded = Base64.encodeBase64(MD5LowerBytes); encodedURL = new String(encoded,"UTF-8"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodedURL; }
0dc2592b-e5ae-4c5e-bf6a-63f069cd8b2f
private static byte[] getLowerBytes(byte[] digest){ byte[] fetchedBytes = new byte[4]; int j=0; for(int i=digest.length-5;i<digest.length-1;i++){ fetchedBytes[j]= digest[i]; j++; } return fetchedBytes; }
8be85f10-eed2-4c23-a3ef-e6608cd6573d
public UrlShortenerResource(Map<String, String> storedValuesTest) { this.cachedKeys = storedValuesTest; this.amazonDBEnabled = false; this.baseURL = "http://localhost:8080/UrlShortener"; }
8c63f775-f917-4e36-80e7-37704ca2aa43
public UrlShortenerResource(UrlShortenerConfiguration urlShortenerConfiguration) { this.baseURL = urlShortenerConfiguration.getBaseURL(); if (urlShortenerConfiguration.getEnableAmazonDB().equals("true")) { this.amazonDBEnabled = true; AmazonDBDAOStore.init(urlShortenerConfiguration); } else { this.cachedKeys = new ConcurrentHashMap<String, String>(); this.amazonDBEnabled = false; } }
78757d2d-ed11-40d0-b557-89e5b37fc0b6
@GET @Path("/{shortUrl}") @Timed public Response fetchOriginalURL(@PathParam("shortUrl") String shortUrl) { try { if (amazonDBEnabled) { Map<String, AttributeValue> result = AmazonDBDAOStore.getOriginalURL(shortUrl); if (result != null) { String originalUrl = result.get("originalurl").getS(); URI location = new URI(originalUrl); return Response.temporaryRedirect(location).build(); } else { return Response.status(404).build(); } } else { if (cachedKeys.containsKey(shortUrl)) { URI location = new URI(cachedKeys.get(shortUrl)); return Response.temporaryRedirect(location).build(); } else { return Response.status(404).build(); } } } catch (URISyntaxException e) { e.printStackTrace(); return Response.serverError().build(); } }
848b7cd7-6d20-4489-b84c-3167e441ce67
@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Url createNewShortURL(Url url) { String originalUrl = url.getUrl(); String shortUrl = UrlShortenerUtil.encodeURL(originalUrl); storeNewEntry(shortUrl, originalUrl); return new Url(baseURL+"/"+shortUrl); }
2319e17b-73cf-4a99-9d36-b4c65a3fbd42
private void storeNewEntry(String shortUrl, String url) { //check my if exists if (amazonDBEnabled) { Map<String, AttributeValue> result = AmazonDBDAOStore.getOriginalURL(shortUrl); if (result == null) { AmazonDBDAOStore.putNewEncodedURL(shortUrl, url); } } else { if (!cachedKeys.containsKey(shortUrl)) { cachedKeys.put(shortUrl, url); } } }
46b9081e-e03e-455d-9e65-3370bc526055
@Test public void serializeToJSON() throws Exception{ final ShortUrl shortUrl = new ShortUrl("http://www.google.com","http://hostname/hashURL"); assertThat(MAPPER.writeValueAsString(shortUrl)).isEqualTo(fixture("fixtures/shortUrl.json")); }
94bea78c-386e-48ce-b61f-4e0fe42f281a
@Test public void deserializeFromJSON() throws Exception{ final ShortUrl shortUrl = new ShortUrl("http://www.google.com","http://hostname/hashURL"); assertThat(MAPPER.readValue(fixture("fixtures/shortUrl.json"), ShortUrl.class)); }
4f296086-837d-46d8-8033-3ce248b051a6
@Test public void sameShortURLEqualsFields() throws Exception{ final ShortUrl shortUrl1 = new ShortUrl("http://www.google.com","http://hostname/hashURL"); final ShortUrl shortUrl2 = new ShortUrl("http://www.google.com","http://hostname/hashURL"); assertThat(shortUrl1).isEqualsToByComparingFields(shortUrl2); }
de6a98cf-d7ac-411d-b6f1-4f1d2c55a3ce
@Test public void sameShortURLObjects() throws Exception{ final ShortUrl shortUrl1 = new ShortUrl("http://www.google.com","http://hostname/hashURL"); final ShortUrl shortUrl2 = new ShortUrl("http://www.google.com","http://hostname/hashURL"); assertEquals(shortUrl1,shortUrl2); }
8927ade5-2a7c-4ad8-a150-71343dc90adc
@Test public void serializeToJSON() throws Exception{ final Url url = new Url("http://www.google.com"); assertThat(MAPPER.writeValueAsString(url)).isEqualTo(fixture("fixtures/url.json")); }
de3b1d7e-8a1c-4540-9ae9-b61739bf8312
@Test public void deserializeFromJSON() throws Exception{ final Url url = new Url("http://www.google.com"); assertThat(MAPPER.readValue(fixture("fixtures/url.json"), Url.class)); }
74d6e6ef-4809-477f-9a9f-24778d6d70c6
@Test public void encodingURLGivesShortURL(){ String shortUrl = UrlShortenerUtil.encodeURL("http://dice.se/"); assertEquals("0Cx8xg==",shortUrl); }
ca67a049-8a45-4eb1-bbf0-041af7521b2d
@Test public void twoDifferentURLsGiveDifferentResult(){ String shortUrl = UrlShortenerUtil.encodeURL("http://dice.se/"); String otherShortUrl = UrlShortenerUtil.encodeURL("http://www.google.com"); assertNotEquals(shortUrl,otherShortUrl); }
a86e9801-5fa4-4207-9ef6-67421870c3c8
@Before public void setup(){ testURLs.put(shortUrl.getShortURL(),shortUrl.getOriginalURL()); testURLs.put(otherShortUrl.getShortURL(),otherShortUrl.getOriginalURL()); }
27422bf6-416f-4be2-bff9-8288dfbf9b1d
@Test public void testGetOriginalURL(){ ClientResponse response = resources.client().resource("/UrlShortener/0Cx8xg==").get(ClientResponse.class); assertEquals(response.getStatus(),307); assertEquals(response.getLocation().toString(),"http://dice.se/"); }
23638e29-6ed6-48df-a354-9dd07e0cb1d6
@Test public void testGetFailsWithUnprocessedURL(){ ClientResponse response = resources.client().resource("/UrlShortener/thisTestFails").get(ClientResponse.class); assertEquals(response.getStatus(),404); }
aadc4f56-8bc7-4fba-aab9-79da42d6456c
@Test public void testPutOriginalURL(){ Url url = new Url("http://www.elotrolado.net/"); Url newUrl = resources.client().resource("/UrlShortener").type(MediaType.APPLICATION_JSON_TYPE).put(Url.class, url); assertEquals(newUrl.getUrl(),"http://localhost:8080/UrlShortener/zBByyw=="); }
76f35e35-3a3b-4825-bdc5-f51bd94c7e6f
public static void main(String[]args) throws Exception{ // The simple Jetty config here will serve static content from the webapp directory String webappDirLocation = "src/main/webapp/"; // Look for that variable and default to 8080 if it isn't there. String webPort = "5000"; Server server = new Server(Integer.valueOf(webPort)); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setDescriptor(webappDirLocation + "/WEB-INF/web.xml"); webapp.setResourceBase(webappDirLocation); server.setHandler(webapp); server.start(); server.join(); }
1e61405c-fe5a-4f91-bd58-c6887603eb87
@BeforeClass public static void setup() { assertFalse("Remember to set your slicify user/password before running the test", username.equals("slicify-user")); //get the web services wrapper & set username/password node = new SlicifyNode(); node.setUsername(username); node.setPassword(password); }
2513e5fa-99d9-4e71-bf03-a0d5dbebd9ab
@Test public void runAll() throws Exception { addBid(); getBooking(); getStatus(); getPassword(); //sshTest(); }
559f521f-c29f-4951-b2ae-8428c3607348
private void addBid() throws Exception { // Create a new bid to book a machine - you can change the values here to specify the particular criteria you want String country = ""; //can specific a particular location if required int minRam = 1; //include machines with any amount of RAM double maxPrice = 0.03; //only pay up to $0.03 per hour. If a machine is too expensive, the booking will be cancelled. int bits = 64; //64-bit machines only int ecu = 5; //minimum benchmark bidID = node.addBid(minRam, maxPrice, bits, ecu, country); // Check result if(bidID < 0) fail("Error thrown from booking call"); System.out.println("BidID:" + bidID); }
17c0d27b-cda2-4bb0-897b-e9c3f7848562
private void getBooking() throws Exception { //check if our bid was successful bookingID = node.getBookingID(bidID); //check result if(bookingID == -2) fail("getBookingID returned an error"); else if(bookingID == -1) fail("No machines available - try increasing the price, or decreasing the requirements"); System.out.println("BookingID:" + bookingID); }
62c7630b-a1e7-48b9-9ddd-8c671d86ea6d
private void getStatus() throws Exception { if(bookingID > 0) { //Wait until Node is ready String status = "Unknown"; while(!status.equals("Ready")) { //check it hasnt faulted assertFalse("Machine wasnt able to be booked succesfully", status.equals("Closed")); //check the status every 10 seconds Thread.sleep(10000); status = node.getBookingStatus(bookingID); System.out.println("Status:" + status); } } }
974218a5-3890-431f-8a52-1ecfc0f53f82
private void getPassword() throws Exception { bookingOTP = node.getBookingPassword(bookingID); assertNotNull("Null booking password", bookingOTP); assertFalse("Empty booking password", bookingOTP.length() < 1); System.out.println("Booking OTP:" + bookingOTP); }
533a1656-4b34-4c27-acfd-ffffbf865071
private void sshTest() throws IOException { //Send some commands via the SSH command session NodeSSHClient sshClient = new NodeSSHClient(); sshClient.connect(username, bookingOTP); String pwdResult = sshClient.send("pwd", true); assertTrue(pwdResult.contains("/home/slicify")); String llResult = sshClient.send("ls -l", true); assertTrue(llResult.contains("total 0")); String wgetResult = sshClient.send("tsocks wget www.google.com", true); assertTrue(wgetResult.contains("`index.html' saved")); String catResult = sshClient.send("cat index.html", true); assertTrue(catResult.contains("</html>")); sshClient.disconnect(); }
ef9b0c57-0c56-4447-9dc3-36fc39463a7e
@AfterClass public static void cancelBooking() { if(node != null && bidID > 0) { // Cancel booking again try { node.deleteBid(bidID); System.out.println("Bid cancelled, booking terminating automatically"); if(bookingID > 0) assertEquals("Booking not closed", "Closed", node.getBookingStatus(bookingID)); } catch (Exception e) { fail("Booking may not be cancelled - check from www.slicify.com web site, and cancel manually if needed"); } } }
3026ce9f-eb32-41a4-a3c3-1d5a63877801
@BeforeClass public static void setup() throws Exception { assertFalse("Remember to set your mediafire login details before running the test", username.equals("mediafire-user")); testData = "Hello World\n A timestamp:" + System.currentTimeMillis() + "\n"; mediaClient = new MediaFireClient(username, password, appid, appkey); }
62cf9c5a-0521-4a2f-8349-0c9d1f38320f
@Test public void MFUpload() throws Exception { //get filename/key map Map<String, String> fileKeys = mediaClient.listFiles(); System.out.println(fileKeys.toString()); if(fileKeys.containsKey(tempFilename)) { //delete the existing temp file String quickKey = fileKeys.get(tempFilename); mediaClient.delete(quickKey); } //upload some test data mediaClient.upload(tempFilename, testData.getBytes()); }
a49e5e65-ce1a-4862-9598-c3db704cefc9
@Test public void MFDownload() throws Exception { //refresh filename/key map - usually the file doesnt appear immediately, and you have to query a few times String quickKey = null; while(quickKey == null) { quickKey = mediaClient.getQuickKey(tempFilename); if(quickKey == null) Thread.sleep(1000); //throttle queries } System.out.println("QuickKey:" + quickKey); //download data again String contents = mediaClient.downloadText(quickKey); //verify contents assertEquals("test data downloaded didnt match original", testData, contents); }
79256b09-c36b-47bd-866b-d753b84fa9be
public MediaFireClient(String mediaFireUsername, String mediaFirePassword, String appId, String appKey) throws Exception { Username = mediaFireUsername; Password = mediaFirePassword; AppID = appId; AppKey = appKey; connect(); }
e87308f5-f8ae-46f0-9627-902f534cd9f8
public void connect() throws Exception { //mediafire requires an SHA1 of your user/password/appid/appkey for authentication String shasig = sha1String(Username + Password + AppID + AppKey); String targetURL = HTTPS_MEDIAFIRE_BASE_API + "user/get_session_token.php" + "?email=" + Username + "&password=" + Password + "&application_id=" + AppID + "&signature=" + shasig + "&version=1"; //send get request, and parse session_token Document XMLDoc = httpGet(targetURL); NodeList tags = XMLDoc.getElementsByTagName("session_token"); if(tags.getLength() != 1) throw new Exception("Missing/multiple session_tokens:" + tags.getLength()); SessionToken = tags.item(0).getTextContent(); }
942516bf-15ef-4544-8072-a61dbfb9dbe0
public String getQuickKey(String filename) throws Exception { Map<String, String> fileKeys = listFiles(); return fileKeys.get(filename); }
972d1fcb-e525-40ba-b99c-2bd71f057821
public String downloadText(String quickKey) throws Exception { String ddLink = getDownloadLink(quickKey); URL website = new URL(ddLink); InputStream webStream = website.openStream(); return convertStreamToString(webStream); }
c05383f8-94f3-4e71-b6b6-77699951aa6d
public InputStream downloadBLOB(String quickKey) throws Exception { String ddLink = getDownloadLink(quickKey); URL website = new URL(ddLink); InputStream webStream = website.openStream(); return webStream; }
9826dcf9-d770-4ee7-9a7d-6c2e4921405d
public String getDownloadLink(String quickKey) throws Exception { String targetURL = HTTP_MEDIAFIRE_BASE_API + "file/get_links.php?session_token=" + SessionToken + "&link_type=direct_download&quick_key=" + quickKey; //send get request, and parse file entries Document XMLDoc = httpGet(targetURL); NodeList tags = XMLDoc.getElementsByTagName("direct_download"); if(tags.getLength() != 1) throw new Exception("Missing/multiple direct_download section:" + tags.getLength()); return tags.item(0).getTextContent(); }
998b7020-f823-4d92-a1f5-a1139b3aee87
public void delete(String quickKey) throws Exception { String targetURL = HTTP_MEDIAFIRE_BASE_API + "file/delete.php?session_token=" + SessionToken + "&quick_key=" + quickKey; //send get request, and parse file entries Document XMLDoc = httpGet(targetURL); NodeList tags = XMLDoc.getElementsByTagName("result"); if(tags.getLength() != 1) throw new Exception("Missing/multiple direct_download section:" + tags.getLength()); String result = tags.item(0).getTextContent(); if(!result.equalsIgnoreCase("success")) throw new Exception("File data failed:" + result); }
b401ed07-e8ff-4a97-8cf7-68a2bb2ff6fd
public Map<String, String> listFiles() throws Exception { Map<String, String> keyNameMap = new HashMap<String, String>(); int chunk = 1; boolean reading = true; while(reading) { String targetURL = HTTP_MEDIAFIRE_BASE_API + "folder/get_content.php?session_token=" + SessionToken + "&content_type=files&chunk=" + chunk; //send get request, and parse file entries Document XMLDoc = httpGet(targetURL); NodeList fileNames = XMLDoc.getElementsByTagName("filename"); NodeList quickKeys = XMLDoc.getElementsByTagName("quickkey"); if(fileNames.getLength() != quickKeys.getLength()) throw new Exception("Mismatch between filenames/keys:" + fileNames.getLength() + " / " + quickKeys.getLength()); for(int i=0;i<fileNames.getLength();i++) { keyNameMap.put(fileNames.item(i).getTextContent(), quickKeys.item(i).getTextContent()); } //stop running when there are no more files returned if(fileNames.getLength() == 0) reading = false; chunk++; } return keyNameMap; }
60b223ba-9121-4006-923b-b2982c157ed0
public void upload(String fileName, byte[] data) throws IOException { String targetURL = HTTP_MEDIAFIRE_BASE_API + "upload/upload.php?session_token=" + SessionToken; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(targetURL); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new ByteArrayBody(data, fileName); mpEntity.addPart("myFile", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println(EntityUtils.toString(resEntity)); } if (resEntity != null) { EntityUtils.consume(resEntity); } httpclient.getConnectionManager().shutdown(); }
c3fd64a4-2ab9-4929-b675-e4a6f912dcd2
private Document httpGet(String targetURL) throws Exception { URL url = new URL(targetURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Send request connection.getOutputStream().flush(); connection.getOutputStream().close(); //check HTTP response code int response = connection.getResponseCode(); if(response != 200) throw new Exception("Unable to login to MediaFire:" + response + " for " + targetURL); //parse response using xml DOM parser DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document XMLDoc = db.parse(connection.getInputStream()); connection.disconnect(); return XMLDoc; }
3d5418c2-0574-4152-a1b5-dc05d12d7f0b
private String sha1String(String myString) throws Exception { String sha1 = ""; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(myString.getBytes("UTF-8")); sha1 = byteToHex(crypt.digest()); } catch(Exception e) { throw new Exception("Exception during creation of SHA1 hash for mediafire login", e.getCause()); } return sha1; }
39a3f04f-c749-48ce-b31e-a7dea2f42b84
private String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; }
1093b594-66be-42b1-8260-3a4b6108f549
private String convertStreamToString(InputStream is) { Scanner s1 = new Scanner(is); Scanner s = s1.useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; s.close(); s1.close(); return result; }
c8e46de2-f24b-4dd1-8868-d7aede49f9d7
public void setUsername(String username) { HttpsGet.Username = username; }
2e07ce09-63a8-4d55-9bbe-ef29a680ad97
public void setPassword(String password) { HttpsGet.Password = password; }
cd23d136-4799-4098-b0be-bb56f11e1ee8
public double getAccountBalance() throws Exception { String bal = runOperation("AccountBalance", null, true); return Double.parseDouble(bal); }
30d6a990-d02c-4be1-9c55-8dd942eb10b5
public int addBid(int minRam, double maxPrice, int bits, int minEcu, String country) throws Exception { String targetOP = "BidAdd"; if(minRam < 0 || minRam > 256*1024) throw new IllegalArgumentException("Minimum RAM must be between 0 and 262144 (mb)"); if(maxPrice < 0 || maxPrice > 2) throw new IllegalArgumentException("Maximum price must be between 0 and 2.0 ($/hour)"); if(bits != 32 && bits != 64 && bits != 0) throw new IllegalArgumentException("Bits must be set to either 32 or 64 (or 0 for either)"); if(minEcu < 0) throw new IllegalArgumentException("Minimum ECU must be greater than 0"); Map<String, Object> params = new HashMap<String, Object>(); params.put("active", true); params.put("maxPrice", maxPrice); params.put("minECU", minEcu); params.put("minRam", minRam); params.put("country", country); params.put("bits", bits); String urlParameters = createUrlParameters(params); //need to parse the first field, which will be an integer bid reference HttpsGet.ParseOnQuery = true; HttpsGet.query(targetOP, urlParameters); String result = HttpsGet.parseReply(0); return Integer.parseInt(result); }
337410fe-527c-480a-818b-3a6b65f64695
public void deleteBid(int bidID) throws Exception { runBidOperation("BidDelete", bidID, false); }
52cf0f7a-d628-4b86-a0f6-53f583190e6c
public int getBookingID(int bidID) throws Exception { String sBookingID = runBidOperation("BidGetBookingID", bidID, true); return Integer.parseInt(sBookingID); }
7c3bf06b-581c-498c-b2b1-fa2d5f2cb938
public List<Integer> getActiveBidIDs() throws Exception { //create result container List<Integer> result = new ArrayList<Integer>(); //get the XML back from the web service HttpsGet.ParseOnQuery = true; HttpsGet.query("BidGetAllInfo", ""); Document document = HttpsGet.XMLDoc; //extract list of booking IDs NodeList bidIDs = document.getElementsByTagName("BidID"); NodeList activeFlags = document.getElementsByTagName("Active"); for(int i=0; i<bidIDs.getLength(); i++) { String sbidID = bidIDs.item(i).getTextContent(); String sactive = activeFlags.item(i).getTextContent(); if(sactive.equalsIgnoreCase("true")) { int bidID = Integer.parseInt(sbidID); result.add(bidID); } } return result; }
a711365c-7847-4dab-af3c-c6f2b04fd8c3
public List<Integer> getActiveBookingIDs() throws Exception { //create result container List<Integer> result = new ArrayList<Integer>(); //get the XML back from the web service HttpsGet.ParseOnQuery = true; HttpsGet.query("BookingGetActiveIDs", ""); Document document = HttpsGet.XMLDoc; //extract list of booking IDs NodeList bookingFields = document.getElementsByTagName("int"); for(int i=0; i<bookingFields.getLength(); i++) { String bookingID = bookingFields.item(i).getTextContent(); result.add(Integer.parseInt(bookingID)); } return result; }
cec2f374-8fb1-4028-b31a-4d0b1f5ac3fa
public String getBookingStatus(int bookingID) throws Exception { return runBookingOperation("BookingGetStatus", bookingID, true); }
2ceef759-5f9e-45d2-a6b3-d9b89aeca325
public String getBookingCountry(int bookingID) throws Exception { return runBookingOperation("BookingGetCountry", bookingID, true); }
b509927c-661a-425e-b8a8-fd63abe79b0f
public String getBookingPassword(int bookingID) throws Exception { return runBookingOperation("BookingGetPassword", bookingID, true); }
51b6bbd6-c12e-4ca9-9513-d6adc73e283c
public String getSudoPassword(int bookingID) throws Exception { return runBookingOperation("BookingGetSudoPassword", bookingID, true); }
acbdeade-132c-45a5-a61e-d10a84a5f38f
public String getMachineSpec(int bookingID) throws Exception { return runBookingOperation("BookingGetMachineSpec", bookingID, true); }
29eda58b-e8de-4ad0-ab40-bb2d1cfff22f
public int getCoreCount(int bookingID) throws Exception { String sCores = runBookingOperation("BookingGetCoreCount", bookingID, true); return Integer.parseInt(sCores); }
9697d0c1-9581-492a-a7f4-5e299a65db00
public int getBookingBidID(int bookingID) throws Exception { String sBidID = runBookingOperation("BookingGetBidID", bookingID, true); return Integer.parseInt(sBidID); }
7f687a19-213d-403c-ba1a-97787a9d8304
public int getECU(int bookingID) throws Exception { String sECU = runBookingOperation("BookingGetECU", bookingID, true); return Integer.parseInt(sECU); }
2428c8c6-a8a7-4d9d-b8dc-647f87a92bbb
public String getCloseReason(int bookingID) throws Exception { return runBookingOperation("BookingGetCloseReason", bookingID, true); }
96d84f3f-0b6f-4d07-a8e0-1e1eefcf2ee7
public void waitReady(int bookingID) throws Exception { String status = "Unknown"; while(!status.equals("Ready")) { //check it hasnt faulted if(status.equals("Closed")) throw new Exception("Machine wasnt able to be booked succesfully:" + bookingID + " " + status); //check the status every 10 seconds Thread.sleep(10000); status = getBookingStatus(bookingID); } }
883ba3af-5b2d-41f1-8937-5789d7af09b3
private String runBookingOperation(String targetOP, int bookingID, boolean parse) throws Exception { if(bookingID < 0) throw new IllegalArgumentException("Booking ID must be > 0"); Map<String, Object> params = new HashMap<String, Object>(); params.put("bookingID", bookingID); return runOperation(targetOP, params, parse); }
696696ba-2741-4b39-935f-faad05ee316e
private String runBidOperation(String targetOP, int bidID, boolean parse) throws Exception { if(bidID < 0) throw new IllegalArgumentException("Bid ID must be >= 0"); Map<String, Object> params = new HashMap<String, Object>(); params.put("bidID", bidID); return runOperation(targetOP, params, parse); }
ad3a31d2-8ff7-4e7a-bc6f-9b643bb2e8d4
private String runOperation(String targetOP, Map<String, Object> params, boolean parse) throws Exception { String urlParameters = createUrlParameters(params); //need to parse the first field, which be the result of the operation HttpsGet.ParseOnQuery = parse; HttpsGet.query(targetOP, urlParameters); if(parse) return HttpsGet.parseReply(0); else return null; }
e41314c2-4829-4de9-9408-aa0c377dee9a
private String createUrlParameters(Map<String, Object> params) { if(params == null || params.size() == 0) return ""; StringBuilder sb = new StringBuilder(); for(Entry<String, Object> param : params.entrySet()) { sb.append(param.getKey() + "=" + param.getValue() + "&"); } String temp = sb.toString(); return temp.substring(0, temp.length()-1); }
5f457cc3-ab59-4536-a276-3c958581b4c7
public HttpsGet(String serviceUrl) { ServiceURL = serviceUrl; }
2a54d096-0e8a-40c1-8bac-94a9a261ec2d
public void query(String operation, String urlParameters) throws Exception { if(Username == null || Username.length() <= 0 || Password == null || Password.length() <= 0) throw new Exception("Must setUsername() / setPassword() before calling any query"); URL url; HttpURLConnection connection = null; try { //open target url //String targetURL = ServiceURL + "/" + operation; String targetURL = ServiceURL + "/" + operation; //System.out.println("Connecting to " + targetURL + " : " + urlParameters); if(!ServiceURL.startsWith("https://")) throw new IllegalArgumentException("Can only be used with https connections - otherwise password is sent plain text"); url = new URL(targetURL + "?" + urlParameters); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //add basic authentication header String encoded = Base64.encodeBytes((Username+":"+Password).getBytes()); connection.setRequestProperty("Authorization", "Basic "+encoded); connection.setConnectTimeout(120000); connection.connect(); //check HTTP response code int response = connection.getResponseCode(); if(response != 200) throw new IOException("HTTP response code error reading from web service: " + response); if(ParseOnQuery) { //parse response using xml DOM parser to get the response booking ID DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); XMLDoc = db.parse(connection.getInputStream()); } } finally { if (connection != null) { connection.disconnect(); } } }
e15d0010-2569-4adb-9751-c3bd0a7e28c7
public String parseReply(int index) throws IndexOutOfBoundsException { //get the contents of the first returned field NodeList replyFields = XMLDoc.getElementsByTagName("*"); if(replyFields.getLength() < index + 1) throw new IndexOutOfBoundsException("Index out of bounds in web service response (" + index + "/" + replyFields.getLength() + ")"); return replyFields.item(index).getTextContent(); }
adc6bdd7-0c92-41b7-a441-e1d6ef3e15ac
private String convertStreamToString(InputStream is) { Scanner s1 = new Scanner(is); Scanner s = s1.useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; s.close(); s1.close(); return result; }
2ed36aeb-6336-47c0-8606-2701e815c2c3
public HttpsPost(String serviceUrl) { ServiceURL = serviceUrl; }
e55debcc-f6ee-4f34-9731-f62a2bfc6d98
public void query(String operation, String urlParameters) throws Exception { if(Username == null || Username.length() <= 0 || Password == null || Password.length() <= 0) throw new Exception("Must setUsername() / setPassword() before calling any query"); URL url; HttpURLConnection connection = null; try { //open target url //String targetURL = ServiceURL + "/" + operation; String targetURL = ServiceURL + "/" + operation; //System.out.println("Connecting to " + targetURL + " : " + urlParameters); if(!ServiceURL.startsWith("https://")) throw new IllegalArgumentException("Can only be used with https connections - otherwise password is sent plain text"); url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //add basic authentication header String encoded = Base64.encodeBytes((Username+":"+Password).getBytes()); connection.setRequestProperty("Authorization", "Basic "+encoded); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //check HTTP response code int response = connection.getResponseCode(); if(response != 200) throw new IOException("HTTP response code error reading from web service: " + response); if(ParseOnQuery) { //parse response using xml DOM parser to get the response booking ID DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); XMLDoc = db.parse(connection.getInputStream()); } } finally { if (connection != null) { connection.disconnect(); } } }
0c88b53f-fbfe-42ec-ae35-e5af83dd6398
public String parseReply(int index) throws IndexOutOfBoundsException { //get the contents of the first returned field NodeList replyFields = XMLDoc.getElementsByTagName("*"); if(replyFields.getLength() < index + 1) throw new IndexOutOfBoundsException("Index out of bounds in web service response (" + index + "/" + replyFields.getLength() + ")"); return replyFields.item(index).getTextContent(); }
0f55a10a-df99-4573-a09a-016f6acc07d2
@Before public void setUp() { parser = new InputParser(); }
5622cbd8-1c4e-4e3c-b12a-27dc7d0266fc
@Test public void parsing() { assertEquals(parser.parse(5), "five"); }
89c89251-8945-4c95-8a57-64dbc4ca401c
@Test public void parsingHundreds() { assertEquals(parser.parse(100), "one hundred"); }
8d687f36-964a-4ea7-b43a-5e94714f2fcc
@Test public void parsingThousands() { assertEquals(parser.parse(1001), "one thousand and one"); }
8ad58474-5eb2-4ac7-b6ce-fea4a50c1f23
@Test public void parsingMillions() { assertEquals(parser.parse(123456789), "one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine"); }
1a9c1d56-55ae-4c1f-9980-aaa6a99262e1
@Test public void parsingThousandsOnly() { assertEquals(parser.parse(1000), "one thousand"); }
6e755201-e3a1-44fd-9389-7a6bb94d54fe
@Before public void setUp() { validator = new InputValidator(); }
20e46ac0-d8d2-41c9-9832-2231b96f3885
@Test public void validInput() throws ValidationException { validator.validate("123456"); }
a9312970-d942-4dd0-af59-6aba4a1285a6
@Test public void validInputWithCommas() throws ValidationException{ validator.validate("123,456"); }
41d22dbb-60ce-4087-a0f0-cc4a13b25338
@Test(expected = ValidationException.class) public void invalidRange() throws ValidationException { validator.validate("1,000,000,000"); }
7080c78f-d5e0-4c62-8079-8beee93fe170
@Test(expected = ValidationException.class) public void invalidInput() throws ValidationException { validator.validate("123f56"); }
08dc58fa-eec0-4fd5-83eb-9b65fdb171eb
@Test(expected = ValidationException.class) public void mostSignigicantDigit() throws ValidationException { validator.validate(",123,456"); }
c9c0043e-3e78-4773-a308-74f282e47692
String ReadInput();
e05ae5b0-31ef-420f-8fa8-1077ae87be60
public PuzzleController() { }