I am trying to implement SSE client in java from this tutorial.
It is working fine when implemented as Servlet client using post method.But it is not working when I am implementing the same in Java project using main method and with same jar files as in servlet.Here is the code I am using along with target URI:-
import javax.ws.rs.Consumes;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.media.sse.EventListener;
import org.glassfish.jersey.media.sse.EventSource;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
public class SSEreceive {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = ((Client)client).target("http://www.w3schools.com/html/demo_sse.php");
EventSource eventSource = (EventSource)EventSource.target(target).build();
EventListener listener = new EventListener() {
#Override
//#Consumes(MediaType.APPLICATION_JSON)
public void onEvent(InboundEvent inboundEvent) {
// System.out.println(inboundEvent.getName() + "; " + inboundEvent.readData(String.class));
System.out.println(inboundEvent.readData(String.class));
}
};
//eventSource.register(listener, "message-to-client");
eventSource.register(listener);
eventSource.open();
System.out.println("Connection tried");
eventSource.close();
} catch (ProcessingException pe) {
pe.printStackTrace();
System.out.println(pe.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Can some please help me why this is not working in Java project ?
Related
I’m trying to add a Prometheus metrics exporter to my Java app. The app is currently using javax.ws.rs to define REST endpoints.
For example:
Import javax.ws.rs.*;
Import javax.ws.rs.core.MediaType;
Import javax.ws.rs.core.Response;
#GET
#Path(“/example”)
#Timed
Public Response example(#QueryParam(“id”) Integer id) {
return Response.ok(“testing”)
}
All the examples I found for setting up Prometheus in Java are using Spring. They suggest the following:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.prometheus.client.exporter.HTTPServer;
import java.io.IOException;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
try {
HTTPServer server = new HTTPServer(8081);
} catch (IOException e) { e.printStackTrace(); }
}
}
Is there a way I can simply define a new endpoint in my current setup, for example:
#GET
#Path(“/metrics”)
#Timed
Public Response example {
return Response.ok(“return prom metrics here”)
}
Without having to introduce Spring into the stack?
This can be done as follows:
import io.prometheus.client.Counter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.TextFormat;
CollectorRegistry registry = new CollectorRegistry();
Counter exCounter = Counter.build().name(“example”).register(registry);
#GET
#Path(“/metrics”)
Public String getMetrics() {
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, registry.metricFamilySamples());
return writer.toString();
} catch (IOException e) {
return “error”;
}
}
I'm trying to listen my Gmail inbox for incoming mails. Every time new mail arrives, I want to see it's subject and content.
So far, I have this:
import java.io.IOException;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.util.MimeMessageParser;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mail.transformer.MailToStringTransformer;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
public class GmailInboundImapIdleAdapterTestApp {
private static Log logger = LogFactory.getLog(GmailInboundImapIdleAdapterTestApp.class);
public static void main (String[] args) throws Exception {
#SuppressWarnings("resource")
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("/META-INF/spring/integration/gmail-imap-idle-config.xml");
DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
inputChannel.subscribe(new MessageHandler() {
public void handleMessage(Message<?> message){
MimeMessage mm = (MimeMessage) message.getPayload();
try {
System.out.println("Subject: "+mm.getSubject());
System.out.println("Body: "+readPlainContent(mm));
}
catch (javax.mail.MessagingException e) {
System.out.println("MessagingException: "+e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
e.printStackTrace();
}
}
});
}
private static String readHtmlContent(MimeMessage message) throws Exception {
return new MimeMessageParser(message).parse().getHtmlContent();
}
private static String readPlainContent(MimeMessage message) throws Exception {
return new MimeMessageParser(message).parse().getPlainContent();
}
}
It can read the mail subject correctly. But no luck with mail body.javax.mail.FolderClosedException hit me. How to fix this?
As Gary said: simple-content="true" or since recently autoCloseFolder = false: https://docs.spring.io/spring-integration/docs/5.2.0.RELEASE/reference/html/mail.html#mail-inbound
Starting with version 5.2, the autoCloseFolder option is provided on the mail receiver. Setting it to false doesn’t close the folder automatically after a fetch, but instead an IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE header (see MessageHeaderAccessor API for more information) is populated into every message to producer from the channel adapter. It is the target application’s responsibility to call the close() on this header whenever it is necessary in the downstream flow:
Community:
Recently while I work in a project with Elasticsearch[2.3.1], I try to make a simple query to ES using a java API compile in a .jar(elasticsearch.2.3.1.jar) file that I add to my project, but when I code next :
QueryBuilder qb = simpleQueryStringQuery("+kimchy -elasticsearch");
The IDE didnt reconize the instruction "simpleQueryStringQuery("+kimchy -elasticsearch")" but in all example in internet and in ES official site appears in this form. What is doing wrong? Thank in advance.
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.sort.SortParseElement;
public class Search {
public static void main(String[] args) {
Client client;
Settings settings = Settings.settingsBuilder()
.put("client.transport.ignore_cluster_name", true).build();
try {
client = TransportClient
.builder()
.settings(settings)
.build()
.addTransportAddress(
new InetSocketTransportAddress(InetAddress
.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
QueryBuilder qb = simpleQueryStringQuery("+kimchy -elasticsearch");
SearchResponse scrollResp = client.prepareSearch("thing")
.addSort(SortParseElement.DOC_FIELD_NAME, SortOrder.ASC)
.setScroll(new TimeValue(60000))
.setQuery(qb)
.setSize(100).execute().actionGet(); //100 hits per shard will be returned for each scroll
//Scroll until no hits are returned
while (true) {
for (SearchHit hit : scrollResp.getHits().getHits()) {
//Handle the hit...
}
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
//Break condition: No hits are returned
if (scrollResp.getHits().getHits().length == 0) {
break;
}
}
}
}
You know how methods and imports work? The error comes because your class doesn't have a method called simpleQueryStringQuery and you don't import that method.
What you really want is: either use QueryBuilders.simpleQueryStringQuery("...")
Or use a static import for QueryBuilders.simpleQueryStringQuery. See: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html or https://en.wikipedia.org/wiki/Static_import
Yes, it's that newbie to Vaadin, again. This time, I'm trying to see if I can do one of the most basic of tasks: connect to a database.
We use MS SQL Server here (version 2012, I believe) and we've been able to connect to it fine in two other Java programs that I've written. When attempting to do the same thing using a newly-created Vaadin project, however, I am told that No suitable driver found for jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014. I have checked and made sure that all three .jars from Microsoft are in the build path: sqljdbc.jar, sqljdbc4.jar, and sqljdbc41.jar.
Here's the ConnectionManager class that I've written which only tests whether or not it can get a connection:
package info.chrismcgee.sky.vaadinsqltest.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class ConnectionManager {
Logger logger = Logger.getLogger(ConnectionManager.class.getName());
private static final String USERNAME = "web";
private static final String PASSWORD = "web";
private static final String CONN_STRING = "jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014";
public ConnectionManager() throws SQLException, ClassNotFoundException {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
The result is the SQLException message I mentioned earlier. I've tried it both with and without that Class.forName... line, which is apparently only necessary for Java versions below 7 (and we're using version 8). When that line is enabled, I get a ClassNotFoundException instead.
What gives?
EDIT 04/01/2015: To help clarify how this ConnectionManager class is called, I am simply creating an instance of it from the main class, thusly:
package info.chrismcgee.sky.vaadinsqltest;
import java.sql.SQLException;
import info.chrismcgee.sky.vaadinsqltest.dbutil.ConnectionManager;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("vaadinsqltest")
public class VaadinsqltestUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = VaadinsqltestUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
ConnectionManager connMan = new ConnectionManager();
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.addComponent(new Label("Thank you for clicking"));
}
});
layout.addComponent(button);
}
}
You need your dependencies in your runtime environment.
Please have a look at this answer here at stackoverflow:
https://stackoverflow.com/a/19630339
I have a web application I am making using a websocket API to handle the websockets, here is the code for that part
package comm2.hello;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.session.*;
#ServerEndpoint(value = "/echo")
public class wschat {
private static ArrayList<Session> sessionList = new ArrayList<Session>();
#OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
// asynchronous communication
session.getBasicRemote().sendText("hello");
} catch (IOException e) {
}
}
public void send(String text, Session session) throws IOException {
session.getBasicRemote().sendText(text);
}
}
I am trying to have another java class then call into the send method to send messages, using the following code.
package comms;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.Session;
import javax.websocket.Session;
import comm2.hello.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
wschat h = new wschat();
String text = "hello";
//session shouldn't be null but not sure what to make it
Session session = null;
h.send(text,session);
}
}
As you can see, I have the session variable in the main.java class set to null which will thus always produce a null pointer error. This is because I am not sure what to make session equal to, does anyone have any idea what to initialize the session variable to in main.java?