如何在java中的嵌套try-catch和while循环中返回值



我正在使用以下代码将SSH连接到远程机器并获取api_key。我使用了try-chatch块和if-and-while循环来返回API键值。以下是步骤-SSH到远程计算机运行cat命令cat命令返回如下所示的JSON数组-

[
{
"apikey": "ewr34234gfdg435",
"app": "app1",
"role": "superadmin",
"user": "req1"
},
{
"apikey": "23rsgsfg3434",
"app": "app1",
"role": "superadmin",
"user": "req2"
}
]

现在,我想要检索API密钥,该密钥具有用户=";req2";只有

以下是代码-

package app1;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.DefaultSessionFactory;
import com.pastdev.jsch.command.CommandRunner;
public class GetAPIKeyValue {
public String getAPIKeyValue(String remote_machine_user,String remote_machine_host, String remote_machine_password) {
String api_key_value = null;
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remote_machine_user, remote_machine_host, 22);
System.out.println("Connecting to Host : " + remote_machine_host + " As user : " + remote_machine_user);
Map<String, String> props = new HashMap<String, String>();
props.put("StrictHostKeyChecking", "no");
sessionFactory.setConfig(props);
System.out.println("Entering Password on Remote Machine to connect");
sessionFactory.setPassword(remote_machine_password);
CommandRunner runner = new CommandRunner(sessionFactory);
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result;
try {
result = runner.execute(command);
if (result.getStderr().isEmpty()) {
System.out.println(result.getStdout());
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(result.getStdout());
JSONArray arrayObj = (JSONArray) obj;
Iterator<JSONObject> iterator = arrayObj.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
api_key_value = (String) jsonObj.get("apikey");
String requestor = (String) jsonObj.get("user");

// Would like to condition here i.e if user=="req2" return the API key of user req2.

}
} else {
System.out.println(result.getStderr());
}
} catch (JSchException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
try {
runner.close();
} catch (IOException e) {
e.printStackTrace();
}
return api_key_value;
}
}

目前,我将在"尝试捕获"结束时返回;返回api_key_value&";。相反,我如何才能返回while语句本身

也许使用Thread可以有所帮助。

if(user =="req2") {
String finalApi_key_value = api_key_value;
new Thread(new Runnable() {
@Override
public void run() {
sendApiKeyValue(finalApi_key_value);
}
}).start();
}

并创建了一个名为sendApiKeyValue:的方法

private void sendApiKeyValue(String finalApi_key_value) {
// Do something.
}

我自己解决了这个问题。

while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
String user = (String) jsonObj.get("user");
if (user.equals("req2")) {
System.out.println("Got User's API Key");
api_key_value = (String) jsonObj.get("apikey");
break;
} else {
System.out.println("Searching user's API Key");
}
}

要简单。只需先重构代码。

public class GetAPIKeyValue {
public static String getApiKeyValue(String remoteMachineUser, String remoteMachineHost, String remoteMachinePassword) throws Exception {
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remoteMachineUser, remoteMachineHost, 22);
sessionFactory.setConfig(Map.of("StrictHostKeyChecking", "no"));
sessionFactory.setPassword(remoteMachinePassword);
return executeAndGetApiKeyForUser(sessionFactory, "req2");
}
private static String executeAndGetApiKeyForUser(SessionFactory sessionFactory, String user) throws Exception {
try (CommandRunner runner = new CommandRunner(sessionFactory)) {
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result = runner.execute(command);
if (result.getStderr().isEmpty())
return getApiKeyForUser(result.getStdout(), user);
System.out.println(result.getStderr());
return null;
}
}
private static String getApiKeyForUser(String json, String user) throws ParseException {
JSONArray arrayObj = (JSONArray)new JSONParser().parse(json);
Iterator<JSONObject> it = (Iterator<JSONObject>)arrayObj.iterator();
while (it.hasNext()) {
JSONObject obj = it.next();
if (obj.get("user").equals(user))
return String.valueOf(obj.get("apikey"));
}
return null;
}
}