What does timeout operator measure in Reactor and why it doesn't work in some cases? - spring-webflux

Recently, a reactive piece of code results in timeout, it involves redis operation, like this:
redisOps.entries(key).map(...).map(...).switchIfEmpty().timeout();
In order to identify if timeout happens in redis query, I think timeout should be located after entries, in this way, map consumed time would not be monitored by timeout. So I made a guess, and wrote demo.
does timeout monitor data emission elapsed time until it, and data operations after it is not counted? For example, in the following code snippet, only time consumption in a and b are monitored by timeout, not including c or d.
Mono mono = foo();
mono.a().b().timeout().c().d();
Why in the following code, timeout does not work.
Mono.just("good luck")
.map(s -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "timeout 1";
})
.map(s->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "timeout 2";
})
.timeout(Duration.ofSeconds(1))
.subscribe(System.out::println);
compared with item 2, timeout in the following code works:
public static void main(String[] args) {
Mono.fromCallable(() -> {
log.info("begin 1");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("return 1");
return "good luck 1";
})
.timeout(Duration.ofMillis(1500l))
.map((s) -> {
log.info("begin 2");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("return 2");
return "good luck 2";
})
.subscribe(System.out::println);
}

Anwser the comment's question, some operator is eager, it will execute at assembly stage. you can use some lazy operator, eg: defer、fromSupplier...
public Mono<?> defaultData() {
return Mono.defer(() -> {
//do Something
return ...
});
}
Here are some demo(https://github.com/echooymxq/reactive-study).

Related

how am i supposed to pull a record from DAO vector?

I'm trying to implement the login page based on Oracle sql using JFrame(swing). I already have inserted IDs and PWs on database. Plus, I've also already defined appropriate -I think- LoginMember method in DAO. Below are the codes for Jframe page and DAO. Please let me know what is wrong with this. I've been struggling with this for the last 5 hours and still have no idea what to do.. HELP!! Sorry if you feel that I have not given enough info to solve this problem.
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strID=tfID.getText();
String strPW=String.valueOf(pwfPW.getPassword());
if(tfID.getText().equals("")) {
JOptionPane.showMessageDialog(Login.this, "Please type your ID");
} else {
dao=new M_DAO();
dao.loginMember(strID,strPW);
if(tfID.getText().equals(dao.loginMember(strID,strPW))) {
JOptionPane.showMessageDialog(Login.this, strID+" : successfully logged in");
}else if(strID ==null && strID.equals(strPW)){
JOptionPane.showMessageDialog(Login.this, "Incorrect ID or PW.");
}else{
System.out.println(10);
}
}
}
});
DAO:
public Vector loginMember(String strID,String strPW) {
Vector items=new Vector();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
conn=DB.hrConn();
String sql="select * from member where strID=? and strPW=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "strID");
pstmt.setString(2, "strPW");
rs=pstmt.executeQuery();
if(rs.next()){
Vector row=new Vector();
row.add("strID");
row.add("strPW");
items.add(row);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt!=null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return items;
}
I wish it would work so bad...
It only shows the correct answer when I type nothing on ID and PW textfields, saying "Please type your ID". It prints out 10 when I type something on those.(just to check which line has an error.) Oh, please let me know if I need to specify something else!

Remote Glassfish JMS lookup

I want to connect to my Glassfish Server at XX.XX.XX.XX:XXXX which is running on a ubuntu machine on our Server.
I want to send messages and then receive them.
My Receiver looks like this:
public JMS_Topic_Receiver(){
init();
}
public List<TextMessage> getCurrentMessages() { return _currentMessages; }
private void init(){
env.put("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBInitialHost", "10.10.32.14");
env.put("org.omg.CORBA.ORBInitialPort", "8080");
try {
ctx = new InitialContext(env); // NamingException
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void subscribeTopic(String topicName, String userCredentials) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
try {
String temp = InetAddress.getLocalHost().getHostName();
topicConnection.setClientID(temp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, userCredentials);
topicSubscriber.setMessageListener(new MyMessageListener());
}
catch(NamingException | JMSException ex)
{
ex.printStackTrace();
}
}
And my Sender looks like this:
public JMS_Topic_Sender(){
init();
}
private void init(){
env.put("java.naming.factory.initial","com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBHost","10.10.32.14");
env.put("org.omg.CORBA.ORBPort","8080");
try {
ctx = new InitialContext(env);
} catch (NamingException e) {
e.printStackTrace();
}
}
public void sendMessage(String message, String topicName) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
if (topicConnectionFactory != null) {
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
TextMessage tm = topicSession.createTextMessage(message);
topicPublisher.send(tm);
topicSession.close();
topicConnection.stop();
topicConnection.close();
}
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}
}
I got most of this code from various tutorials online.
Now when I want to do the lookup aka. -> ctx.lookup("myTopicConnectionFactory");
I get all sorts of errors thrown:
INFO: HHH000397: Using ASTQueryTranslatorFactory
org.omg.CORBA.COMM_FAILURE: FEIN: 00410008: Connection abort vmcid: OMG minor code: 8 completed: Maybe
javax.naming.NamingException: Lookup failed for 'myTopicConnectionFactory' in SerialContext ........
My question here is, how do I do the lookup correctly?
My guess is that my Propertys (env) are incorrect and I need to change thouse, but I dont know to what?
Also, it works if i run my Glassfish localy on my own Computers localhost.
When im using localhost as adress and 8080 as port.

Selenium Testing : If element is not present then exception is not handled by Exception of type NoSuchElementException in Selenium

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.
I have tried this code snippet also.
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
What should I do so that in small span of time it returns true or false.
Another option would be something like
return driver.FindElements(by).length > 0;
I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}
try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
Please try and let me know.......

Not able Scan using redis template

I am trying to use SCAN http://redis.io/commands/scan to iterate over all the keys present in redis. But the Redis template provided by spring do not have any scan() method. Is there any trick to use the above?
Thanks
You can use a RedisCallback on RedisOperations to do so.
redisTemplate.execute(new RedisCallback<Iterable<byte[]>>() {
#Override
public Iterable<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
List<byte[]> binaryKeys = new ArrayList<byte[]>();
Cursor<byte[]> cursor = connection.scan(ScanOptions.NONE);
while (cursor.hasNext()) {
binaryKeys.add(cursor.next());
}
try {
cursor.close();
} catch (IOException e) {
// do something meaningful
}
return binaryKeys;
}
});
Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Cursor<byte[]> cursor = null;
Set<String> keysTmp = new HashSet<>();
try {
cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(keyPrefix + "*").count(10000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(cursor) && !cursor.isClosed()) {
try {
cursor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keysTmp;
});

Progress is not shown in Eclipse wizard window

I am developing an Eclipse plugin that creates a project in the current workspace. I want to show a progress bar in the wizard window (above the next - previous - finish buttons ) to represent the progress of creation. However, when the finish button is pressed, the progress bar is not shown. Below is my code.
#Override
WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
#Override
protected void execute(IProgressMonitor monitor) throws CoreException,
InvocationTargetException, InterruptedException {
monitor.beginTask("Create *** Project", 100);
try {
ProjectUtil.createProject(monitor);
} catch (Exception e) {
} finally {
monitor.done();
}
monitor.done();
}
};
try {
getContainer().run(true, true, op);
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside the createProject(IProgressMonitor monitor) method of class ProjectUtil, I have monitor.worked(someWork) after each operation.
What am I missing?
Try to set setNeedsProgressMonitor(true); in the class, which extends Wizard. Hope this helps.