我在eclipse中使用了java代码,并完成了eclipse与IBM bluemix cloudant服务之间所需的所有设置 我不知道如何更新我的代码以在eclipse中启用cloudant 有人可以帮忙吗?
答案 0 :(得分:4)
您需要在项目源目录下的CloudantClient.java文件中添加一段代码。 请在CloudantClient类中添加以下行:
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQULDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
你也可以将这段代码放在try catch循环中。
try {
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQULDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
}
catch (IOException e) {
e.printStackTrace();
}
我希望它有效!
答案 1 :(得分:1)
您可以使用Bluemix配置解析器库自动解析VCAP_SERVICES env变量(https://github.com/icha024/bluemix-config-parser)
它将凌乱的代码简化为......
String username = BluemixConfigStore.getConfig().getCloudantNoSQLDB()
.getCredentials().getUsername();
String password = BluemixConfigStore.getConfig().getCloudantNoSQLDB()
.getCredentials().getPassword();
然后您可以照常创建Cloudant客户端:
CloudantClient cloudantClient = ClientBuilder.account(username)
.username(username)
.password(password)
.build();
答案 2 :(得分:0)
您需要使用bluemix中使用的VCAP_SERVICES env变量,如下所示:
private JSONArray cloudant;
private JSONObject cloudantInstance;
private JSONObject cloudantCredentials;
public CloudantClient()
{
this.httpClient = null;
try {
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQLDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
} catch (IOException e) {
e.printStackTrace();
}
this.port = Config.CLOUDANT_PORT;
this.host = (String) cloudantCredentials.get("host");
this.username = (String) cloudantCredentials.get("username");
this.password = (String) cloudantCredentials.get("password");
this.name = Config.CLOUDANT_NAME;
this.dbc = this.createDBConnector();
}