Created
September 27, 2012 16:09
-
-
Save fern4lvarez/3794863 to your computer and use it in GitHub Desktop.
Get credentials from addons json file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.json.simple.JSONObject; | |
import org.json.simple.parser.JSONParser; | |
import org.json.simple.parser.ParseException; | |
public class Credentials { | |
/* | |
* Example of use: | |
* Credentials cr = new Credentials(); | |
* String addon = "MYSQLSDEV"; | |
* HashMap<String, Object> creds = cr.getCredentials(addon); | |
* String database = (String)creds.get("database"); | |
* String password = (String)creds.get("password"); | |
* Long port = (Long)creds.get("port"); | |
* String hostname = (String)creds.get("hostname"); | |
* String username = (String)creds.get("username"); | |
*/ | |
private JSONObject credFile; | |
public Credentials() { | |
this.credFile = getCredFile(); | |
} | |
public HashMap<String, Object> getCredentials(String addon) { | |
HashMap<String, Object> creds = new HashMap<String, Object>(); | |
if ( (addon == "MYSQLSDEV") || (addon == "MYSQLS") || (addon == "MYSQLD") ) { | |
creds.put("database", getCredential("database", addon)); | |
creds.put("password", getCredential("password", addon)); | |
creds.put("port", getCredential("port", addon)); | |
creds.put("hostname", getCredential("hostname", addon)); | |
creds.put("username", getCredential("username", addon)); | |
} else if (addon == "MONGOLAB") { | |
creds.put("uri", getCredential("uri", addon)); | |
} | |
else System.out.println("No available addon"); | |
return creds; | |
} | |
private Object getCredential(String param, String addon) { | |
String upper_param = param.toUpperCase(); | |
JSONObject addonJSON = getAddon(credFile, addon); | |
// TODO credential in addon validation | |
Object credential = addonJSON.get(addon+"_"+upper_param); | |
return credential; | |
} | |
private JSONObject getCredFile() { | |
JSONObject credFile = new JSONObject(); | |
JSONParser parserJSON = new JSONParser(); | |
Map<String, String> env = System.getenv(); | |
String credFilePath = (String)env.get("CRED_FILE"); | |
System.out.println("cred file path: " + credFilePath); | |
try { | |
Object obj = parserJSON.parse(new FileReader(credFilePath)); | |
credFile = (JSONObject) obj; | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
return credFile; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment