Skip to content

Instantly share code, notes, and snippets.

@aponsin
Forked from gillien/TextmasterApi.java
Created April 14, 2014 17:48
Show Gist options
  • Save aponsin/10668950 to your computer and use it in GitHub Desktop.
Save aponsin/10668950 to your computer and use it in GitHub Desktop.
require 'digest/sha1'
require 'net/http'
require 'json'
class TextmasterApi
API_KEY = ""
API_SECRET = ""
API_VERSION = "beta"
API_BASE_URL = "http://api.sandbox.textmaster.com"
def initialize(attributes = [])
self.url = attributes[0]
self.method = attributes[1]
self.data = attributes[2]
end
def uri
return URI.parse API_BASE_URL
end
def url
return "/#{@url}" if @url == 'test'
return "/#{API_VERSION}/clients/#{@url}"
end
def url=(url)
@url = url || "test"
end
def method
@method.downcase
end
def method=(method)
@method = method || "GET"
end
def data
@data
end
def data=(data)
@data = JSON.parse(data) || {}
end
def request
response = Net::HTTP.start(uri.host, uri.port) do |http|
if ['post', 'put'].include? method
http.send(method, url, data.to_json, headers)
else
http.send(method, url, headers)
end
end
case response
when Net::HTTPSuccess
return response.body
else
return "#{response.code} ERROR"
end
end
private
def self.signature(api_secret, time)
Digest::SHA1.hexdigest(api_secret + time.to_s)
end
def self.str2time(time_str)
Time.parse(time_str + " UTC")
end
def self.get_current_time
Time.now.getutc.to_s[0..-5]
end
def headers
time = TextmasterApi.get_current_time
signature = TextmasterApi.signature(API_SECRET, time)
return {"APIKEY" => API_KEY, "SIGNATURE" => signature, "DATE" => time, 'Content-Type' => 'application/json' }
end
end
tm = TextmasterApi.new(ARGV)
puts tm.request
//date formatting
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
//http request
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//sha1
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
public class TextmasterApi {
private static String API_KEY = "";
private static String API_SECRET = "";
private static String API_BASE_URL = "http://api.sandbox.textmaster.com/";
private static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
private String _result;
private String _url = "test";
private String _method = "GET";
private String _data = "";
public static void main(String[] args) {
TextmasterApi apiConnector = new TextmasterApi(args);
System.out.println(apiConnector.executeRequestAndGetResult());
}
public TextmasterApi(String[] args) {
if (args.length > 0)
_url = args[0];
if (args.length > 1)
_method = args[1];
if (args.length > 2)
_data = args[2];
}
public String getUrl() {
if (_url == "test") {
return _url;
} else {
return "beta/clients/" + _url;
}
}
public String getMethod() {
return _method;
}
public String getData() {
return _data;
}
public String executeRequestAndGetResult() {
baseRequest(getUrl(), getMethod(), getData());
return _result;
}
private void baseRequest(String path, String method, String data) {
try {
URL url = new URL(API_BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoInput(true);
setConnectionHeaders(conn);
//Send request
if (data.getBytes().length > 0) {
conn.setRequestProperty("Content-Length", "" +
Integer.toString(data.getBytes().length));
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream ());
wr.writeBytes(data);
wr.flush();
wr.close();
}
if (conn.getResponseCode() != 200 && conn.getResponseCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
this._result = "";
while ((output = br.readLine()) != null) {
this._result += output;
}
conn.disconnect();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void setConnectionHeaders(HttpURLConnection conn) {
String date = GetUTCdatetimeAsString();
conn.setRequestProperty("APIKEY", API_KEY);
conn.setRequestProperty("DATE", date);
conn.setRequestProperty("SIGNATURE", toSHA1(API_SECRET + date));
conn.setRequestProperty("Content-Type", "application/json");
}
private static String GetUTCdatetimeAsString() {
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
private static String toSHA1(String password) {
String sha1 = "";
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
return sha1;
}
private static 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;
}
}
export TZ=GMT;
API_KEY=""
API_SECRET=""
API_SERVER="api.sandbox.textmaster.com"
API_VERSION="beta"
API_URL="http://$API_SERVER/$API_VERSION/clients/$1"
CURRENT_DATE=`date "+%F %T"`
SIGNATURE=$(echo -n $API_SECRET$CURRENT_DATE | openssl dgst -sha1)
if [ $# -eq 0 ]; then
curl http://$API_SERVER/test -H "DATE: $CURRENT_DATE" -H "APIKEY: $API_KEY" -H "SIGNATURE: $SIGNATURE" --header "Content-type: application/json"
elif [ $# -eq 1 ]; then
curl $API_URL -H "DATE: $CURRENT_DATE" -H "APIKEY: $API_KEY" -H "SIGNATURE: $SIGNATURE" --header "Content-type: application/json"
elif [ $# -eq 2 ]; then
curl $API_URL -H "DATE: $CURRENT_DATE" -H "APIKEY: $API_KEY" -H "SIGNATURE: $SIGNATURE" --header "Content-type: application/json" -X $2
else [ $# -eq 3 ]
curl $API_URL -H "DATE: $CURRENT_DATE" -H "APIKEY: $API_KEY" -H "SIGNATURE: $SIGNATURE" --header "Content-type: application/json" -X $2 -d "$3"
fi
<?php
class TextMasterApi {
const API_KEY = "";
const API_SECRET = "";
const API_BASE_URL = "http://api.sandbox.textmaster.com/"; //"http://api.staging.textmaster.com/";
const API_VERSION = "beta";
public function request($path, $method, $content) {
$body = $this->_baseRequest($path, $method, $content);
print $body;
}
private function _baseRequest($path = "", $method = "", $content = ""){
list($path, $method, $content) = $this->_switchToDefaultIfBlank($path, $method, $content);
return file_get_contents(
self::API_BASE_URL . $path,
false,
$this->_createContext($method, $content));
}
private function _switchToDefaultIfBlank($path, $method, $content) {
$base_request_default = array( "path" => "test", "method" => "GET", "content" => array(), "api_section" => self::API_VERSION . "/clients/");
$path = ($path == "") ? $base_request_default["path"] : $base_request_default["api_section"] . $path;
$method = ($method == "") ? $base_request_default["method"] : $method;
$content = ($content == "") ? $base_request_default["content"] : $content;
return array($path, $method, $content);
}
private function _getAuthHeader() {
$date = gmdate("Y-m-d H:i:s");
$signature = sha1( self::API_SECRET . $date );
return "APIKEY: " . self::API_KEY . "\r\n" . "DATE: " . $date . "\r\n" .
"SIGNATURE: " . $signature . "\r\n" . "Content-Type: application/json";
}
private function _createContext($method, $content) {
$options = array(
"http" => array(
"method" => strtoupper($method),
"header" => $this->_getAuthHeader(),
"content" => $content
)
);
return stream_context_create($options);
}
}
$apiConnector = new TextMasterApi();
$apiConnector->request($argv[1], $argv[2], $argv[3]);
?>
import httplib, urllib, datetime, hashlib
import sys, getopt, json
class TextMasterApi:
API_KEY = ""
API_SECRET = ""
API_BASE_URL = "api.sandbox.textmaster.com"
API_VERSION = "beta"
path = '/test'
method = 'GET'
data = { }
def __init__(self, params = ""):
opts, extraparams = getopt.getopt(params, 'p:m:d:')
for k,v in opts:
if k == '-p':
self.path = ('/beta/clients/' + v)
elif k == '-m':
self.method = v
elif k == '-d':
self.data = json.loads(v)
print self.data
def request(self):
response = self._baseRequest(json.dumps( self.data ))
print response.read()
def _baseRequest(self, json_params = {}):
conn = httplib.HTTPConnection(self.API_BASE_URL)
conn.request(self.method, self.path, json_params, self._getHeaders())
return conn.getresponse()
def _getHeaders(self):
date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
return {
"APIKEY": self.API_KEY,
"DATE": date,
"SIGNATURE": hashlib.sha1(self.API_SECRET + date).hexdigest(),
"Content-Type": "application/json"
}
apiConnector = TextMasterApi(sys.argv[1:])
apiConnector.request()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment