1 10 11 package org.mule.providers; 12 13 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger; 14 15 import org.mule.config.ExceptionHelper; 16 import org.mule.config.i18n.Message; 17 import org.mule.config.i18n.Messages; 18 import org.mule.umo.provider.UMOConnectable; 19 20 25 26 public class SimpleRetryConnectionStrategy extends AbstractConnectionStrategy 27 { 28 29 private static final ThreadLocal count = new ThreadLocal () 30 { 31 protected Object initialValue() 32 { 33 return new AtomicInteger(0); 34 } 35 }; 36 37 private int retryCount = 2; 38 private long frequency = 2000; 39 40 public void doConnect(UMOConnectable connectable) throws FatalConnectException 41 { 42 while (true) 43 { 44 int currentCount = ((AtomicInteger)count.get()).incrementAndGet(); 45 46 try 47 { 48 connectable.connect(); 49 if (logger.isDebugEnabled()) 50 { 51 logger.debug("Successfully connected to " + getDescription(connectable)); 52 } 53 break; 54 } 55 catch (InterruptedException ie) 56 { 57 throw new FatalConnectException(new Message(Messages.RECONNECT_STRATEGY_X_FAILED_ENDPOINT_X, 60 getClass().getName(), getDescription(connectable)), ie, connectable); 61 } 62 catch (Exception e) 63 { 64 if (currentCount == retryCount) 65 { 66 throw new FatalConnectException(new Message( 67 Messages.RECONNECT_STRATEGY_X_FAILED_ENDPOINT_X, getClass().getName(), 68 getDescription(connectable)), e, connectable); 69 } 70 71 if (logger.isErrorEnabled()) 72 { 73 StringBuffer msg = new StringBuffer (512); 74 msg.append("Failed to connect/reconnect on endpoint: ").append( 75 getDescription(connectable)); 76 Throwable t = ExceptionHelper.getRootException(e); 77 msg.append(". Root Exception was: ").append(ExceptionHelper.writeException(t)); 78 logger.error(msg.toString(), e); 79 } 80 81 if (logger.isInfoEnabled()) 82 { 83 logger.info("Waiting for " + frequency + "ms before reconnecting. Failed attempt " 84 + currentCount + " of " + retryCount); 85 } 86 87 try 88 { 89 Thread.sleep(frequency); 90 } 91 catch (InterruptedException e1) 92 { 93 throw new FatalConnectException(new Message( 94 Messages.RECONNECT_STRATEGY_X_FAILED_ENDPOINT_X, getClass().getName(), 95 getDescription(connectable)), e, connectable); 96 } 97 } 98 } 99 } 100 101 104 public synchronized void resetState() 105 { 106 ((AtomicInteger)count.get()).set(0); 107 } 108 109 public int getRetryCount() 110 { 111 return retryCount; 112 } 113 114 public void setRetryCount(int retryCount) 115 { 116 this.retryCount = retryCount; 117 } 118 119 public long getFrequency() 120 { 121 return frequency; 122 } 123 124 public void setFrequency(long frequency) 125 { 126 this.frequency = frequency; 127 } 128 } 129 | Popular Tags |