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();
  
 }
 
}

Friday, 17 June 2016

[Java] How to Indent XML Generated by Transformer

● Not Indent

1
<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b/></a>

● Indent

1
2
3
4
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
 <b/>
</a>


◎ Java Code

1
2
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")

Thursday, 16 June 2016

[Java] How to get Inherited or same class in ClassLoader (클래스로더에 로드된 클래스 중 특정 클래스나 그 클래스를 상속받는 클래스 찾기)


 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
public class DorbaeClassLoaderUtil {
         public static java.util.List< Class< ?>> findInheritedClasses( ClassLoader classLoader, Class< ?> parentClass) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  java.util.List< Class< ?>> filteredClasses = new java.util.LinkedList< Class< ?>>();
  
  Field f = ClassLoader.class.getDeclaredField( "classes");
  f.setAccessible( true);

  Vector< Class< ?>> classes = ( Vector< Class< ?>>)f.get( classLoader);
  int size = classes.size();
  Class< ?> cls = null;
  for ( int ll = 0; ll < size; ll++) {
    try {
     cls = classes.get( ll);
                 if ( parentClass.isAssignableFrom( cls)) {
                  filteredClasses.add( cls);
                 }
             
             } catch ( Exception e) {
              continue;

             } catch ( Error e) {
              continue;
              
             }
  }
  
  return filteredClasses;

 }
 
 public static void main( String[] args) throws Exception {
  A a = new A();
  B b = new B();
  C c = new C();
  
  System.out.println( "=================== All Classes ===================");
  java.util.Vector< Class< ?>> clss = DorbaeClassLoaderUtil.getAllLoadedClasses( Thread.currentThread().getContextClassLoader());
  for ( int ll = 0; ll < clss.size(); ll++) {
   System.out.println( clss.get( ll).getName());
   
  }
  
  System.out.println( "=================== Inherited Classes ===================");
  java.util.List< Class< ?>> clsss = DorbaeClassLoaderUtil.findInheritedClasses( Thread.currentThread().getContextClassLoader(), C.class);
  for ( int ll = 0; ll < clsss.size(); ll++) {
   System.out.println( clsss.get( ll).getName());
   
  }
 }

}

class A extends C {
 public A() {}
}

class B {
 public B() {}
 
}

class C {
 public C() {}
}


[Java] How to get all loaded classes in ClassLoader (클래스로더에 올라간 모든 Class 가져오기)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public static Vector< Class< ?>> getAllLoadedClasses( ClassLoader classLoader) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
 Field f = ClassLoader.class.getDeclaredField( "classes");
 f.setAccessible( true);

 return ( Vector< Class< ?>>)f.get( classLoader);

}
 
public static void main( String[] args) throws Exception {
 DorbaeDateUtil.getCurrentDate();
 DorbaeByteUtil.dos2Unix( "%n".getBytes());
  
 java.util.List< Class< ?>> clss = DorbaeClassLoaderUtil.findInheritedClasses( Thread.currentThread().getContextClassLoader(), Object.class);
 for ( int ll = 0; ll < clss.size(); ll++) {
  System.out.println( clss.get( ll).getName());
  
 }
}


[JDBC] How to find classes implemented java.sql.Drvier in JDBC Driver jar file.(JDBC 드라이버 Jar 파일에서 Drvier Class 찾기)


 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
public static java.util.List< String> findDriverClassNamesInJars( java.io.File[] jarFiles) throws FileNotFoundException, IOException {
  java.util.jar.JarInputStream jarFileInputStream = null;
  java.util.jar.JarEntry jarEntry = null;
  java.net.URLClassLoader ucl = null;
  java.net.URL url = null;
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  Class< ?> baseInClass = java.sql.Driver.class;
  java.util.List< String> classNames = new java.util.ArrayList< String>();
  
  for ( int ll = 0; ll < jarFiles.length; ll++) {
   url = new java.net.URL( "jar:file:" + jarFiles[ ll] + "!/");
   ucl = new URLClassLoader( new java.net.URL[] { url }, classLoader);
   try {
    jarFileInputStream =  new java.util.jar.JarInputStream( new java.io.FileInputStream( jarFiles[ ll]));
  
    while ( ( jarEntry = jarFileInputStream.getNextJarEntry()) != null) {
              if ( jarEntry.getName().endsWith( ".class")) {
                  String classname = jarEntry.getName().replaceAll( "/", "\\.");
                  classname = classname.substring( 0, classname.length() - 6);
                  if ( !classname.contains( "$")) {
                      try {
                          final Class< ?> myLoadedClass = Class.forName( classname, true, ucl);
                          if ( baseInClass.isAssignableFrom( myLoadedClass)) {
                           classNames.add( myLoadedClass.getName());
                          }
                      
                      } catch ( Exception e) {
                       continue;
 
                      } catch ( Error e) {
                       continue;
                       
                      }
                  }
              }
          }
   
   } finally {
    try {
     jarFileInputStream.close();
    } catch ( Exception e) {}
   }
  }
  
  return classNames;
        
 }

Friday, 10 June 2016

[Maria/MySQL] Illegal mix of collations for operation '=' Error Troubleshooting

I met Illegal mix of collations for operation '=' exception when executing join select query.

It is because of this that difference of collation table or column.

1. Check Table Collation

SELECT TABLE_NAME
     , TABLE_COLLATION
  FROM information_schema.`TABLES` T
 WHERE T.table_schema = '<DB_NAME>'
   AND T.table_name = '<TABLE_NAME>'
;
















2. Change Table Collation

ALTER TABLE <DB_NAME>.<TABLE_NAME> DEFAULT CHARACTER SET utf8 COLLATE 'utf8_general_ci';













3. Check Column Collation

SELECT TABLE_NAME
     , COLUMN_NAME
     , DATA_TYPE
     , COLLATION_NAME
  FROM information_schema.`COLUMNS`
  WHERE TABLE_SCHEMA = '<DB_NAME>'
    AND TABLE_NAME = '<TABLE_NAME>'
;






















It is related with character type columns like VARCHAR, CHAR, and so on.



4. Change column collation

ALTER TABLE <DB_NAME>.<TABLE_NAME> modify <COLUMN_NAME> <DATA_TYPE> CHARACTER SET utf8 COLLATE utf8_general_ci;