How to access Spring REST API in JHipster with standalone - rest

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.

Related

Power automate send email 401 Unauthorized: [no body] - Spring RestTemplate

We defined email workflow in power automate for sending micro soft’s teams meeting invite, and we tried to send using spring-boot RestTemplate.
However, we are getting error saying “401 Unauthorized: [no body]”.
Here is what we tried in sending teams invitation using RestTemplate
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
data.add("SUBJECT", "xxx");
data.add("START_TIME", "xxx");
data.add("END_TIME", "xxx");
data.add("ATTENDEES", "xxx");
data.add("TEXT_BODY", "xxx");
HttpEntity<MultiValueMap> entity = new HttpEntity<>(data, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
While the same workflow is working sending teams meeting using OKHttp with below code snippet,
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "json formatted string content");
Request request = new Request.Builder().url(<<workflow-url>>).method("POST", body).addHeader("Content-Type", "application/json").build();
Response response = client.newCall(request).execute();
There is no authentication/authorization details are provided while sending teams meeting request using OkHttp.
Any clue, where we are going wrong?

How Can i pass the Basic Credentials while using REST API client Program

Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
WebResource resource = client.resource("https://server.location.path");
//WebResource.Builder builder=resource.getRequestBuilder().header("Authorization", "Basic Base64value");
ClientResponse response = resource.accept("application/json")
.get(ClientResponse.class);
System.out.println(response);
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
Here i have been placed the code and please let me know is you have any suggestion please

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();

Activemq jolokia rest api for deleting a queue?

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

Logging in to facebook using apache HTTP client

I am trying to write automated tests for a REST API using apache HTTP client, we are using Facebook as an affiliate to log in.
I have used this question as a starting point:
apache HttpClient to access facebook
But it is using lots of deprecated methods.
I have switched all of these out but I am finding that it is not working.
to validate I have written a method to print out the body response and I am viewing that by making it into a HTML document. When I load that page it has the facebook error message of:
Cookies Required
Cookies are not enabled on your browser. Please enable cookies in your browser preferences to continue.
My code:
CookieStore cs = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpget);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php");
context.setCookieStore(cs);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*****"));
nvps.add(new BasicNameValuePair("lsd", "AVptst2v"));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Cookie", cs.toString());
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().setDefaultCookieStore(cs).build().execute(httpost,context);
System.out.println("Login form post: " + response.getStatusLine());
System.out.println(printBodyOfResponse(response));
To answer my own question, I found that creating a context and passing that through with each request carried the session, I see lots of answers saying that cookie management is automatic, but for me the only solution was to pass the context throughout
BasicHttpContext context = new BasicHttpContext();
HttpGet get = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response= HttpClientBuilder.create().build().execute(get,context);
System.out.println("Login form get: " + response.getStatusLine());
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php?login_attempt=1");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email",PropertiesUtil.loadSiteProperty("FB_email")));
nvps.add(new BasicNameValuePair("pass", PropertiesUtil.loadSiteProperty("FB_password")));
httpost.setHeader("User-Agent", "Mozilla/5.0");
httpost.setHeader("Host", "www.facebook.com");
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Referer", "https://www.facebook.com/login");
httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = HttpClientBuilder.create().build().execute(httpost,context);