I am new to ActiveMQ, we had a ActiveMQ Server else where location, we are unable to connect thru tcp socket, But able to cousume the message using REST command
http://admin:admin#localhost:8161/api/message?destination=queue://orders.input
I have 99K+ messages in ActiveMQ, need consume using REST command and need to store in a text file,
import static com.jayway.restassured.RestAssured.given;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.dnb.e2e.automation.util.CommonUtil;
import com.dnb.e2e.automation.util.WebServiceUtil;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.config.SSLConfig;
import com.jayway.restassured.config.SessionConfig;
import com.jayway.restassured.response.Headers;
public class MQwithRest {
public static String getResponse() throws Exception
{
String url = "http://admin:admin#localhost:8161/api/message?destination=queue://SAMPLEQUEUE";
String response = "a";
while(response!=""){
try {
response = given().header("content-type", "application/json")
.request()
.config(RestAssured.config().sslConfig(new SSLConfig().allowAllHostnames()))
.when().get(url).asString();
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
return "empty";
}
public static void main(String args[]) throws Exception
{
System.out.println(MQwithRest.getResponse());
}
}
In the above code i am displaying consumed messages at output side. When I am implementing thru rest i am able to consume only one message at a time per session.
Can any body help for Consuming 99k+ message with in a single session using REST service?
You can also tunnel JMS client over HTTP.
That way, you can get bypass any non-HTTP restrictions in your network and still use the JMS terminology.
Using the rest web app bundled you are a bit limited to the semantics of retrieving messages. Anyway, you should be able to get all messages using plain HTTP/Rest anyway. Simply use a loop to get messages.
Related
I have an application running on port 7070 on my local. It exposes and endpoint /metrics and shows all the tags that are available. Prometheus is not able to get these data and it says 'expected label name, got "BCLOSE"'.
I have been trying to figure this out but not sure why this code doesn't work:
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import metrics.PrometheusRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
#Path("/metrics")
public class MetricsController {
private final PrometheusMeterRegistry prometheusRegistry = PrometheusRegistry.INSTANCE();
#GET
public Response getMetrics(#Context HttpHeaders headers) {
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, prometheusRegistry.getPrometheusRegistry().metricFamilySamples());
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
}
}
Also, the application is neither a sprintboot nor a spring project.
Tried this:
#GET
public Response getMetrics(#Context HttpHeaders headers) {
String accept = headers.getRequestHeader("Accept").get(0);
System.out.println("Accept Header --------------------------> " + accept);
return Response.ok(prometheusRegistry.scrape(), "application/openmetrics-text").build();
}
Even then the same error as above SS.
This worked for me:
#GET
public Response getMetrics() {
return Response.ok(prometheusRegistry.scrape(), TextFormat.CONTENT_TYPE_004).build();
}
I'm trying to parse the request sent to a java based fulfillment in V2 of the API. I can't find any example documentation in Java for doing this in V2 of the API (com.google.cloud:google-cloud-dialogflow:0.38.0-alpha dependency in my project).
So far I've got as far as writing a very basic Spring MVC controller to accept the request.
How can I parse out the payload in the request, e.g. the parameters that dialog flow sent ?
import com.google.cloud.dialogflow.v2beta1.WebhookRequest;
import com.google.cloud.dialogflow.v2beta1.WebhookResponse;
import com.google.protobuf.Descriptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
#RestController
#RequestMapping("test")
public class TestRequestRestController {
private static final Logger log = LoggerFactory.getLogger(TestRequestRestController.class);
#PostMapping("test1t")
public WebhookResponse getTest1(WebhookRequest request) {
System.out.println(request.toString());
return WebhookResponse.newBuilder().setFulfillmentText("Example reply 1 ").build();
}
}
Not sure about WebhookRequest and WebhookResponse.
The code below code might help you.
import org.springframework.http.HttpEntity;
#PostMapping("test1t")
public String getTest1(HttpEntity<String> httpEntity) {
String reqObject = httpEntity.getBody();
System.out.println("request json object = "+reqObject);
//Get the action
JSONObject obj = new JSONObject(reqObject);
String action = obj.getJSONObject("result").getString("action");
//Get the parameters
JSONObject params = obj.getJSONObject("result").getJSONObject("parameters");
String response = "Hello from Java.";
return "{'speech': '"+response+"', 'displayText':'"+response+"'}";
}
I'm trying to store a response comprising of a list of channels into a List Object in the client, so that it can display its contents in a JSP.
Right now, I wrapped the list into a GenericEntity, because I know it will only compile this way.
UPDATE: I'm using REST 3.1.3-Final-all, and I have also added all the JARs in them. From research, I thought the reason was that I don't have the jackson provider jars, but this has not solved the problem.
I also am wrapping the list in a GenericType from the other side.
I'm confused as to what a "MessageBodyReader" is, as I'm getting an exception that shows the following:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Client created.
Exception in thread "main" javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type text/plain and type interface java.util.List
at org.jboss.resteasy.core.interception.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:42)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:75)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:52)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:55)
at org.jboss.resteasy.security.doseta.DigitalVerificationInterceptor.aroundReadFrom(DigitalVerificationInterceptor.java:36)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:55)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:251)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:181)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:225)
at examples.pubhub.utilities.test.main(test.java:33)
The segment of code I'm trying to test is as follows:
client (tested in an offline main class):
package examples.pubhub.utilities;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.SyncInvoker;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import examples.pubhub.model.Channel;
public class test {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
System.out.println("Client created.");
WebTarget target = client.target("http://localhost:8080/RESTService/service/authorchannels/channels/");
Response response = target.request().accept(MediaType.TEXT_PLAIN).get();
List<Channel> channels = response.readEntity(new GenericType<List<Channel>>() {});
if (response.getStatus() != 200) {
System.out.println("ChannelDAOImpl utilized, but channels could not be retrieved!" );
} else {
System.out.println(response.getMediaType().toString());
System.out.println(response.readEntity(String.class));
System.out.println("Channels? " + channels);
System.out.println("ChannelDAOImpl utilized; channels succesfully acquired.");
}
}
}
and the RESTFUL Service class with method:
package methods;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import model.Channel;
import resources.DAOUtilities;
#Path("/authorchannels")
public class AuthorChannel {
#SuppressWarnings("unchecked")
#GET
#Path("/channels")
public Response getAllChannels() {
System.out.println("Accessing RESTService, and acquiring channels...");
SessionFactory sessionFactory = DAOUtilities.getSessionFactory();
System.out.println("Session Factory acquired.");
Session session = sessionFactory.openSession();
System.out.println("Session opened.");
session.beginTransaction();
Query query = session.createQuery("from Channel");
List<Channel> channels = (List<Channel>) query.list();
GenericEntity<List<Channel>> list = new GenericEntity<List<Channel>>(channels) {};
System.out.println("Did we get the channels? " + channels);
System.out.println("Channel users? " + ((List<Channel>) channels).get(0).getChannel_user());
System.out.println("Channel bios? " + ((List<Channel>) channels).get(0).getChannel_bio());
session.getTransaction().commit();
//prepare response status to be returned to client
ResponseBuilder respBuilder = null;
if (channels != null)
respBuilder = Response.status(Response.Status.OK);
else
respBuilder = Response.status(Response.Status.NOT_FOUND);
//deliver response to client, indicating that the channels have been acquired.
return respBuilder.status(200).entity(list).build();
}
}
A few things to note:
I'm not using Maven, as I only want to display each one in MediaType.TEXT_PLAIN, but if its easier to switch to APPLICATION_XML or APPLICATION_JSON, then please let me know.
My intention is to simply convert the list Response into a javatype list, so that I can display each of its elements in a table in a JSP later on.
If someone can explain to me what a MessageBodyReader is, I would greatly appreciate it.
Executing this url on my browser: http://localhost:3161/devices/simulator/stop
I don't need login for it. It returns this rest api xml:
<response>
<type>response</type>
<ts>1463749194000</ts>
<status>OK</status>
<msg-version>2.3.0</msg-version>
<op>stop</op>
<data/>
</response>
How can I execute this from JAVA and then capture the xml response?
As other mentioned in this post, it is generic thing, you would be able to find it online already..
I know there are clients to call the REST services from Java. Two of them are listed for your case.
case -1 : if you are using Jersey REST API. Here to capture XML , you can go with your own way,for example use JAXB and XML elements to Java Bean properties.
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(UriBuilder.fromUri('http://localhost:3161/devices/simulator/stop').build());
// getting XML data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_JSON).get(String.class));
// getting JSON data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class));
}
}
Case 2: using HTTP method, it is simple method but parse XML instead of printing it here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet('http://localhost:3161/devices/simulator/stop');
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = '';
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}
I have to get the list of files or folder present in ftp server .I have tried the following code but I do not get the list. If I am running the same code I am getting list of file if I am making my local system as server but when I apply the same code then I am sucessfully logged in and list method of FTPClient class is working but listFiles(),listNames() are not working .
import java.io.IOException;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
/**
*
* #author admin
*/
public class ListFileOfServerCheck {
public static void main(String args[]) throws SocketException, IOException{
FTPClient client = new FTPClient();
ArrayList dirList=new ArrayList();
client.connect("myserver");
client.login("vishal", "vishal");
if(client.isConnected())
System.out.println("connected");
int i=0;
System.out.println("number of files on server="+client.list());
String[] names = null;
int itration=1;
while(names==null){
System.out.println(itration +"th itration");
names = client.listNames();
itration++;
}
client.logout();
client.disconnect();
}
}
It's question what is your current dir when you log in to the FTP. Try to use:
client.listNames("/path/to/the/folder");
instead of relying on the current working directory.
It would be also good practice to check what returns the
client.login(...)