Shared info of IoT & Cloud, Banking, Angular Wicket, Spring Reactive, AI, Flutter, E-comm, Java Telecomm and More.

Tuesday, February 21, 2017

Consuming a RESTful Web Service with Spring for Android

This Getting Started guide walks you through the process of building an application that uses Spring for Android's RestTemplate to consume a Spring MVC-based RESTful web service.

Compile và chạy ứng dụng rest server

You will build an Android client that consumes a Spring-based RESTful web service. Specifically, the client will consume the service created in Building a RESTful Web Servce.
Chạy spring boot rest: java -jar gs-rest-service-0.1.0.jar
The Android client will be accessed through an Android emulator, and will consume the service accepting requests at:
http://192.168.1.3:8080/greeting
The service will respond with a JSON representation of a greeting:
{"id":1,"content":"Hello, World!"}
The Android client will render the ID and content into a view.

Monday, February 20, 2017

Spring for Android Showcase

Introduction

This showcase includes an Android client and a Spring MVC server. Together these illustrate the interaction of the client and server when using Spring for Android. This Android project requires set up of the Android SDK. See the main README at the root of this repository for more information about configuring your environment.

Wednesday, December 7, 2016

JavaScript căn bản - part 1

1. Javascript là gì?

Javascript là ngôn ngữ lập trình của HTML và Web  chạy trên browser dưới dạng các script.


A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
  • Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
    The window object represents an open window in a browser.
  • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
  • Form object − Everything enclosed in the <form>...</form> tags sets the form object.
  • Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes. They have events, attributes, styles.
Here is a simple hierarchy of a few important objects -

Closures: Một số link tham khảo về Closures là

2. Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:
   1. HTML to define the content of web pages
   2. CSS to specify the layout of web pages
   3. JavaScript to program the behavior of web pages

3. Ví dụ 1: JavaScript can change HTML content

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html> 

4. Ví dụ 2: JavaScript can change CSS style

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>


</body>

</html> 

. Ví dụ 3: JavaScript can change HTML attributes

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>

</html>
<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>


</body>

</html> 
Tương tự, để hiển thị phần tử đang ở trạng thái hidden thì dùng đặt style.display='block'

7. Ví dụ 5: JavaScript với sự kiện onchange

<html>
<head>
<script type="text/javascript"> 
function updateInputValue(ishVal){
// ID of current element
var elementID = document.getElementById('CurrentUnitId').value;
document.getElementById(elementID).value = ishVal;
}

function updateTextBox(textboxID) {
//var txtID = document.getElementById(textboxID);
var orgID = document.getElementById('organizationSearchName');
orgID.value = '';
document.getElementById('CurrentUnitId').value = textboxID;
var tempElement = document.createElement("markActionURL");
tempElement.type = "hidden";
tempElement.value = '${actionUrl}';
document.getElementById('CommonTagsTreeChooserUnitID').appendChild(tempElement);
openTreeChooserDialog('organizationSearch','${actionUrl}');

}

function updateInput(ish){
   document.getElementById("fieldname").value = ish;
}

</script>

</head>
<body>
<input type="text" name="fieldname" id="fieldname" />  
<input type="text" name="thingy" onchange="updateInput(this.value)" />
</body>

</html>

this.value là value của phần tử đang xét.

8. Ví dụ 6: JavaScript chạy trưc tiếp một hàm cùng với trang web

Dùng đoạn mã sau nhúng vào body của trang html:
<script type="text/javascript">javascript:changeColumnWidthR2();</script>

khi load trang web, browser sẽ gọi hàm changeColumnWidthR2()。

Nội dung của hàm changeColumnWidthR2
<script type="text/javascript">
function changeColumnWidthR2(){
    $('#ColumnLabelEmployeeName').attr('style','width: 15%');
    $('#ColumnLabelCompany).attr('style','width: 35%');
    $('#ColumnLabelPosition').attr('style','width: 15%');
    $("#Output_Other_Help").html("<font color='red'><center>Click checkbox để chọn organization.</center></font>");
}
</script>


Ngoài ra, có thể gọi những hàm javascript mà không cần tới prefix javascript:
ví dụ:
<script>
    focusTextboxElement("frmSearch");
    pressSearchButton();

</script>

9. Điều kiện true/false với 1 biến số

var inputValue = null | undefined | NaN | empty string ("") | 0 | false
if(inputValue)
  alert('false');
else
  alert('true value');
=> trả về giá trị false cho biến số inputValue.

10. What does this mean: "undefined object property"?


What does this mean: "undefined object property"?
Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }
Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false
We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

11. JSON - check an Integer variable is valid

if(!(zoneId % 1 === 0)) {
    isZoneIdValid = false;
    result.code = 422;
    result.message = "zoneid = " + zoneId + " khong hop le";
}

if(jsonInput.maxItems >= 0)
    maxItems = jsonInput.maxItems;

12. JSON - check empty in javascript

- function isEmpty(value){
    return (typeof value === "undefined" || value === null || value.length === 0 || value === "undefined");
}
- hasOwnProperty
if(jsonInput.hasOwnProperty('maxItems')) {}


Tuesday, November 29, 2016

Struts2 vs Struts1

1. Khái quát chung


2. Struts1


The framework just uses one instance of it and only one instance is used to process all incoming requests, care must be taken not to do something with in the Action class that is not thread safe. From the javadoc:
Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind:
  1. Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action.
  2. Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.

This is what the official Apache Struts page says :
Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.

3. Struts2




4. Tham khảo:

Struts 2 Architecture and Flow
Introduction to the Struts Web Framework
Overview of Struts
Struts document home
Struts Architecture and life-cycle
Struts1 document

JavaDB Connection pool

From Wikipedia, the free encyclopedia

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required.[citation needed] Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.

Applications

Web-based and enterprise applications use an application server to handle connection pooling. Dynamic web pages without connection pooling open connections to database services as required and close them when the page is done servicing a particular request. Pages that use connection pooling, on the other hand, maintain open connections in a pool. When the page requires access to the database, it simply uses an existing connection from the pool, and establishes a new connection only if no pooled connections are available. This reduces the overhead associated with connecting to the database to service individual requests.
Local applications that need frequent access to databases can also benefit from connection pooling. Open connections can be maintained in local applications that don't need to service separate remote requests like application servers, but implementations of connection pooling can become complicated. A number of available libraries implement connection pooling and related SQL query pooling, simplifying the implementation of connection pools in database-intensive applications.
Administrators can configure connection pools with restrictions on the numbers of minimum connections, maximum connections and idle connections to optimize the performance of pooling in specific problem contexts and in specific environments.

Database support

Connection pooling is supported by IBM DB2,[1] Microsoft SQL Server,[2] Oracle,[3] MySQL,[4] and PostgreSQL.[5]

How to configure the C3P0 connection pool in Hibernate

Connection Pool
Connection pool is good for performance, as it prevents Java application create a connection each time when interact with database and minimizes the cost of opening and closing connections.
Hibernate comes with internal connection pool, but not suitable for production use. In this tutorial, we show you how to integrate third party connection pool – C3P0, with Hibernate.

1. Get hibernate-c3p0.jar

To integrate c3p0 with Hibernate, you need hibernate-c3p0.jar, get it from JBoss repository.
File : pom.xml
<project ...>

 <repositories>
  <repository>
   <id>JBoss repository</id>
   <url>http://repository.jboss.org/nexus/content/groups/public/</url>
  </repository>
 </repositories>

 <dependencies>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

  <!-- Hibernate c3p0 connection pool -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-c3p0</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

 </dependencies>
</project>

2. Configure c3p0 properties

To configure c3p0, puts the c3p0 configuration details in “hibernate.cfg.xml“, like this :
File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:MKYONG</property>
  <property name="hibernate.connection.username">mkyong</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">MKYONG</property>
  <property name="show_sql">true</property>

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

  <mapping class="com.mkyong.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
  1. hibernate.c3p0.min_size – Minimum number of JDBC connections in the pool. Hibernate default: 1
  2. hibernate.c3p0.max_size – Maximum number of JDBC connections in the pool. Hibernate default: 100
  3. hibernate.c3p0.timeout – When an idle connection is removed from the pool (in second). Hibernate default: 0, never expire.
  4. hibernate.c3p0.max_statements – Number of prepared statements will be cached. Increase performance. Hibernate default: 0 , caching is disable.
  5. hibernate.c3p0.idle_test_period – idle time in seconds before a connection is automatically validated. Hibernate default: 0
Note
For detail about hibernate-c3p0 configuration settings, please read this article.

Understanding Java Database Connection Pooling Properties

Basic properties controlling pooling behaviour.
PropertyExplanation
minpoolMinimum number of connections that should be held in the pool.
maxpoolMaximum number of connections that may be held in the pool.
maxsizeMaximum number of connections that can be created for use.
idleTimeoutThe idle timeout for connections (seconds).
  
Bean properties supported by snaq.db.DBPoolDataSource (can also be specified via snaq.db.DBPoolDataSourceFactory).
PropertyDescription
nameName of the DataSource, which is also used to assign a ConnectionPool name.
descriptionDescription for the DataSource.
driverClassNameFully-qualified class name of JDBC Driver to use.
urlJDBC URL to connect to the database.
userUsername for database connections.
passwordPassword for database connections.
passwordDecoderClassNameFully-qualified class name of snaq.db.PasswordDecoder implementation to use.
(It must have a public no-argument constructor).
minPoolMinimum number of pooled connections to maintain.
maxPoolMaximum number of pooled connections to maintain.
maxSizeMaximum number of connection that can be created.
idleTimeoutIdle timeout of pooled connections (seconds).
loginTimeoutTimeout for database connection attempts (seconds).
validatorClassNameFully-qualified class name of snaq.db.ConnectionValidator implementation to use.
(It must have a public no-argument constructor).
validatorQuery*Query string to use for validation, if validatorClassName not specified.
This is passed to a snaq.db.SimpleQueryValidator instance.

Hibernate-Supported Connection Pools

Table 10.1. Hibernate-Supported Connection Pools

c3p0
Distributed with Hibernate
Apache DBCP
Apache Pool
Proxool
JDBC Pooling Wrapper

Tuesday, November 22, 2016

Đọc ghi tệp (file) trong java

1. ByteArrayOutputStream
InputStream in = context.openFileInput("datafile.txt");
ByteArrayOutputStream bais = new ByteArrayOutputStream();
byte[] bytes = new byte[8192];
for(int len; (lne = in.read(bytes) > 0;)
   bais.write(bytes, 0, len);
in.close();
return bais.toByteArray();

Popular Posts

Blog Archive