Wednesday 29 June 2016

[Ubuntu] Setup firewall using UFW

UFW is a default firewall. it is more easier than iptables. But iptables supports more various options and functions for building high-quality service.

1. Set UFW Enable/Disable

#> ufw enable

#> ufw disable

2. Check UFW status

#> ufw status verbose






3. Check default rule

#> ufw show raw



4. Allow/Deny default rule

#> ufw default allow

#> ufw default deny

5. Allow/Deny specific port and protocol

#> ufw allow [port]

#> ufw allow [port]/tcp

#> ufw allow [port]/udp

#> ufw deny[port]

#> ufw deny[port]/tcp

#> ufw deny[port]/udp



[Ubuntu] How to turn off coloring syntax in vi editor

#> vi /etc/vim/vimrc








remove if has("syntax") syntax on end if.

Friday 24 June 2016

[CloudSQL] Getting Started Google Cloud SQL

1. Create new instance

I choose Cloud SQL generation 2. this is more fast and support more disk and more cheaper than generation 1. But, it is beta service yet.


2. Set up resource size



3. Set up options and add network allowed access



4. Set up other options



5. Finished creating instance







6. Set up root password



7. Connect DB using database tool





[Oracle] ORA-00845 : MEMORY TARGET not supported on this system

I used Oracle 11g in CentOS VM image. this image is allocated 16GB memory. But after reducing memory to 8GB, oracle instance was not started.



This error comes up because you tried to use the Automatic Memory Management (AMM) feature of Oracle 11g R2. It seems that your shared memory filesystem (shmfs) is not big enough. In this case, you should increase shmfs.


1. Check shared memory filesystem size

# df -h



2. Remount and increase size

# umount tmpfs
# mount -t tmpfs shmfs -o size=8192m /dev/shm



3. Startup database instance



4. Check parameter related with memory



[Oracle] How to increase line width in SQLPlus

set linesize [SIZE]

Wednesday 22 June 2016

[Windows] How to check Main(Mother) Board model

C:\Users\Administrator>wmic baseboard

Caption ConfigOptions CreationClassName Depth Description Height HostingBoard HotSwappable InstallDate Manufacturer Model Name OtherIdentifyingInfo PartNumber PoweredOn Product Removable Replaceable RequirementsDescription RequiresDaughterBoard SerialNumber SKU SlotLayout SpecialRequirements Status Tag Version Weight Width
Base Board Win32_BaseBoard Base Board TRUE FALSE Dell Inc. Base Board TRUE 0D735T FALSE TRUE FALSE ..CN697029CK0163. OK Base Board A00

[Windows] How to check Memory model

C:\Users\Administrator>wmic momorychip


BankLabel Capacity Caption CreationClassName DataWidth Description DeviceLocator FormFactor HotSwappable InstallDate InterleaveDataDepth InterleavePosition Manufacturer MemoryType Model Name OtherIdentifyingInfo PartNumber PositionInRow PoweredOn Removable Replaceable SerialNumber SKU Speed Status Tag TotalWidth TypeDetail Version
BANK0 4294967296 Physical Memory Win32_PhysicalMemory 64 Physical Memory DIMM0 8 1 0 Samsung 1 Physical Memory M378B5273CH0-CH9 1 002D7AA2 1333 Physical Memory 0 64 128
BANK1 4294967296 Physical Memory Win32_PhysicalMemory 64 Physical Memory DIMM1 8 1 0 Samsung 1 Physical Memory M378B5273DH0-CH9 1 6468CE66 1333 Physical Memory 1 64 128
BANK2 4294967296 Physical Memory Win32_PhysicalMemory 64 Physical Memory DIMM2 8 1 0 Samsung 1 Physical Memory M378B5273DH0-CH9 1 00421459 1333 Physical Memory 2 64 128
BANK3 4294967296 Physical Memory Win32_PhysicalMemory 64 Physical Memory DIMM3 8 1 0 Samsung 1 Physical Memory M378B5273DH0-CH9 1 6555173D 1333 Physical Memory 3 64 128

[Utility] hiltie.me - Make code like Java, Shell, SQL, HTML etc to HTML code

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.

http://hilite.me/

[Java] What is difference between Class.forName() and Class.forName().newInstance()

In JavaDoc, calling Class.forName( String) returns the Class object associated with the class or interface with the given string name.
On the other hand, calling Class.forName( String).newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.
In other words, Class.forName( String CLASS_NAME) is equivalent to new CLASS_NAME()
(Referenced by http://stackoverflow.com/questions/2092659/what-is-the-difference-between-class-forname-and-class-forname-newinstanc)


Class.forName( String) is not create instance, but call static block in class. On the other hand, newInstance() creates instance. The result of below code will make you more understandable.

Class pe.dorbae.test.Driver
 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
package pe.dorbae.test;

/*
 * ************************************************************************************
 *
 * Driver.java
 * 
 * ************************************************************************************
 * 
 * @version 1.0.00 2016-06-21 dorbae Initialize
 * @since 2016-06-21
 * @author dorbae
 * 
 * ************************************************************************************
 */
public class Driver {
 
 static {
  System.out.println( "Static Block");
 }

 public Driver() {
  System.out.println( "Constructure");
  
 }
 
 public void test() {
  System.out.println( "test");
 }
 
}


Calling Class.forName( String) Code and Result
1
2
3
4
5
6
public class Test {
 public static void main(String[] args) throws Exception {
  Class.forName( "pe.dorbae.test.Driver"); // equivalent to Class.forName( "pe.dorbae.test.Driver", true, this.getClass().getClassLoader())
  
 }
}




Calling Class.forName( String, false, ClassLoader) Code and Result
1
2
3
4
5
6
public class Test {
 public static void main(String[] args) throws Exception {
  Class.forName( "pe.dorbae.test.Driver", false, Thread.currentThread().getContextClassLoader());
  
 }
}



Calling Class.forName( String).newInstance()
1
2
3
4
5
6
public class Test {
 public static void main(String[] args) throws Exception {
  Class.forName( "pe.dorbae.test.Driver").newInstance(); // equivalent to Class.forName( "pe.dorbae.test.Driver", true, this.getClass().getClassLoader())
  
 }
}




Calling Class.forName( String, false, ClassLoader).newInstance()
1
2
3
4
5
6
public class Test {
 public static void main(String[] args) throws Exception {
  Class.forName( "pe.dorbae.test.Driver", false, Thread.currentThread().getContextClassLoader()).newInstance();
  
 }
}




When use JDBC driver, we usually call Class.forName( String driverClass). Class.forName( String) is not create JDBC Driver Object instance. If so, how to use driver object?

JDBC Driver generally make driver class that implements java.sql.Driver like this.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public final class <DriverClass> implements java.sql.Driver {

    static {
        try {
            DriverManager.registerDriver(new <DriverClass>());
        } catch (SQLException e) {
            throw new RuntimeException("Could not register driver", e);
        }
    }

    .
    .
    .
    
}

Therefore, if you call Class.forName( String driverClass), static block is called and it register new driver class instance.

However, it is different when JDBC Driver class is loaded in another. DriverManager.getConnection() finds driver object in Thread.current.getContextClassLoader().  DriverManager can't not find driver object, because it is actually loaded in another class loader.

In this case, you should like this.
1
2
java.sql.Driver driver = ( java.sql.Driver)Class.forName( DriverClassName, true, AnotherClassLoader).newInstance();
java.sql.Connection conn = driver.connect( <URL>, <Properties>);

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