Activemq jolokia rest api for deleting a queue? - rest

Is there a way to delete a queue with ActiveMQ rest api on 5.9.0? I know you can purge a queue with
"http://" + host + ":" + port + "/api/jolokia/exec/org.apache.activemq:brokerName=localhost,destinationName=" + queueName + ",destinationType=Queue,type=Broker/purge()";
But what is the one for deleting?

You should use the following URL pattern:
http://hostname:8161/hawtio/jolokia/exec/org.apache.activemq:type=Broker,brokerName=MyBroker/removeQueue(java.lang.String)/MyQueue
You can read about the format to access JMX operations thorugh jolokia here.

This one works.
curl --location --request GET 'http://localhost:8161/api/jolokia/exec/org.apache.activemq:type=Broker,brokerName=<brokerName>/removeQueue/<queueName>' --header 'Authorization: Basic <token>' \
Courtesy: brettPorter

Here is a java f'n that does it:
public static String removeQueue(String queueName) throws ClientProtocolException, IOException, URISyntaxException {
String username = "admin";
String password = "admin";
URI mqUrl = new URI( YOUR ACTIVE MQ URI HERE );
HttpHost targetHost = new HttpHost(mqUrl.getHost(), mqUrl.getPort(), "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpClient client = HttpClientBuilder.create().build();
String uri = "http://" + mqUrl.getHost() + ":" + mqUrl.getPort() + "/hawtio/jolokia/exec/org.apache.activemq:type=Broker,brokerName=localhost/removeQueue/" + queueName;
HttpResponse response = client.execute(new HttpGet(uri), context);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException(response.getStatusLine().toString());
}
return IOUtils.toString(response.getEntity().getContent());
}

Related

Azure Devops Java HttpsURLConnection authorization

HttpsURLConnection problem, getting a 401 error when running an ADO API to create a new work item. It works from curl command line, but not in Java.
I have tried various suggestions and alternatives I have found, but so far no luck. I am using a PAT generated from ADO for password, so not sure if that is related to the problem. I tried revoking the PAT and regenerate, but it did not help. Can someone tell me what I am doing wrong here?
This works:
curl -u me:mypassword -x myproxy.corp:80 \
'https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0' \
-H 'Content-Type: application/json-patch+json' \
--data-binary '[{"op":"add","path":"/fields/System.Title","value":"Test API"}]'
But this does not work. It gets a 401 error:
public static void createIncident() {
String input = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"Test API\"}]";
String userpass="me:mypassword";
String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes()));
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.corp", 80));
try {
URL url = new URL("https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json-patch+json");
conn.setRequestProperty("Content-Type", "application/json-patch+json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpsURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

How to access Spring REST API in JHipster with standalone

i need to call de jhipster rest service in a java sheduling standalone.
but i dont know how, I try with HttpClient libraries and use CredentialsProvider to set de username and password
I cant login use this
HttpGet httpget = new HttpGet("http://localhost:8080/#Login");
but when I try to get de rest jason api i get HTTP 401 Unauthorized
I see de Gatlin Test make in scala and its like there are simulating a web-browser.
So I am stacking here, and I will apreciate anybody that can give me some suggest in how to do these.
These is the code
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(DEFAULT_USER,DEFAULT_PASS));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
String output;
In this call a have de estatus 401
response = client.execute(new HttpGet(URL_PROMOTORES), context);
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
response.close();
client.close();
Thanks in advance.
I don't think you should use basicAuth because it is for HTTP basic authentication (RFC 2617) which is different from what JHipster uses in your case login/password form encoded and session.

How to call CQ author URL from a standalone code

I am trying to hit URL in cq Author instance from my standalone code. The URL looks like — http://<somehost>:<someport>//libs/dam/gui/content/reports/export.json
Below is the code:
URL url = new URL(newPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15 * 10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
But I got a 401 error, which is expected, as I'm not passing any authentication information — hence Sling says:
getAnonymousResolver: Anonymous access not allowed by configuration - requesting credentials.
How can I get resolve this?
You may use Basic HTTP authentication. Adding it to the HttpURLConnection is little awkward:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
Consider using Apache HttpClient:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
DefaultHttpClient authorizedClient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = authorizedClient.execute(request);
InputStream stream = response.getEntity().getContent();

How to get a paypal access token using REST request

I'm trying to get this working https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/
Using Java + Jersey application. It seems like I'm missing something in POST params.
public String getPaypalToken() {
Client client = Client.create();
WebResource webResource = client.resource("https://api.sandbox.paypal.com/v1/oauth2/token");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("username", CLIENT_ID + ":" + SECRET );
queryParams.add("grant_type", "client_credentials");
ClientResponse response = webResource.accept("application/json").acceptLanguage("en_US").type("application/x-www-form-urlencoded").post(ClientResponse.class, queryParams);
return response.toString();
}
Using previous code I got: POST https://api.sandbox.paypal.com/v1/oauth2/token returned a response status of 401 Unauthorized.
This CURL command line option just works fine:
curl -X POST https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp" -d "grant_type=client_credentials"
Any suggestions will be appreciated.
J.
The -u option in curl sends a base64 encoded "username:password" string. I don't think adding client id / secret to the queryParams map does the same (unless Jersey treats the 'username' key differently which I don't think it does).
You should instead try
webResource.header("Authorization", "Basic " + Base64.encode(CLIENT_ID + ":" + SECRET.getBytes()))
Just sharing my solution:
Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", "sandbox");
string clientid = "<your client id>";
string secretid = "<your secret id>";
string accessToken = new OAuthTokenCredential(clientid, secretid, sdkConfig).GetAccessToken();
I previously encountered unauthorized response using RestSharp, then found this. I'm using paypal .net sdk from nuget package.
Reference.

force.com callout exception Unable to tunnel through proxy

We make a callout from one Salesforce org to another Salesforce org using the REST API. That worked until end of november. We didn't make any changes at the affected classes or configuration.
Now, while sending a request to the rest api a callout exception will be thrown with the message : "Unable to tunnel through proxy. Proxy returns "HTTP/1.0 503 Service Unavailable".
The authorisation to the rest api is done by session id.
Does anyone have any idea what the problem is?
Here the code snipped:
final String WS_ENDPOINT = 'https://login.salesforce.com/services/Soap/c/24.0';
final String REST_ENDPOINT = 'https://eu2.salesforce.com/services/apexrest/UsageReporterService';
final String USERNAME = '*****';
final String PASSWORD = '*****';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('POST');
req.setEndpoint(REST_ENDPOINT);
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000);
HTTP hLogin = new HTTP();
HTTPRequest reqLogin = new HTTPRequest();
reqLogin.setMethod('POST');
reqLogin.setEndpoint(WS_ENDPOINT);
reqLogin.setHeader('Content-Type', 'text/xml');
reqLogin.setHeader('SOAPAction', 'login');
reqLogin.setTimeout(60000);
reqLogin.setCompressed(false);
// get a valid session id
String sessionId;
String loginSoap = '<?xml version="1.0" encoding="UTF-8"?>';
loginSoap += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">';
loginSoap += '<soapenv:Body>';
loginSoap += '<urn:login>';
loginSoap += '<urn:username>' + USERNAME + '</urn:username>';
loginSoap += '<urn:password>' + PASSWORD + '</urn:password>';
loginSoap += '</urn:login>';
loginSoap += '</soapenv:Body>';
loginSoap += '</soapenv:Envelope>';
reqLogin.setBody(loginSoap);
HTTPResponse respLogin;
try {
respLogin = hLogin.send(reqLogin);
} catch(CalloutException c){
return null;
}
System.debug('++++++'+respLogin.getStatus() + ': ' + respLogin.getBody());
Dom.Document doc = new Dom.Document();
doc.load(respLogin.getBody());
Dom.XMLNode root = doc.getRootElement();
String ns = root.getNamespace();
Dom.XMLNode bodyEl = root.getChildElements()[0];
if(bodyEl.getChildElements()[0].getName().equals('loginResponse')){
sessionId = bodyEl.getChildElements()[0].getChildElement('result', ns).getChildElement('sessionId', ns).getText();
}
// finished getting session Id
if(sessionId != null){ // login was successfull
req.setHeader('Authorization', 'Bearer ' + sessionId);
// serialize data into json string
UsageReporterModel usageReporterData = new UsageReporterModel();
String inputStr = usageReporterData.serialize();
req.setBody('{ "usageReportData" : ' + inputStr + '}');
// fire!
HTTPResponse resp;
try {
resp = h.send(req);
} catch(CalloutException c){
return null;
}
}
I suspect this will relate to a change of IP addresses for one of the org's which haven't been whitelisted correctly (or added to the "network access" object). With it being Salesforce to Salesforce I would hope that Salesforce.com support can assist?