Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Better way to make a string with template variables in java

Hi,
I have been working with GraphQL queries for Github...
I am building for example the following query to be sent to Git to fetch the number of pullRequests, issues,...etc...
{
  repository(owner: "ta", name: "otes") {
    pullRequests(states: OPEN) {
      totalCount
    }
    issues(states: OPEN) {
      totalCount
    }
    refs(refPrefix: "refs/heads/") {
      totalCount
    }
  }
}

Open in new window

This works if you type it in :
https://developer.github.com/early-access/graphql/explorer/
But if you see in the network tab a string of the similar nature gets passed.. How i am doing this currently in Java is :
 public String queryForRepoInfo(String owner, String repo) {
        String ownerWithQuotes = "\\\"" + owner + "\\\"";
        String repoWithQutoes = "\\\"" + repo + "\\\"";
        String query = "{\n" +
                "  repository(owner: " + ownerWithQuotes + ", name: " + repoWithQutoes + ") {\n" +
                "    pullRequests(states: OPEN) {\n" +
                "      totalCount\n" +
                "    }\n" +
                "    issues(states: OPEN) {\n" +
                "      totalCount\n" +
                "    }\n" +
                "    refs(refPrefix: \\\"refs/heads/\\\") {\n" +
                "      totalCount\n" +
                "    }\n" +
                "  }\n" +
                "}\n";

        return query;
    }

    public void executIt(String query) {
        String data = "{ \"query\" :" + "\"" + query + "\"" + ", \"variables\" : \"{}\" " + ", \"operationName\" : null}";
        data = data.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n");
        JsonNode jsonNode = restTemplate.postForObject(gitGraphQlUrl, data, JsonNode.class);

    }

Open in new window


This seems to be a bug prone and ugly way to do it... Please suggest an alternative way to do the same...

Thanks
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

The first thing that springs to mind is that could create a domain object (Query?) and set its attributes. Then json-ize it to send over
Avatar of Rohit Bajaj

ASKER

Hi,
Its not json that i am sending here...
Its the exact string query... with newlines etc...
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial