简体   繁体   中英

How to return a value in nested try catch and while loop in java

I am using the below piece of code to SSH to a remote machine and get api_key. I have used a try-catch block and if and while loop to return the API key value. Below are the steps - SSH to Remote machine run cat command cat command returns JSON array like below -

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

Now, I want to retrieve the API key which has user="req2" only.

Below is the code -

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;
    }
}

Currently i am returning at the end of try catch "return api_key_value;". Instead how can i return in while statement itself

Maybe use Thread can help.

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

And creat a method called sendApiKeyValue :

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

I fixed the issue myself.

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");
                    }
                }

Be simple. Just refactor your code first.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM