Tuesday, 21 June 2016

[Java] Mobile to Desktop URL Transfer using Topic Pub/Sub

When I opened web content and read it in mobile web browser, I sometimes have wanted to read it in desktop web browser.
So I made background program that receive URL from mobile app and open web content in desktop browser.

An architecture of this program is like below.




I have been using iPhone, but I can't develop iOS applications. So I use  free app MQTTTest that was developed by Kwang il Cho. (https://appsto.re/kr/CxN--.i)

Mobile







Desktop




Java Code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package pe.dorbae.url.tranfer;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.commons.lang3.exception.ExceptionUtils;

/*
 * ************************************************************************************
 *
 * URLTranfer.java
 * 
 * ************************************************************************************
 * 
 * @version 1.0.00 2016-06-21 dorbae Initialize
 * @since 2016-06-21
 * @author dorbae
 * 
 * ************************************************************************************
 */
public class URLTranfer implements Runnable {
 
 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger( URLTranfer.class);
 
 private static final String OS = System.getProperty( "os.name", "Unknown");
 private static final String[] COMMAND_WINDOW = new String[] { "rundll32", "url.dll,FileProtocolHandler", null};
 private static final String[] COMMAND_MAC = new String[] { "open", null};
 private static final String[] COMMAND_UNIX = new String[] { "xdg-open", null};
 private static String[] command = null;
 static  {
  String osName = OS.toLowerCase();
  if ( osName.indexOf( "win") >= 0)
   command = COMMAND_WINDOW;
  else if ( osName.indexOf( "nux") >= 0)
   command = COMMAND_MAC;
//  else if ( osName.indexOf( "aix") >= 0)
//   osType =  OSType.Aix;
//  else if ( osName.indexOf( "nix") >= 0)
//   osType =  OSType.Unix;
//  else if ( osName.indexOf( "mac") >= 0)
//   osType =  OSType.MacOS;
//  else if ( osName.indexOf( "darwin") >= 0)
//   osType =  OSType.MacOS;
//  else if ( osName.indexOf( "sunos") >= 0)
//   osType =  OSType.Solaris;
  else           // Affiliation with Unix
   command = COMMAND_UNIX;
  
 }
 
 private static String[] envrionmentArray = null;
 static {
  java.util.Map< String, String> env = System.getenv();
  java.util.Iterator< java.util.Map.Entry< String, String>> iterator = env.entrySet().iterator();
  java.util.Map.Entry< String, String> entry = null;
  envrionmentArray = new String[ env.size()];
  int ll = 0;
  while ( iterator.hasNext()) {
   entry = iterator.next();
   envrionmentArray[ ll++] = String.format( "%s=%s", entry.getKey(), entry.getValue());
   
  }
 }
 
 private Thread mThread = null;
 private boolean mIsRunning = false;
 
 private String mBrokerUrl = null;
 private String mTopicName = null;
 private String mClientID = null;
 private String mHostname = null;
 private javax.jms.Connection mConn = null;
 private javax.jms.Session mSession = null;
 private javax.jms.MessageConsumer mSubscriber = null;
 private javax.jms.Topic mTopic = null;

 public URLTranfer(String brokerUrl, String topicName) {
  this.mBrokerUrl = brokerUrl;
  this.mTopicName = topicName;
  try {
   this.mHostname = InetAddress.getLocalHost().getHostName();
  
  } catch ( UnknownHostException e) {
   this.mHostname = "Unknown";
   
  }
  
  this.mClientID = String.format( "iSharkClient.%s.URLTransfer", this.mHostname);
  
 }
 
 @Override
 public void run() {
  LOG.info( "Start URLTranfer.");
  try {
   this.mConn.start();
   this.mSubscriber.setMessageListener( new MessageListener() {
    @Override
    public void onMessage( Message msg) {
     try {
      String url = null;
      
      if ( msg instanceof javax.jms.BytesMessage) {
       javax.jms.BytesMessage byteMessage = ( javax.jms.BytesMessage) msg;
       byte[] payload = new byte[ ( int)byteMessage.getBodyLength()];
       byteMessage.readBytes( payload);
       url = new String( payload, "UTF8");
       
      } else if ( msg instanceof javax.jms.TextMessage) {
       javax.jms.TextMessage textMessage = ( javax.jms.TextMessage)msg;
       url = textMessage.getText();
       
      }
      LOG.info( "url={}", url);
      
      if ( java.awt.Desktop.isDesktopSupported()) {
       LOG.debug( "Deskop Supported");
       java.awt.Desktop.getDesktop().browse( new java.net.URI( url));
      
      } else {
       Runtime runtime = Runtime.getRuntime();
       command[ command.length - 1] = url;
       runtime.exec( command, envrionmentArray, null);
        
      }
      
     } catch ( Exception e) {
      LOG.warn( "Failed to subscribe url and open browser.\n{}", ExceptionUtils.getStackTrace( e));
      
     }
    }
   });

  } catch ( JMSException e) {
   LOG.error( "Error in DataTopicSubWorker.\n{}", ExceptionUtils.getStackTrace( e));
   
  }
 }
 
 public void start() {
  this.connectBroker();
  if ( !this.mIsRunning && this.mThread == null) {
   this.mIsRunning = true;
   this.mThread = new Thread( this);
   this.mThread.setName( "URLTransfer");
   this.mThread.start();
   
  } else {
   LOG.info( "Already running...");
   
  }
  
 }
 
 public void stop() {
  this.disconnectBroker();
  this.mIsRunning = false;
  this.mThread = null;
  
 }
 
 private void disconnectBroker() {
  try {
   if ( this.mSubscriber != null)
    this.mSubscriber.close();
   if ( this.mSession != null)
    this.mSession.close();
   if ( this.mConn != null) {
    this.mConn.stop();
    this.mConn.close();
    
   }
  
  } catch ( Exception ex) {}
 }
 
 
 private boolean connectBroker() {
  try {
   LOG.info( "Initialize URLTranfer.[BrokerURL={}, Topic={}, ClientID={}]", this.mBrokerUrl, this.mTopicName, this.mClientID);
   
   Properties jmsProps = new Properties();
   jmsProps.put( javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
   jmsProps.put( javax.naming.Context.PROVIDER_URL, this.mBrokerUrl);
   
   javax.naming.InitialContext jndi = new javax.naming.InitialContext( jmsProps);
   javax.jms.ConnectionFactory connectionFactory = ( javax.jms.ConnectionFactory) jndi.lookup( "ConnectionFactory");
   this.mConn = connectionFactory.createConnection();
   this.mConn.setClientID( this.mClientID);
   this.mSession = this.mConn.createSession( false, Session.AUTO_ACKNOWLEDGE); // transacted, acknowolegeMode
   this.mTopic = this.mSession.createTopic( this.mTopicName);
   this.mSubscriber = this.mSession.createConsumer( this.mTopic);
   
   return true;
   
  } catch ( Exception e) {
   LOG.error( "Failed to initialize URLTranfer.\n{}", ExceptionUtils.getStackTrace( e));
   this.disconnectBroker();
   
   return false;
   
  }
  
 }
 
 public static void main( String[] args) {
  org.apache.log4j.PropertyConfigurator.configure( "log4j.properties");
  URLTranfer transfer = new URLTranfer( "nio://192.168.0.85:61616?wireFormat.maxInactivityDuration=0", "Url.Transfer");
  Runtime.getRuntime().addShutdownHook( new Thread( new ShutdownHook( transfer)));
  transfer.start();
  
 }

}

class ShutdownHook implements Runnable {
 private URLTranfer mURLTransfer = null;
 
 public ShutdownHook( URLTranfer urlTransfer) {
  this.mURLTransfer = urlTransfer;
  
 }
 
 @Override
 public void run() {
  this.mURLTransfer.stop();
  
 }
 
}

No comments:

Post a Comment