Skip to content

Instantly share code, notes, and snippets.

@pjmuley
Created July 6, 2017 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjmuley/2ea582e90dae0754862887ea308bcbf2 to your computer and use it in GitHub Desktop.
Save pjmuley/2ea582e90dae0754862887ea308bcbf2 to your computer and use it in GitHub Desktop.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.util.UUID;
import javax.ws.rs.core.MultivaluedMap;
public class TestAPI {
public static void main(String[] args){
try {
String client_id="85xxxxxxxxxxxxxxxxxxxxxxxxxxx8fd";
String client_secret="2B7xxxxxxxxxxxxxxxxxxxxxxxxxxx3b1";
String queueName="myQueue";
String queueMessage="This is my sample message";
String authURI="https://mq-us-west-2.anypoint.mulesoft.com/api/v1/authorize";
String brokerURI="https://mq-us-west-2.anypoint.mulesoft.com/api/v1/organizations/";
// Get access token required for publish/subscribe API's
Client client = Client.create();
WebResource webResource = client.resource(authURI);
String input = "client_id="+client_id+"&client_secret="+client_secret+"&grant_type=client_credentials";
ClientResponse response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
.accept("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String authResponse = response.getEntity(String.class);
System.out.println("\n============Platform Reponse============");
System.out.println(authResponse);
JSONParser jsonParser=new JSONParser();
JSONObject jsonObject= (JSONObject) jsonParser.parse(authResponse);
String access_token=(String)jsonObject.get("access_token");
JSONObject structure = (JSONObject) jsonObject.get("simple_client");
String orgId=(String)structure.get("orgId");
String envId=(String)structure.get("envId");
System.out.println("Access Token:"+access_token);
System.out.println("Organization Id:"+orgId);
System.out.println("EnvironmentId:"+envId);
brokerURI = brokerURI + orgId +"/environments/"+ envId +"/destinations/"+ queueName+"/messages";
// Post message to existing queue using API
String messageId=UUID.randomUUID().toString();
String postURI=brokerURI+"/"+messageId;
System.out.println(postURI);
WebResource webResourcePost = client.resource(postURI);
String inputPost="{ \"body\": \""+queueMessage+"\" }";
ClientResponse responsePost=webResourcePost.header("Authorization"," bearer" + access_token)
.type("application/json")
.accept("application/json")
.put(ClientResponse.class, inputPost);
String outputPost = responsePost.getEntity(String.class);
System.out.println("Post Successful: \n"+outputPost);
// Get message from existing queue using API
WebResource webResourceGet = client.resource(brokerURI);
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("poolingTime","10000");
queryParams.add("batchSize","1");
queryParams.add("lockTtl","10000");
ClientResponse responseGet=webResourceGet.queryParams(queryParams)
.header("Authorization"," bearer" + access_token)
.type("application/json").accept("application/json").get(ClientResponse.class);
String outputGet = responseGet.getEntity(String.class);
System.out.println("Message Retrieved: \n" + outputGet);
// Message acknowledgement, effectively deleting message from the queue
JSONArray jsonArrayAck= (JSONArray) jsonParser.parse(outputGet);
JSONObject structureAck =(JSONObject) ((JSONObject)jsonArrayAck.get(0)).get("headers");
String lockId= (String)structureAck.get("lockId");
WebResource webResourceAck = client.resource(postURI);
String inputAck="{ \"lockId\": \""+lockId+"\" }";
ClientResponse responseAck=webResourceAck.header("Authorization"," bearer" + access_token)
.type("application/json")
.accept("application/json")
.delete(ClientResponse.class, inputAck);
String outputAck = responseAck.getEntity(String.class);
System.out.println("Ack Message: \n" + outputAck);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@sylvia090
Copy link

Hi, I tried the same code in .net as below -

`String client_id = "20a348457fbd4d729341c813f1168ee1";
String client_secret = "99b6Df309a0447b587bA5f13df28F335";
String queueName = "sl-westmq-app";

        String queueMessage = "This is my sample message";
        String authURI = "https://mq-us-west-2.anypoint.mulesoft.com/api/v1/authorize";
        String brokerURI = "https://mq-us-west-2.anypoint.mulesoft.com/api/v1/organizations/";
        //get token
        var request = WebRequest.Create(authURI) as HttpWebRequest;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        var authCredentials = "client_id="+client_id+"&client_secret="+client_secret+"&grant_type=client_credentials";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        request.ContentLength = bytes.Length;
        try
        {
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            var authResponse = request.GetResponse() as HttpWebResponse;
            Stream rebut = authResponse.GetResponseStream();
            StreamReader readStream = new StreamReader(rebut, Encoding.UTF8); // Pipes the stream to a higher level stream reader with the required encoding format. 
            string info = readStream.ReadToEnd();
            string[] responsedata = info.Split(',');
            string access_token;
            
            string[] acc = responsedata[0].Split(':');
               
                    access_token = acc[1].Replace("\"", "");

               
            
            //send message to MQ

                    try
                    {
                        string orgId = "8f8e6e12-de89-4e43-b05b-ebfcc75c676b";
                        string envId = "7715a562-89c4-401d-91a7-71fc1c7227ba";
                        String messageId = Guid.NewGuid().ToString();
                        brokerURI = brokerURI + orgId + "/environments/" + envId + "/destinations/" + queueName + "/messages/" + messageId;
                        WebRequest theRequest = WebRequest.Create(brokerURI);
                        theRequest.Method = "POST";
                        theRequest.ContentType = "application/json";
                        theRequest.ContentLength = queueMessage.Length;
                        theRequest.Headers.Add("Authorization", access_token);
                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                        Stream requestPostStream = theRequest.GetRequestStream();

                        requestPostStream.Write(Encoding.ASCII.GetBytes(queueMessage), 0, queueMessage.Length);
                        requestPostStream.Close();
                        HttpWebResponse response = (HttpWebResponse)theRequest.GetResponse();
                    }

                    catch (WebException webex)
                    {
                        WebResponse errResp = webex.Response;
                        using (Stream respStream = errResp.GetResponseStream())
                        {
                            StreamReader reader = new StreamReader(respStream);
                            string text = reader.ReadToEnd();
                        }
                    }

            
        }
        catch (Exception ex)
        {
           Console.Write(ex.ToString());
        }

`

However when i send the message to the Anypoint MQ I get the error as
The remote server returned 500

Even I try to access the broker URL directly as below -
https://mq-us-west-2.anypoint.mulesoft.com/api/v1/organizations/8f8e6e12-de89-4e43-b05b-ebfcc75c676b/environments/7715a562-89c4-401d-91a7-71fc1c7227ba/destinations/sl-westmq-app/messages/390b01d9-ca75-4936-8230-7120feff30f1

I get the below error -

{
"status": "failure",
"statusMessage": "Unexpected error"
}

Can someone help me?

@vijay-whishworks
Copy link

i am also getting the same error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment