├── MapSort ├── README.md └── src │ └── com │ └── hmkcode │ ├── MapSort.java │ ├── Test.java │ └── ValueComparator.java ├── castor-xml-object ├── .classpath ├── article.xml ├── mapped_article.xml ├── mapping.xml ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ ├── AppMapping.java │ └── vo │ └── Article.java ├── gson-json-java ├── .classpath ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ └── vo │ └── Article.java ├── itext-create-pdf ├── .classpath ├── helloworld.pdf ├── pagesettings.pdf ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── HelloWorld.java │ └── PageSettings.java ├── itext-java-html-pdf ├── .classpath ├── index.html ├── java.png ├── pom.xml ├── src │ └── main │ │ └── java │ │ └── com │ │ └── hmkcode │ │ └── App.java └── style.css ├── itext-java-pdf-table ├── .classpath ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ ├── Style.java │ └── TableBuilder.java ├── jackson-json-java ├── .classpath ├── article.json ├── articles.json ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ └── vo │ └── Article.java ├── java-async-servlet ├── .classpath ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ ├── AsyncServlet.java │ │ └── SyncServlet.java │ └── webapp │ ├── WEB-INF │ └── web.xml │ ├── bootstrap │ ├── css │ │ └── bootstrap.css │ ├── img │ │ ├── glyphicons-halflings-white.png │ │ └── glyphicons-halflings.png │ └── js │ │ └── bootstrap.min.js │ ├── index.html │ └── js │ ├── jquery.1.9.1.min.js │ └── myfunctions.js ├── java-combinations ├── Combination.java ├── README.md └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── ForwardBackward.java │ ├── Recursive.java │ └── Shifting.java ├── java-excel-poi ├── .classpath ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ └── poi │ ├── AppRead.java │ └── AppWrite.java ├── java-inputstream-string ├── .classpath ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ └── InputStreamToString.java ├── java-jasper ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ ├── App.java │ │ └── Country.java │ └── resources │ └── report.jrxml ├── java-lambda ├── README.md ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── App.java │ ├── Button.java │ └── OnClickListener.java ├── java-list-map ├── .classpath ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── hmkcode │ ├── ListApp.java │ ├── MapApp.java │ └── vo │ └── Person.java ├── java-servlet-json ├── .classpath ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ ├── JSONServlet.java │ │ └── vo │ │ └── Article.java │ └── webapp │ ├── bootstrap │ ├── css │ │ └── bootstrap.css │ ├── img │ │ ├── glyphicons-halflings-white.png │ │ └── glyphicons-halflings.png │ └── js │ │ └── bootstrap.min.js │ ├── index.html │ └── js │ ├── jquery.1.9.1.min.js │ └── myfunctions.js ├── java-simple-text-file-reader └── src │ └── main │ └── java │ └── com │ └── hmkcode │ └── TextFileReader.java ├── java-spi ├── java-spi-api │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── hmkcode │ │ └── api │ │ ├── MyService.java │ │ └── MyServiceProviderInterface.java ├── java-spi-app │ ├── lib │ │ ├── java-spi-api-1.0-SNAPSHOT.jar │ │ └── java-spi-impl1-1.0-SNAPSHOT.jar │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── hmkcode │ │ └── app │ │ ├── App.java │ │ └── MyServiceLoader.java └── java-spi-impl1 │ ├── lib │ └── java-spi-api-1.0-SNAPSHOT.jar │ ├── pom.xml │ └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ └── impl │ │ ├── MyServiceImpl1.java │ │ └── MyServiceProviderImpl1.java │ └── resources │ └── META-INF │ └── services │ └── com.hmkcode.api.MyServiceProviderInterface ├── java-stream └── src │ └── main │ └── java │ └── com │ └── hmkcode │ └── App.java ├── java-unzip └── src │ └── main │ └── java │ └── com │ └── hmkcode │ └── Unzip.java ├── junit-exception ├── .classpath ├── pom.xml └── src │ └── test │ └── java │ └── com │ └── hmkcode │ └── AppTest.java ├── mybatis-insert-generatedkey ├── .classpath ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── hmkcode │ │ │ └── spring │ │ │ └── mybatis │ │ │ ├── App.java │ │ │ ├── mapper │ │ │ └── Mapper.java │ │ │ ├── service │ │ │ └── Service.java │ │ │ └── vo │ │ │ └── MyObject.java │ └── resources │ │ ├── com │ │ └── hmkcode │ │ │ └── spring │ │ │ └── mybatis │ │ │ ├── mapper │ │ │ └── Mapper.xml │ │ │ └── mybatis-config.xml │ │ ├── schema.sql │ │ ├── spring-config.xml │ │ └── test-data.sql │ └── test │ └── java │ └── com │ └── hmkcode │ └── spring │ └── mybatis │ └── AppTest.java ├── servlet-file-upload ├── .classpath ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ ├── FileUploadServlet.java │ │ ├── MultipartRequestHandler.java │ │ └── vo │ │ └── FileMeta.java │ └── webapp │ ├── WEB-INF │ └── web.xml │ ├── bootstrap │ ├── css │ │ └── bootstrap.css │ ├── img │ │ ├── glyphicons-halflings-white.png │ │ └── glyphicons-halflings.png │ └── js │ │ └── bootstrap.min.js │ ├── css │ ├── dropzone.css │ ├── mystyle.css │ └── style.css │ ├── img │ ├── facebook.png │ ├── gae-logo.png │ ├── googleplus.png │ ├── tech-stack.jpg │ └── twitter.png │ ├── index.html │ └── js │ ├── jquery.1.9.1.min.js │ ├── jquery.fileupload.js │ ├── jquery.iframe-transport.js │ ├── myuploadfunction.js │ └── vendor │ └── jquery.ui.widget.js ├── simple-junit ├── .classpath ├── .project ├── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── hmkcode │ │ │ └── junit │ │ │ └── Math.java │ └── test │ │ └── java │ │ └── com │ │ └── hmkcode │ │ └── junit │ │ └── MathTest.java └── target │ ├── classes │ └── com │ │ └── hmkcode │ │ └── junit │ │ └── Math.class │ ├── surefire-reports │ ├── TEST-com.hmkcode.junit.MathTest.xml │ └── com.hmkcode.junit.MathTest.txt │ └── test-classes │ └── com │ └── hmkcode │ └── junit │ └── MathTest.class ├── webservlet-annotation ├── .classpath ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ └── MyServlet.java │ └── webapp │ ├── WEB-INF │ └── web.xml │ └── index.jsp ├── websocket-java-api ├── websocket-app-client │ ├── .classpath │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── hmkcode │ │ ├── App.java │ │ └── MyClient.java └── websocket-glassfish-server │ ├── .classpath │ ├── pom.xml │ └── src │ └── main │ ├── java │ └── com │ │ └── hmkcode │ │ └── MyServerEndpoint.java │ └── webapp │ ├── WEB-INF │ └── web.xml │ ├── bootstrap │ └── css │ │ └── bootstrap.min.css │ ├── index.htm │ └── websocket.js └── xstream-java-xml ├── .classpath ├── pom.xml └── src └── main └── java └── com └── hmkcode ├── App.java └── vo └── Article.java /MapSort/README.md: -------------------------------------------------------------------------------- 1 | SORT JAVA MAP BY KEYS AND VALUES 2 | -------------------------------- 3 | 4 | * "Key,Value" order in Java HashMap is not guaranteed. 5 | * Sorting a Map type class by "keys" is given by TreeMap, just TreeMap.putAll(map) will return sorted map by keys. 6 | * Sorting a Map by "values" needs one more step, we need to define a Comparator that compares values to each other. 7 | 8 | -------------------------------------------------------------------------------- /MapSort/src/com/hmkcode/MapSort.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | import java.util.Map; 5 | import java.util.TreeMap; 6 | 7 | public class MapSort { 8 | 9 | public static Map sortByValue(Map unsortedMap){ 10 | Map sortedMap = new TreeMap(new ValueComparator(unsortedMap)); 11 | sortedMap.putAll(unsortedMap); 12 | return sortedMap; 13 | } 14 | public static Map sortByKey(Map unsortedMap){ 15 | Map sortedMap = new TreeMap(); 16 | sortedMap.putAll(unsortedMap); 17 | return sortedMap; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MapSort/src/com/hmkcode/Test.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class Test { 8 | public static void main(String[] args){ 9 | 10 | 11 | Map map = new HashMap(); 12 | 13 | //*value Class should implements the Comparable interface 14 | //*String implements Comparable by default. 15 | 16 | map.put("Z", "3"); 17 | map.put("D", "4"); 18 | map.put("A", "1"); 19 | map.put("B", "2"); 20 | map.put("F", "6"); 21 | map.put("E", "5"); 22 | 23 | System.out.println("Unsorted Map: "+map); 24 | System.out.println("Sorted Map By Values: "+MapSort.sortByValue(map)); 25 | System.out.println("Sorted Map By Keys: "+MapSort.sortByKey(map)); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /MapSort/src/com/hmkcode/ValueComparator.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.Comparator; 4 | import java.util.Map; 5 | 6 | public class ValueComparator implements Comparator { 7 | 8 | Map map; 9 | 10 | public ValueComparator(Map map){ 11 | this.map = map; 12 | } 13 | public int compare(Object keyA, Object keyB){ 14 | 15 | Comparable valueA = (Comparable) map.get(keyA); 16 | Comparable valueB = (Comparable) map.get(keyB); 17 | 18 | System.out.println(valueA +" - "+valueB); 19 | 20 | return valueA.compareTo(valueB); 21 | 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /castor-xml-object/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /castor-xml-object/article.xml: -------------------------------------------------------------------------------- 1 | 2 |
3 | Java 4 | Java 5 | Castor 6 | XML 7 | Marshalling 8 | Unmarshalling 9 | http://hmkcode.com/castor-java-object-xml 10 | Castor - Java Object to XML & XML to Object Mapping 11 |
-------------------------------------------------------------------------------- /castor-xml-object/mapped_article.xml: -------------------------------------------------------------------------------- 1 | 2 |
3 | http://hmkcode.com/castor-java-object-xml 4 | Java 5 | Java 6 | Castor 7 | XML 8 | Marshalling 9 | Unmarshalling 10 |
-------------------------------------------------------------------------------- /castor-xml-object/mapping.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /castor-xml-object/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | castor-xml-object 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | castor-xml-object 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | 20 | org.codehaus.castor 21 | castor 22 | 1.2 23 | 24 | 25 | xerces 26 | xercesImpl 27 | 2.8.1 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /castor-xml-object/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileReader; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.util.LinkedList; 7 | 8 | import org.exolab.castor.xml.MarshalException; 9 | import org.exolab.castor.xml.Marshaller; 10 | import org.exolab.castor.xml.Unmarshaller; 11 | import org.exolab.castor.xml.ValidationException; 12 | 13 | import com.hmkcode.vo.Article; 14 | 15 | public class App 16 | { 17 | public static void main( String[] args ) 18 | { 19 | 20 | try { 21 | 22 | //( 1 ) OBJECT --> XML 23 | FileWriter writer = new FileWriter("article.xml"); 24 | Marshaller.marshal(createArticle(), writer); 25 | writer.close(); 26 | 27 | 28 | //( 2 ) XML --> OBJECT 29 | FileReader reader = new FileReader("article.xml"); 30 | Article article = (Article) Unmarshaller.unmarshal(Article.class, reader); 31 | 32 | System.out.println(article); 33 | 34 | 35 | } catch (IOException e) { 36 | e.printStackTrace(); 37 | } catch (MarshalException e) { 38 | e.printStackTrace(); 39 | } catch (ValidationException e) { 40 | e.printStackTrace(); 41 | } 42 | 43 | } 44 | 45 | public static Article createArticle(){ 46 | Article article = new Article(); 47 | 48 | article.setTitle("Castor - Java Object to XML & XML to Object Mapping"); 49 | article.setUrl("http://hmkcode.com/castor-java-object-xml"); 50 | article.addCategory("Java"); 51 | article.addTag("Java"); 52 | article.addTag("Castor"); 53 | article.addTag("XML"); 54 | article.addTag("Marshalling"); 55 | article.addTag("Unmarshalling"); 56 | 57 | return article; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /castor-xml-object/src/main/java/com/hmkcode/AppMapping.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileReader; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.Reader; 7 | import java.io.Writer; 8 | 9 | import org.exolab.castor.mapping.Mapping; 10 | import org.exolab.castor.mapping.MappingException; 11 | import org.exolab.castor.xml.MarshalException; 12 | import org.exolab.castor.xml.Marshaller; 13 | import org.exolab.castor.xml.Unmarshaller; 14 | import org.exolab.castor.xml.ValidationException; 15 | import org.exolab.castor.xml.XMLContext; 16 | 17 | import com.hmkcode.vo.Article; 18 | 19 | 20 | public class AppMapping 21 | { 22 | public static void main( String[] args ) 23 | { 24 | 25 | try { 26 | //Load Mapping 27 | Mapping mapping = new Mapping(); 28 | mapping.loadMapping("mapping.xml"); 29 | XMLContext context = new XMLContext(); 30 | context.addMapping(mapping); 31 | 32 | //( 1 ) OBJECT --> XML 33 | 34 | //1.1 Prepare file writer 35 | Writer writer = new FileWriter("mapped_article.xml"); 36 | 37 | //1.2 Create a new Marshaller 38 | Marshaller marshaller = context.createMarshaller(); 39 | marshaller.setWriter(writer); 40 | 41 | //1.3 Marshal "map" to xml 42 | marshaller.marshal(createArticle()); 43 | 44 | //1.4 45 | writer.close(); 46 | 47 | 48 | //( 2 ) XML --> OBJECT 49 | 50 | //2.1 Prepare file writer 51 | Reader reader = new FileReader("mapped_article.xml"); 52 | 53 | //2.2 Create a new Unmarshaller 54 | Unmarshaller unmarshaller = context.createUnmarshaller(); 55 | unmarshaller.setClass(Article.class); 56 | 57 | //2.3 Unmarshal "map" to Object 58 | Article article = (Article) unmarshaller.unmarshal(reader); 59 | 60 | //2.4 61 | reader.close(); 62 | 63 | System.out.println(article); 64 | 65 | } catch (IOException e1) { 66 | e1.printStackTrace(); 67 | } catch (MappingException e1) { 68 | e1.printStackTrace(); 69 | } catch (MarshalException e) { 70 | e.printStackTrace(); 71 | } catch (ValidationException e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | public static Article createArticle(){ 76 | Article article = new Article(); 77 | 78 | article.setTitle("Castor - Java Object to XML & XML to Object Mapping"); 79 | article.setUrl("http://hmkcode.com/castor-java-object-xml"); 80 | article.addCategory("Java"); 81 | article.addTag("Java"); 82 | article.addTag("Castor"); 83 | article.addTag("XML"); 84 | article.addTag("Marshalling"); 85 | article.addTag("Unmarshalling"); 86 | 87 | return article; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /castor-xml-object/src/main/java/com/hmkcode/vo/Article.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class Article { 7 | 8 | private String title; 9 | private String url; 10 | private List categories; 11 | private List tags; 12 | 13 | public String getTitle() { 14 | return title; 15 | } 16 | public void setTitle(String title) { 17 | this.title = title; 18 | } 19 | public String getUrl() { 20 | return url; 21 | } 22 | public void setUrl(String url) { 23 | this.url = url; 24 | } 25 | public List getCategories() { 26 | return categories; 27 | } 28 | public void setCategories(List categories) { 29 | this.categories = categories; 30 | } 31 | public List getTags() { 32 | return tags; 33 | } 34 | public void setTags(List tags) { 35 | this.tags = tags; 36 | } 37 | 38 | public void addCategory(String category){ 39 | if(this.categories == null) 40 | this.categories = new LinkedList(); 41 | this.categories.add(category); 42 | } 43 | public void addTag(String tag){ 44 | if(this.tags == null) 45 | this.tags = new LinkedList(); 46 | 47 | this.tags.add(tag); 48 | } 49 | @Override 50 | public String toString() { 51 | return "Article [title=" + title + ", url=" + url + ", categories=" 52 | + categories + ", tags=" + tags + "]"; 53 | } 54 | 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /gson-json-java/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /gson-json-java/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | gson-json-java 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | gson-json-java 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | com.google.code.gson 20 | gson 21 | 2.2.4 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /gson-json-java/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import com.google.gson.Gson; 8 | import com.google.gson.reflect.TypeToken; 9 | import com.hmkcode.vo.Article; 10 | 11 | 12 | public class App 13 | { 14 | public static void main( String[] args ) 15 | { 16 | Gson gson = new Gson(); 17 | 18 | 19 | List
articles = new LinkedList
(); 20 | 21 | articles.add(createArticle()); 22 | articles.add(createArticle()); 23 | 24 | // Java --> JSON 25 | String json = gson.toJson(articles); 26 | System.out.println("toJson: "+json); 27 | 28 | 29 | // JSON --> Java 30 | List list = gson.fromJson(json, List.class); 31 | System.out.println("fromJson: "+list); 32 | System.out.println("Class Type: "+list.get(0).getClass()); 33 | 34 | // JSON --> Java "Get the actual type" 35 | Type type = new TypeToken>(){}.getType(); 36 | list = gson.fromJson(json, type); 37 | System.out.println("fromJson: "+list); 38 | System.out.println("Class Type: "+list.get(0).getClass()); 39 | 40 | 41 | } 42 | private static Article createArticle(){ 43 | 44 | Article article = new Article(); 45 | 46 | article.setTitle("GSON - Java JSON Library"); 47 | article.setUrl("http://hmkcode.com/gson-json-java"); 48 | article.addCategory("Java"); 49 | article.addTag("Java"); 50 | article.addTag("GSON"); 51 | article.addTag("JSON"); 52 | 53 | return article; 54 | } 55 | } -------------------------------------------------------------------------------- /gson-json-java/src/main/java/com/hmkcode/vo/Article.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class Article { 7 | 8 | private String title; 9 | private String url; 10 | private List categories; 11 | private List tags; 12 | 13 | public String getTitle() { 14 | return title; 15 | } 16 | public void setTitle(String title) { 17 | this.title = title; 18 | } 19 | public String getUrl() { 20 | return url; 21 | } 22 | public void setUrl(String url) { 23 | this.url = url; 24 | } 25 | public List getCategories() { 26 | return categories; 27 | } 28 | public void setCategories(List categories) { 29 | this.categories = categories; 30 | } 31 | public List getTags() { 32 | return tags; 33 | } 34 | public void setTags(List tags) { 35 | this.tags = tags; 36 | } 37 | 38 | public void addCategory(String category){ 39 | if(this.categories == null) 40 | this.categories = new LinkedList(); 41 | this.categories.add(category); 42 | } 43 | public void addTag(String tag){ 44 | if(this.tags == null) 45 | this.tags = new LinkedList(); 46 | 47 | this.tags.add(tag); 48 | } 49 | @Override 50 | public String toString() { 51 | return "Article [title=" + title + ", url=" + url + ", categories=" 52 | + categories + ", tags=" + tags + "]"; 53 | } 54 | 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /itext-create-pdf/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /itext-create-pdf/helloworld.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/itext-create-pdf/helloworld.pdf -------------------------------------------------------------------------------- /itext-create-pdf/pagesettings.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/itext-create-pdf/pagesettings.pdf -------------------------------------------------------------------------------- /itext-create-pdf/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | itext-create-pdf 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | itext-create-pdf 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | com.itextpdf 20 | itextpdf 21 | 5.4.2 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /itext-create-pdf/src/main/java/com/hmkcode/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | 6 | import com.itextpdf.text.Document; 7 | import com.itextpdf.text.DocumentException; 8 | import com.itextpdf.text.Paragraph; 9 | import com.itextpdf.text.pdf.PdfWriter; 10 | 11 | 12 | public class HelloWorld 13 | { 14 | public static void main( String[] args ) 15 | { 16 | try { 17 | 18 | // 1. create the document 19 | Document document = new Document(); 20 | // 2. get PdfWriter 21 | PdfWriter.getInstance(document, new FileOutputStream("helloworld.pdf")); 22 | // 3. open the document 23 | document.open(); 24 | // 4. add the content 25 | document.add(new Paragraph("Hello World!")); 26 | // 5. close the document 27 | document.close(); 28 | 29 | System.out.println("Document created!"); 30 | 31 | } catch (FileNotFoundException e) { 32 | e.printStackTrace(); 33 | } catch (DocumentException e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /itext-create-pdf/src/main/java/com/hmkcode/PageSettings.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | 6 | import com.itextpdf.text.Document; 7 | import com.itextpdf.text.DocumentException; 8 | import com.itextpdf.text.PageSize; 9 | import com.itextpdf.text.Paragraph; 10 | import com.itextpdf.text.Rectangle; 11 | import com.itextpdf.text.pdf.PdfWriter; 12 | 13 | 14 | public class PageSettings 15 | { 16 | public static void main( String[] args ) 17 | { 18 | try { 19 | 20 | // 1. create the document page size: A4, margins: left:20 right:20 top:40 bottom:40 21 | Document document = new Document(PageSize.A4, 20f,20f,40f,40); 22 | 23 | //for custom pagesize 24 | //Rectangle pagesize = new Rectangle(216f, 720f); 25 | 26 | // 2. get PdfWriter 27 | PdfWriter.getInstance(document, new FileOutputStream("pagesettings.pdf")); 28 | // 3. open the document 29 | document.open(); 30 | // 4. add the content 31 | document.add(new Paragraph("Hello World!")); 32 | // 5. close the document 33 | document.close(); 34 | 35 | System.out.println("Document created!"); 36 | 37 | } catch (FileNotFoundException e) { 38 | e.printStackTrace(); 39 | } catch (DocumentException e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /itext-java-html-pdf/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /itext-java-html-pdf/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HTML to PDF 5 | 6 | 7 | 8 |

HTML to PDF

9 |

10 | itext 7.1.9 11 | converting HTML to PDF 12 |

13 | java-logo 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
TitleiText - Java HTML to PDF
URLhttp://hmkcode.com/itext-html-to-pdf-using-java
24 | 25 | 26 | -------------------------------------------------------------------------------- /itext-java-html-pdf/java.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/itext-java-html-pdf/java.png -------------------------------------------------------------------------------- /itext-java-html-pdf/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | itext-java-html-pdf 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | itext-java-html-pdf 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | RELEASE 16 | 17 | 18 | 19 | 20 | com.itextpdf 21 | itext7-core 22 | 7.1.9 23 | pom 24 | 25 | 26 | com.itextpdf 27 | html2pdf 28 | 2.1.6 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /itext-java-html-pdf/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | 8 | import com.itextpdf.html2pdf.HtmlConverter; 9 | 10 | public class App 11 | { 12 | public static final String HTML = "

Hello

" 13 | + "

This was created using iText

" 14 | + "hmkcode.com"; 15 | 16 | 17 | public static void main( String[] args ) throws FileNotFoundException, IOException 18 | { 19 | 20 | // String to PDF 21 | HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf")); 22 | 23 | 24 | // HTML file to PDF 25 | HtmlConverter.convertToPdf(new FileInputStream("index.html"), 26 | new FileOutputStream("index-to-pdf.pdf")); 27 | 28 | 29 | System.out.println( "PDF Created!" ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /itext-java-html-pdf/style.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | color:#ccc; 3 | } 4 | table tr td{ 5 | text-align:center; 6 | border:1px solid gray; 7 | padding:4px; 8 | } 9 | table tr th{ 10 | background-color:#84C7FD; 11 | color:#fff; 12 | width: 100px; 13 | } 14 | .itext{ 15 | color:#84C7FD; 16 | font-weight:bold; 17 | } 18 | .description{ 19 | color:gray; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /itext-java-pdf-table/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /itext-java-pdf-table/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | itext-java-pdf-table 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | itext-java-pdf-table 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | com.itextpdf 20 | itextpdf 21 | 5.4.2 22 | 23 | 24 | com.itextpdf.tool 25 | xmlworker 26 | 5.4.1 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /itext-java-pdf-table/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | 6 | import com.itextpdf.text.Document; 7 | import com.itextpdf.text.DocumentException; 8 | import com.itextpdf.text.PageSize; 9 | import com.itextpdf.text.pdf.PdfWriter; 10 | 11 | 12 | public class App 13 | { 14 | public static void main( String[] args ) throws FileNotFoundException, DocumentException 15 | { 16 | // step 1 17 | Document document = new Document(); 18 | document.setPageSize(PageSize.A4); 19 | 20 | // step 2 21 | PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf")); 22 | 23 | // step 3 24 | document.open(); 25 | 26 | // step 4 create PDF contents 27 | document.add(TableBuilder.createTable()); 28 | 29 | //step 5 30 | document.close(); 31 | 32 | System.out.println( "PDF Created!" ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /itext-java-pdf-table/src/main/java/com/hmkcode/Style.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import com.itextpdf.text.BaseColor; 4 | import com.itextpdf.text.Element; 5 | import com.itextpdf.text.pdf.PdfPCell; 6 | 7 | public class Style { 8 | 9 | public static void headerCellStyle(PdfPCell cell){ 10 | 11 | // alignment 12 | cell.setHorizontalAlignment(Element.ALIGN_CENTER); 13 | 14 | // padding 15 | cell.setPaddingTop(0f); 16 | cell.setPaddingBottom(7f); 17 | 18 | // background color 19 | cell.setBackgroundColor(new BaseColor(0,121,182)); 20 | 21 | // border 22 | cell.setBorder(0); 23 | cell.setBorderWidthBottom(2f); 24 | 25 | } 26 | public static void labelCellStyle(PdfPCell cell){ 27 | // alignment 28 | cell.setHorizontalAlignment(Element.ALIGN_LEFT); 29 | cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 30 | 31 | // padding 32 | cell.setPaddingLeft(3f); 33 | cell.setPaddingTop(0f); 34 | 35 | // background color 36 | cell.setBackgroundColor(BaseColor.LIGHT_GRAY); 37 | 38 | // border 39 | cell.setBorder(0); 40 | cell.setBorderWidthBottom(1); 41 | cell.setBorderColorBottom(BaseColor.GRAY); 42 | 43 | // height 44 | cell.setMinimumHeight(18f); 45 | } 46 | 47 | public static void valueCellStyle(PdfPCell cell){ 48 | // alignment 49 | cell.setHorizontalAlignment(Element.ALIGN_CENTER); 50 | cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 51 | 52 | // padding 53 | cell.setPaddingTop(0f); 54 | cell.setPaddingBottom(5f); 55 | 56 | // border 57 | cell.setBorder(0); 58 | cell.setBorderWidthBottom(0.5f); 59 | 60 | // height 61 | cell.setMinimumHeight(18f); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /itext-java-pdf-table/src/main/java/com/hmkcode/TableBuilder.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import com.itextpdf.text.BaseColor; 4 | import com.itextpdf.text.DocumentException; 5 | import com.itextpdf.text.Font; 6 | import com.itextpdf.text.Phrase; 7 | import com.itextpdf.text.Font.FontFamily; 8 | import com.itextpdf.text.pdf.PdfPCell; 9 | import com.itextpdf.text.pdf.PdfPTable; 10 | 11 | public class TableBuilder { 12 | // create table 13 | public static PdfPTable createTable() throws DocumentException { 14 | 15 | 16 | // create 6 column table 17 | PdfPTable table = new PdfPTable(6); 18 | 19 | // set the width of the table to 100% of page 20 | table.setWidthPercentage(100); 21 | 22 | // set relative columns width 23 | table.setWidths(new float[]{0.6f, 1.4f, 0.8f,0.8f,1.8f,2.6f}); 24 | 25 | 26 | // ----------------Table Header "Title"---------------- 27 | // font 28 | Font font = new Font(FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.WHITE); 29 | // create header cell 30 | PdfPCell cell = new PdfPCell(new Phrase("HMKCODE.com - iText PDFTable Example",font)); 31 | // set Column span "1 cell = 6 cells width" 32 | cell.setColspan(6); 33 | // set style 34 | Style.headerCellStyle(cell); 35 | // add to table 36 | table.addCell(cell); 37 | 38 | //-----------------Table Cells Label/Value------------------ 39 | 40 | // 1st Row 41 | table.addCell(createLabelCell("Label 1")); 42 | table.addCell(createValueCell("Value 1")); 43 | table.addCell(createLabelCell("Label 2")); 44 | table.addCell(createValueCell("Value 2")); 45 | table.addCell(createLabelCell("Label 3")); 46 | table.addCell(createValueCell("Value 3")); 47 | 48 | // 2nd Row 49 | table.addCell(createLabelCell("Label 4")); 50 | table.addCell(createValueCell("Value 4")); 51 | table.addCell(createLabelCell("Label 5")); 52 | table.addCell(createValueCell("Value 5")); 53 | table.addCell(createLabelCell("Label 6")); 54 | table.addCell(createValueCell("Value 6")); 55 | 56 | return table; 57 | } 58 | 59 | // create cells 60 | private static PdfPCell createLabelCell(String text){ 61 | // font 62 | Font font = new Font(FontFamily.HELVETICA, 8, Font.BOLD, BaseColor.DARK_GRAY); 63 | 64 | // create cell 65 | PdfPCell cell = new PdfPCell(new Phrase(text,font)); 66 | 67 | // set style 68 | Style.labelCellStyle(cell); 69 | return cell; 70 | } 71 | 72 | // create cells 73 | private static PdfPCell createValueCell(String text){ 74 | // font 75 | Font font = new Font(FontFamily.HELVETICA, 8, Font.NORMAL, BaseColor.BLACK); 76 | 77 | // create cell 78 | PdfPCell cell = new PdfPCell(new Phrase(text,font)); 79 | 80 | // set style 81 | Style.valueCellStyle(cell); 82 | return cell; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /jackson-json-java/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /jackson-json-java/article.json: -------------------------------------------------------------------------------- 1 | {"title":"Jackson - Java to JSON & JSON to Java", 2 | "categories":["Java"], 3 | "address":"http://hmkcode.com/jackson-java-json"} -------------------------------------------------------------------------------- /jackson-json-java/articles.json: -------------------------------------------------------------------------------- 1 | [{"title":"Jackson - Java to JSON & JSON to Java","url":"http://hmkcode.com/jackson-java-json","categories":["Java"],"tags":["Java","Jackson","JSON"]},{"title":"Jackson - Java to JSON & JSON to Java","url":"http://hmkcode.com/jackson-java-json","categories":["Java"],"tags":["Java","Jackson","JSON"]}] -------------------------------------------------------------------------------- /jackson-json-java/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | jackson-json-java 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | jackson-json-java 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | com.fasterxml.jackson.core 20 | jackson-core 21 | 2.2.2 22 | 23 | 24 | com.fasterxml.jackson.core 25 | jackson-databind 26 | 2.2.2 27 | 28 | 29 | com.fasterxml.jackson.core 30 | jackson-annotations 31 | 2.2.2 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /jackson-json-java/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Iterator; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import com.fasterxml.jackson.core.JsonGenerationException; 11 | import com.fasterxml.jackson.core.type.TypeReference; 12 | import com.fasterxml.jackson.databind.JsonMappingException; 13 | import com.fasterxml.jackson.databind.JsonNode; 14 | import com.fasterxml.jackson.databind.ObjectMapper; 15 | import com.fasterxml.jackson.databind.SerializationFeature; 16 | import com.fasterxml.jackson.databind.node.ArrayNode; 17 | import com.fasterxml.jackson.databind.node.ObjectNode; 18 | import com.hmkcode.vo.Article; 19 | 20 | 21 | public class App 22 | { 23 | public static void main( String[] args ) 24 | { 25 | 26 | ObjectMapper mapper = new ObjectMapper(); 27 | 28 | try { 29 | 30 | //POJO to JSON 31 | mapper.writeValue(new File("article.json"), createArticle()); 32 | System.out.println("json created!"); 33 | 34 | //JSON to POJO 35 | Article article = mapper.readValue(new File("article.json"), Article.class); 36 | 37 | //"Raw" Data Binding Example 38 | Map articleMap = mapper.readValue(new File("article.json"), Map.class); 39 | 40 | System.out.println(article); 41 | 42 | System.out.println(articleMap); 43 | 44 | //Data binding Collection 45 | List
articles = new LinkedList
(); 46 | 47 | articles.add(createArticle()); 48 | articles.add(createArticle()); 49 | 50 | mapper.writeValue(new File("articles.json"), articles); 51 | 52 | //( 1 ) Collection 53 | List result = mapper.readValue(new File("articles.json"), List.class); 54 | System.out.println(result.get(0).getClass()); 55 | System.out.println(result); 56 | 57 | //( 2 ) Collection 58 | result = mapper.readValue(new File("articles.json"), new TypeReference>() { }); 59 | System.out.println(result.get(0).getClass()); 60 | System.out.println(result); 61 | 62 | System.out.println("---------------------------------------------------------"); 63 | //Tree 64 | ObjectNode objectRoot = (ObjectNode) mapper.readTree(new File("article.json")); 65 | Iterator fields = objectRoot.fieldNames(); 66 | String field = ""; 67 | while(fields.hasNext()){ 68 | field = fields.next(); 69 | System.out.println("field: "+field); 70 | } 71 | System.out.println("---------------------------------------------------------"); 72 | 73 | ArrayNode arrayRoot = (ArrayNode) mapper.readTree(new File("articles.json")); 74 | 75 | Iterator elements = arrayRoot.elements(); 76 | JsonNode element; 77 | 78 | while(elements.hasNext()){ 79 | element = elements.next(); 80 | fields = element.fieldNames(); 81 | field = ""; 82 | while(fields.hasNext()){ 83 | field = fields.next(); 84 | System.out.println("field: "+field); 85 | } 86 | 87 | } 88 | 89 | } catch (JsonGenerationException e) { 90 | e.printStackTrace(); 91 | } catch (JsonMappingException e) { 92 | e.printStackTrace(); 93 | } catch (IOException e) { 94 | e.printStackTrace(); 95 | } 96 | } 97 | 98 | private static Article createArticle(){ 99 | 100 | Article article = new Article(); 101 | 102 | article.setTitle("Jackson - Java to JSON & JSON to Java"); 103 | article.setUrl("http://hmkcode.com/jackson-java-json"); 104 | article.addCategory("Java"); 105 | article.addTag("Java"); 106 | article.addTag("Jackson"); 107 | article.addTag("JSON"); 108 | 109 | return article; 110 | } 111 | } -------------------------------------------------------------------------------- /jackson-json-java/src/main/java/com/hmkcode/vo/Article.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import com.fasterxml.jackson.annotation.JsonIgnore; 7 | import com.fasterxml.jackson.annotation.JsonProperty; 8 | 9 | public class Article { 10 | 11 | private String title; 12 | //@JsonProperty("address") 13 | private String url; 14 | private List categories; 15 | //@JsonIgnore 16 | private List tags; 17 | 18 | public String getTitle() { 19 | return title; 20 | } 21 | public void setTitle(String title) { 22 | this.title = title; 23 | } 24 | public String getUrl() { 25 | return url; 26 | } 27 | public void setUrl(String url) { 28 | this.url = url; 29 | } 30 | public List getCategories() { 31 | return categories; 32 | } 33 | public void setCategories(List categories) { 34 | this.categories = categories; 35 | } 36 | public List getTags() { 37 | return tags; 38 | } 39 | public void setTags(List tags) { 40 | this.tags = tags; 41 | } 42 | 43 | public void addCategory(String category){ 44 | if(this.categories == null) 45 | this.categories = new LinkedList(); 46 | this.categories.add(category); 47 | } 48 | public void addTag(String tag){ 49 | if(this.tags == null) 50 | this.tags = new LinkedList(); 51 | 52 | this.tags.add(tag); 53 | } 54 | @Override 55 | public String toString() { 56 | return "Article [title=" + title + ", url=" + url + ", categories=" 57 | + categories + ", tags=" + tags + "]"; 58 | } 59 | 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /java-async-servlet/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /java-async-servlet/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | java-async-servlet 7 | 1.0-SNAPSHOT 8 | war 9 | 10 | java-async-servlet 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | javax.servlet 20 | javax.servlet-api 21 | 3.1.0 22 | 23 | 24 | 25 | 26 | 27 | java-async-servlet 28 | 29 | 30 | org.eclipse.jetty 31 | jetty-maven-plugin 32 | 9.0.0.M5 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /java-async-servlet/src/main/java/com/hmkcode/AsyncServlet.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.AsyncContext; 6 | import javax.servlet.AsyncEvent; 7 | import javax.servlet.AsyncListener; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.annotation.WebServlet; 10 | import javax.servlet.http.HttpServlet; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | 15 | @WebServlet(name="asyncServlet",value = {"/async"},asyncSupported = true) 16 | public class AsyncServlet extends HttpServlet 17 | { 18 | 19 | 20 | 21 | private static final long serialVersionUID = 1L; 22 | 23 | String param =""; 24 | 25 | @Override 26 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) 27 | throws ServletException, IOException { 28 | 29 | 30 | // 1.0 start async 31 | final AsyncContext ctx = req.startAsync(); 32 | param = ctx.getRequest().getParameter("seq"); 33 | 34 | // 2.0 set the timeout 35 | ctx.setTimeout(0); 36 | 37 | // 3.0 add listener 38 | ctx.addListener(new AsyncListener() { 39 | 40 | @Override 41 | public void onTimeout(AsyncEvent arg0) throws IOException { 42 | System.out.println("onTimeout..."); 43 | } 44 | 45 | @Override 46 | public void onStartAsync(AsyncEvent arg0) throws IOException { 47 | System.out.println("onStartAsync..."); 48 | } 49 | 50 | @Override 51 | public void onError(AsyncEvent arg0) throws IOException { 52 | System.out.println("onError..."); 53 | } 54 | 55 | @Override 56 | public void onComplete(AsyncEvent arg0) throws IOException { 57 | System.out.println("onComplete..."); 58 | } 59 | }); 60 | 61 | // 4.0 run a thread 62 | ctx.start(new Runnable() { 63 | @Override 64 | public void run() { 65 | try { 66 | 67 | // hold until receive exit 68 | while(!param.equals("exit")){} 69 | 70 | ctx.getResponse().getWriter().write(ctx.getRequest().getParameter("seq")); 71 | 72 | } catch (IOException e) { 73 | e.printStackTrace(); 74 | } 75 | 76 | ctx.complete(); 77 | } 78 | 79 | 80 | }); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /java-async-servlet/src/main/java/com/hmkcode/SyncServlet.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | import javax.servlet.ServletException; 5 | import javax.servlet.annotation.WebServlet; 6 | import javax.servlet.http.HttpServlet; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | 11 | @WebServlet(name="syncServlet",value = {"/sync"}) 12 | public class SyncServlet extends HttpServlet 13 | { 14 | public static int index = 0; 15 | 16 | public SyncServlet(){ 17 | System.out.println("SyncServlet - "+index++); 18 | } 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | @Override 23 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) 24 | throws ServletException, IOException { 25 | 26 | 27 | String seq = req.getParameter("seq"); 28 | 29 | try { 30 | Thread.sleep(50 * Integer.parseInt(seq)); 31 | } catch (NumberFormatException e) { 32 | e.printStackTrace(); 33 | } catch (InterruptedException e) { 34 | e.printStackTrace(); 35 | } 36 | resp.getWriter().write(seq); 37 | 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java-async-servlet/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | java async servlet 8 | 9 | index.html 10 | 11 | 12 | -------------------------------------------------------------------------------- /java-async-servlet/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-async-servlet/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png -------------------------------------------------------------------------------- /java-async-servlet/src/main/webapp/bootstrap/img/glyphicons-halflings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-async-servlet/src/main/webapp/bootstrap/img/glyphicons-halflings.png -------------------------------------------------------------------------------- /java-async-servlet/src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Java Async Servlet 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |

Java Async Servlet

20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
Request IDResponse ID
28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /java-async-servlet/src/main/webapp/js/myfunctions.js: -------------------------------------------------------------------------------- 1 | function sendAsync(seq) { 2 | var data = new Object(); 3 | data.seq = seq; 4 | $.ajax({ 5 | url: "/async", 6 | type: 'GET', 7 | data: data, 8 | 9 | success: function (data) { 10 | $("#ares-"+data).text("reponse "+data); 11 | }, 12 | error:function(data,status,er) { 13 | alert("error: "+data+" status: "+status+" er:"+er); 14 | } 15 | }); 16 | } 17 | 18 | 19 | $(document).ready(function(){ 20 | $("#start").click(function(){ 21 | 22 | $("tr:has(td)").remove(); 23 | 24 | for(i = 1 ; i < 5 ; i++){ 25 | $("#asyncResponse").append($('') 26 | .append($('').text("request -"+i)) 27 | .append($("").text("processing..")) 28 | ); 29 | sendAsync(i); 30 | } 31 | }); 32 | 33 | 34 | $("#exit").click(function(){ 35 | sendAsync("exit"); 36 | }); 37 | }) 38 | -------------------------------------------------------------------------------- /java-combinations/Combination.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | 5 | public class Combination { 6 | 7 | 8 | public static void main(String[] args){ 9 | Object[] elements = new Object[] {'A','B','C','D','E'}; 10 | combination(elements,3); 11 | } 12 | 13 | 14 | public static void combination(Object[] elements, int K){ 15 | 16 | // get the length of the array 17 | // e.g. for {'A','B','C','D'} => N = 4 18 | int N = elements.length; 19 | 20 | if(K > N){ 21 | System.out.println("Invalid input, K > N"); 22 | return; 23 | } 24 | 25 | // calculate the possible combinations 26 | c(N,K); 27 | 28 | // init combination index array 29 | int combination[] = new int[K]; 30 | 31 | 32 | int r = 0; // index for combination array 33 | int i = 0; // index for elements array 34 | 35 | while(r >= 0){ 36 | 37 | // forward step if i < (N + (r-K)) 38 | if(i <= (N + (r - K))){ 39 | combination[r] = i; 40 | 41 | // if combination array is full print and increment i; 42 | if(r == K-1){ 43 | print(combination, elements); 44 | i++; 45 | } 46 | else{ 47 | // if combination is not full yet, select next element 48 | i = combination[r]+1; 49 | r++; 50 | } 51 | 52 | } 53 | 54 | // backward step 55 | else{ 56 | r--; 57 | if(r >= 0) 58 | i = combination[r]+1; 59 | 60 | } 61 | } 62 | } 63 | 64 | 65 | 66 | private static int c(int n, int r){ 67 | int nf=fact(n); 68 | int rf=fact(r); 69 | int nrf=fact(n-r); 70 | int npr=nf/nrf; 71 | int ncr=npr/rf; 72 | 73 | System.out.println("C("+n+","+r+") = "+ ncr); 74 | 75 | return ncr; 76 | } 77 | 78 | private static int fact(int n) 79 | { 80 | if(n == 0) 81 | return 1; 82 | else 83 | return n * fact(n-1); 84 | } 85 | 86 | 87 | private static void print(int[] combination, Object[] elements){ 88 | 89 | String output = ""; 90 | for(int z = 0 ; z < combination.length;z++){ 91 | output += elements[combination[z]]; 92 | } 93 | System.out.println(output); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /java-combinations/README.md: -------------------------------------------------------------------------------- 1 | Algorithms for Finding all Possible Combinations of k Elements in an Array with Java Implementation 2 | =================================================================================================== 3 | 4 | Refer to the [http://hmkcode.github.io/calculate-find-all-possible-combinations-of-an-array-using-java/](http://hmkcode.github.io/calculate-find-all-possible-combinations-of-an-array-using-java/) for more info. 5 | 6 | Given an array of size N e.g. `e={'A','B','C','D','E'}` **N=5**, we want to find all possible combinations of K elements in that array. For example, if K=3 then one possible combination is of array **e** is `{'A','B','C'}. Here we have three different algorithms for finding *k*-combinations of an array. 7 | 8 | ![combinations](http://hmkcode.github.io/images/java/combinations_forwardbackward.png) 9 | -------------------------------------------------------------------------------- /java-combinations/src/main/java/com/hmkcode/ForwardBackward.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | 5 | public class ForwardBackward { 6 | 7 | 8 | public static void main(String[] args){ 9 | Object[] e = new Object[] {'A','B','C','D','E'}; 10 | int k = 3; 11 | combination(e,k); 12 | } 13 | 14 | 15 | public static void combination(Object[] elements, int k){ 16 | 17 | // get the length of the array 18 | // e.g. for {'A','B','C','D'} => N = 4 19 | int N = elements.length; 20 | 21 | if(k > N){ 22 | System.out.println("Invalid input, K > N"); 23 | return; 24 | } 25 | 26 | // calculate the possible combinations 27 | c(N,k); 28 | 29 | // init combination index array 30 | int pointers[] = new int[k]; 31 | 32 | 33 | int r = 0; // index for combination array 34 | int i = 0; // index for elements array 35 | 36 | while(r >= 0){ 37 | 38 | // forward step if i < (N + (r-K)) 39 | if(i <= (N + (r - k))){ 40 | pointers[r] = i; 41 | 42 | // if combination array is full print and increment i; 43 | if(r == k-1){ 44 | print(pointers, elements); 45 | i++; 46 | } 47 | else{ 48 | // if combination is not full yet, select next element 49 | i = pointers[r]+1; 50 | r++; 51 | } 52 | } 53 | 54 | // backward step 55 | else{ 56 | r--; 57 | if(r >= 0) 58 | i = pointers[r]+1; 59 | 60 | } 61 | } 62 | } 63 | 64 | 65 | 66 | private static int c(int n, int r){ 67 | int nf=fact(n); 68 | int rf=fact(r); 69 | int nrf=fact(n-r); 70 | int npr=nf/nrf; 71 | int ncr=npr/rf; 72 | 73 | System.out.println("C("+n+","+r+") = "+ ncr); 74 | 75 | return ncr; 76 | } 77 | 78 | private static int fact(int n) 79 | { 80 | if(n == 0) 81 | return 1; 82 | else 83 | return n * fact(n-1); 84 | } 85 | 86 | 87 | private static void print(int[] combination, Object[] elements){ 88 | 89 | String output = ""; 90 | for(int z = 0 ; z < combination.length;z++){ 91 | output += elements[combination[z]]; 92 | } 93 | System.out.println(output); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /java-combinations/src/main/java/com/hmkcode/Recursive.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Recursive { 7 | 8 | public static void main(String[] args) { 9 | 10 | List e = Arrays.asList("A", "B", "C", "D", "E"); 11 | int k = 3; 12 | combination(e, k, ""); 13 | 14 | } 15 | static int counter = 0; 16 | public static void combination(List e, int k, String accumulated){ 17 | 18 | // 1. stop 19 | if(e.size() < k) 20 | return; 21 | 22 | // 2. add each element in e to accumulated 23 | if(k == 1) 24 | for(String s:e) 25 | print(accumulated+s); 26 | 27 | // 3. add all elements in e to accumulated 28 | else if(e.size() == k){ 29 | for(String s:e) 30 | accumulated+=s; 31 | print(accumulated); 32 | } 33 | 34 | // 4. for each element, call combination 35 | else if(e.size() > k) 36 | for(int i = 0 ; i < e.size() ; i++) 37 | combination(e.subList(i+1, e.size()), k-1, accumulated+e.get(i)); 38 | 39 | } 40 | 41 | public static void print(String c){ 42 | counter++; 43 | System.out.println(counter+"\t"+c); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /java-combinations/src/main/java/com/hmkcode/Shifting.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | public class Shifting 4 | { 5 | public static void main( String[] args ) 6 | { 7 | String[] e = {"A","B","C","D","E"}; 8 | int k = 3; 9 | combination(e,k); 10 | } 11 | public static void combination(Object[] e, int k){ 12 | 13 | int[] ignore = new int[e.length-k]; // --> [0][0] 14 | int[] combination = new int[k]; // --> [][][] 15 | 16 | // set initial ignored elements 17 | //(last k elements will be ignored) 18 | for(int w = 0; w < ignore.length; w++) 19 | ignore[w] = e.length - k +(w+1); 20 | 21 | int i = 0, r = 0, g = 0; 22 | 23 | boolean terminate = false; 24 | while(!terminate){ 25 | 26 | // selecting N-k non-ignored elements 27 | while(i < e.length && r < k){ 28 | 29 | if(i != ignore[g]){ 30 | combination[r] = i; 31 | r++; i++; 32 | } 33 | else{ 34 | if(g != ignore.length-1) 35 | g++; 36 | i++; 37 | } 38 | } 39 | print(combination, e); 40 | i = 0; r = 0; g = 0; 41 | 42 | terminate = true; 43 | 44 | // shifting ignored indices 45 | for(int w = 0 ; w < ignore.length; w++){ 46 | if(ignore[w] > w){ 47 | ignore[w]--; 48 | 49 | if(w > 0) 50 | ignore[w-1] = ignore[w]-1; 51 | terminate = false; 52 | break; 53 | } 54 | } 55 | } 56 | } 57 | 58 | private static void print(int[] combination, Object[] elements){ 59 | 60 | String output = ""; 61 | for(int z = 0 ; z < combination.length;z++){ 62 | output += elements[combination[z]]; 63 | } 64 | System.out.println(output); 65 | } 66 | } -------------------------------------------------------------------------------- /java-excel-poi/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /java-excel-poi/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | java-excel-poi 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | java-excel-poi 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.apache.poi 20 | poi 21 | 3.9 22 | 23 | 24 | org.apache.poi 25 | poi-ooxml 26 | 3.9 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /java-excel-poi/src/main/java/com/hmkcode/poi/AppRead.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.poi; 2 | 3 | 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.util.Date; 9 | 10 | import org.apache.poi.hssf.util.CellReference; 11 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 12 | import org.apache.poi.ss.usermodel.Cell; 13 | import org.apache.poi.ss.usermodel.CellStyle; 14 | import org.apache.poi.ss.usermodel.CreationHelper; 15 | import org.apache.poi.ss.usermodel.DateUtil; 16 | import org.apache.poi.ss.usermodel.Row; 17 | import org.apache.poi.ss.usermodel.Sheet; 18 | import org.apache.poi.ss.usermodel.Workbook; 19 | import org.apache.poi.ss.usermodel.WorkbookFactory; 20 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 21 | 22 | 23 | public class AppRead 24 | { 25 | public static void main( String[] args ) 26 | { 27 | Workbook wb = null; 28 | try { 29 | wb = WorkbookFactory.create(new File("workbook.xlsx")); 30 | } catch (InvalidFormatException e) { 31 | e.printStackTrace(); 32 | } catch (IOException e) { 33 | e.printStackTrace(); 34 | } 35 | 36 | Sheet sheet = wb.getSheetAt(0); 37 | 38 | //********************************* 39 | Cell cell = sheet.getRow(0).getCell(0); 40 | double numberVal = cell.getNumericCellValue(); 41 | System.out.println("Row: 0 - Column: 0 = "+numberVal); 42 | //----------------------------- 43 | cell = sheet.getRow(0).getCell(1); 44 | String stringVal = cell.getStringCellValue(); 45 | System.out.println("Row: 0 - Column: 1 = "+stringVal); 46 | //----------------------------- 47 | cell = sheet.getRow(0).getCell(2); 48 | Date dateVal = cell.getDateCellValue(); 49 | System.out.println("Row: 0 - Column: 2 = "+dateVal); 50 | //----------------------------- 51 | cell = sheet.getRow(0).getCell(3); 52 | boolean booleanVal = cell.getBooleanCellValue(); 53 | System.out.println("Row: 0 - Column: 3 = "+booleanVal); 54 | //----------------------------- 55 | 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /java-excel-poi/src/main/java/com/hmkcode/poi/AppWrite.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.poi; 2 | 3 | 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.util.Date; 8 | import org.apache.poi.ss.usermodel.Cell; 9 | import org.apache.poi.ss.usermodel.CellStyle; 10 | import org.apache.poi.ss.usermodel.CreationHelper; 11 | import org.apache.poi.ss.usermodel.Row; 12 | import org.apache.poi.ss.usermodel.Sheet; 13 | import org.apache.poi.ss.usermodel.Workbook; 14 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 15 | 16 | 17 | public class AppWrite 18 | { 19 | public static void main( String[] args ) 20 | { 21 | 22 | //1. Create a new Workbook 23 | Workbook wb = new XSSFWorkbook(); 24 | 25 | //2. Create a new sheet 26 | Sheet sheet = wb.createSheet("sheet 1"); 27 | 28 | //3. Create a row 29 | Row row = sheet.createRow((short) 0); 30 | 31 | //4. Create cells 32 | 33 | //4.1 number cell 34 | row.createCell(0).setCellValue(1); 35 | //4.2 text 36 | row.createCell(1).setCellValue("Text"); 37 | 38 | //4.3 date cell 39 | CreationHelper createHelper = wb.getCreationHelper(); 40 | CellStyle cellStyle = wb.createCellStyle(); 41 | cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm")); 42 | Cell cell = row.createCell(2); 43 | cell.setCellValue(new Date()); 44 | cell.setCellStyle(cellStyle); 45 | 46 | //4.4 boolean cell 47 | row.createCell(3).setCellValue(true); 48 | 49 | //5. create excel file 50 | FileOutputStream fileOut; 51 | try { 52 | 53 | fileOut = new FileOutputStream("workbook.xlsx"); 54 | wb.write(fileOut); 55 | fileOut.close(); 56 | 57 | } catch (FileNotFoundException e) { 58 | e.printStackTrace(); 59 | } catch (IOException e) { 60 | e.printStackTrace(); 61 | } 62 | 63 | System.out.println( "File created!" ); 64 | 65 | } 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /java-inputstream-string/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /java-inputstream-string/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | java-inputstream-string 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | java-inputstream-string 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | commons-io 20 | commons-io 21 | 2.4 22 | 23 | 24 | com.google.guava 25 | guava 26 | 14.0.1 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /java-inputstream-string/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | 7 | public class App 8 | { 9 | public static void main( String[] args ) throws IOException 10 | { 11 | 12 | // 1. By java.util.Scanner 13 | InputStream inputStream = new ByteArrayInputStream("hmkcode..inputStream to String".getBytes()); 14 | System.out.println("getStringByScanner: "+InputStreamToString.getStringByScanner(inputStream)); 15 | 16 | // 2. By BufferedReader 17 | inputStream = new ByteArrayInputStream("hmkcode..inputStream to String".getBytes()); 18 | System.out.println("getStringByBufferedReader: " +InputStreamToString.getStringByBufferedReader(inputStream)); 19 | 20 | // 3. By Apache IO 21 | inputStream = new ByteArrayInputStream("hmkcode..inputStream to String".getBytes()); 22 | System.out.println("getStringByApacheIO IOUtils.toString: "+InputStreamToString.getStringByApacheIO_toString(inputStream)); 23 | 24 | // 4. By Apache IO 25 | inputStream = new ByteArrayInputStream("hmkcode..inputStream to String".getBytes()); 26 | System.out.println("getStringByApacheIO IOUtils.copy: "+InputStreamToString.getStringByApacheIO_copy(inputStream)); 27 | 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /java-inputstream-string/src/main/java/com/hmkcode/InputStreamToString.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.io.StringWriter; 8 | import java.util.Scanner; 9 | import org.apache.commons.io.IOUtils; 10 | 11 | public class InputStreamToString { 12 | 13 | // 1. By java.util.Scanner 14 | public static String getStringByScanner(InputStream inputStream){ 15 | return new Scanner(inputStream,"UTF-8").next(); 16 | } 17 | 18 | // 2. By BufferedReader 19 | public static String getStringByBufferedReader(InputStream inputStream) throws IOException{ 20 | BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); 21 | String line = ""; 22 | String result = ""; 23 | while((line = bufferedReader.readLine()) != null) 24 | result += line; 25 | return result; 26 | } 27 | 28 | // 3. By Apache IO 29 | public static String getStringByApacheIO_toString(InputStream inputStream) throws IOException{ 30 | return IOUtils.toString(inputStream); 31 | } 32 | 33 | // 4. By Apache IO 34 | public static String getStringByApacheIO_copy(InputStream inputStream) throws IOException{ 35 | StringWriter writer = new StringWriter(); 36 | IOUtils.copy(inputStream, writer, "UTF-8"); 37 | return writer.toString(); 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /java-jasper/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.hmkcode 8 | java-jasper 9 | 1.0-SNAPSHOT 10 | 11 | java-jasper 12 | 13 | http://www.example.com 14 | 15 | 16 | UTF-8 17 | 1.7 18 | 1.7 19 | 20 | 21 | 22 | 23 | net.sf.jasperreports 24 | jasperreports 25 | 6.10.0 26 | 27 | 28 | 29 | 30 | org.springframework 31 | spring-core 32 | 5.2.3.RELEASE 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /java-jasper/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import net.sf.jasperreports.engine.*; 4 | import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; 5 | import org.springframework.util.ResourceUtils; 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | 10 | public class App 11 | { 12 | // name and destination of output file e.g. "report.pdf" 13 | private static String destFileName = "report.pdf"; 14 | public static void main( String[] args ) throws FileNotFoundException, JRException { 15 | 16 | System.out.println( "generating jasper report..." ); 17 | 18 | // 1. compile template ".jrxml" file 19 | JasperReport jasperReport = getJasperReport(); 20 | 21 | // 2. parameters "empty" 22 | Map parameters = getParameters(); 23 | 24 | // 3. datasource "java object" 25 | JRDataSource dataSource = getDataSource(); 26 | 27 | JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource); 28 | JasperExportManager.exportReportToPdfFile(jasperPrint, destFileName); 29 | 30 | } 31 | 32 | private static JasperReport getJasperReport() throws FileNotFoundException, JRException { 33 | File template = ResourceUtils.getFile("classpath:report.jrxml"); 34 | return JasperCompileManager.compileReport(template.getAbsolutePath()); 35 | } 36 | private static Map getParameters(){ 37 | Map parameters = new HashMap<>(); 38 | parameters.put("createdBy", "hmkcode"); 39 | return parameters; 40 | } 41 | 42 | private static JRDataSource getDataSource(){ 43 | 44 | List countries = new LinkedList<>(); 45 | 46 | countries.add(new Country("IS", "Iceland", "https://i.pinimg.com/originals/72/b4/49/72b44927f220151547493e528a332173.png")); 47 | countries.add(new Country("TR", "Turkey", "https://i.pinimg.com/originals/82/63/23/826323bba32e6e5a5996062c3a3c662f.png")); 48 | countries.add(new Country("ZA", "South Africa", "https://i.pinimg.com/originals/f5/c7/8d/f5c78da001b46e26481c04fb93473454.png")); 49 | countries.add(new Country("PL", "Poland", "https://i.pinimg.com/originals/7f/ae/21/7fae21c4854010b11127218ead743863.png")); 50 | countries.add(new Country("CA", "Canada", "https://i.pinimg.com/originals/4d/d4/01/4dd401733ba25e6442fc8696e04e5846.png")); 51 | 52 | countries.add(new Country("PA", "Panama", "https://i.pinimg.com/originals/84/dc/e4/84dce49e52ebfb5b3814393069807e0a.png")); 53 | countries.add(new Country("HR", "Croatia", "https://i.pinimg.com/originals/f5/8c/94/f58c94a2a2b3221328fc1e2b7acfa656.png")); 54 | countries.add(new Country("JP", "Japan", "https://i.pinimg.com/originals/a5/d6/88/a5d688289cd6850016f14fe93b17da01.png")); 55 | countries.add(new Country("DE", "Germany", "https://i.pinimg.com/originals/af/c9/b2/afc9b2592a9f1cf591e8a52256ae1e9f.png")); 56 | countries.add(new Country("BR", "Brazil", "https://i.pinimg.com/originals/e4/03/c4/e403c4447a3bd8940459ae4f50856bed.png")); 57 | 58 | 59 | return new JRBeanCollectionDataSource(countries); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /java-jasper/src/main/java/com/hmkcode/Country.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | public class Country { 4 | 5 | private String code; 6 | private String name; 7 | private String url; 8 | 9 | public Country(String code, String name, String url) { 10 | this.code = code; 11 | this.name = name; 12 | this.url = url; 13 | } 14 | 15 | public String getCode() { 16 | return code; 17 | } 18 | 19 | public void setCode(String code) { 20 | this.code = code; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public void setName(String name) { 28 | this.name = name; 29 | } 30 | 31 | public String getUrl() { 32 | return url; 33 | } 34 | 35 | public void setUrl(String url) { 36 | this.url = url; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "Country{" + 42 | "code='" + code + '\'' + 43 | ", name='" + name + '\'' + 44 | ", url='" + url + '\'' + 45 | '}'; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /java-jasper/src/main/resources/report.jrxml: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /java-lambda/README.md: -------------------------------------------------------------------------------- 1 | Using Lambda to Implement Functional Interface Method 2 | ==================================================== 3 | 4 | - We have a *virtual* `Button` that when clicked will call an abstract method **onClick()** of a listener interface `OnClickListener`. 5 | - We need to implement the **onClick()** so that it prints the `Button` name. 6 | 7 | `OnClickListener.java` 8 | 9 | ```java 10 | package com.hmkcode; 11 | 12 | public interface OnClickListener { 13 | void onClick(Button button); 14 | } 15 | ``` 16 | 17 | `Button.java` 18 | 19 | ```java 20 | package com.hmkcode; 21 | 22 | public class Button { 23 | 24 | private OnClickListener onClickListener; 25 | private String name; 26 | 27 | // click the button 28 | public void click(){ 29 | this.onClickListener.onClick(this); 30 | } 31 | 32 | // getters & setters 33 | } 34 | ``` 35 | 36 | - We have three ways to achieve that: 37 | 1. **Implement** `OnClickListener` and override **onClick()** method. 38 | 2. Use `OnClickListener` as an anonymous class. 39 | 3. Use Lambda. 40 | 41 | - Our main class is `App.java` 42 | 43 | ```java 44 | package com.hmkcode; 45 | 46 | public class App 47 | { 48 | public static void main( String[] args ){ 49 | System.out.println( "Running App..." ); 50 | new App().run(); 51 | } 52 | 53 | public void run(){ 54 | 55 | Button myButton = new Button(); 56 | myButton.setName("MyButton"); 57 | 58 | // 1. implements onClickListener 59 | 60 | // 2. anonymous class 61 | 62 | // 3. lambda 63 | 64 | 65 | // click the button 66 | myButton.click(); 67 | } 68 | } 69 | ``` 70 | 71 | ### 1. **Implement** `OnClickListener` and override **onClick()** method 72 | 73 | ```java 74 | public class App implements OnClickListener 75 | { 76 | public static void main( String[] args ){...} 77 | 78 | public void run(){ 79 | 80 | Button myButton = new Button(); 81 | myButton.setName("MyButton"); 82 | 83 | // 1. implements onClickListener 84 | myButton.setOnClickListener(this); 85 | 86 | // click the button 87 | myButton.click(); 88 | } 89 | 90 | @Override 91 | public void onClick(Button button) { 92 | System.out.println(button.getName() +" Clicked! - implements interface"); 93 | 94 | } 95 | } 96 | ``` 97 | 98 | ### 2. Use `OnClickListener` as an anonymous class 99 | 100 | ```java 101 | public class App 102 | { 103 | public static void main( String[] args ){...} 104 | 105 | public void run(){ 106 | 107 | Button myButton = new Button(); 108 | myButton.setName("MyButton"); 109 | 110 | // 2. anonymous class 111 | myButton.setOnClickListener(new OnClickListener() { 112 | @Override 113 | public void onClick(Button button) { 114 | System.out.println(button.getName() +" Clicked! - anonymous class"); 115 | } 116 | }); 117 | 118 | // click the button 119 | myButton.click(); 120 | } 121 | } 122 | ``` 123 | 124 | ### 3. Use Lambda 125 | 126 | ```java 127 | public class App 128 | { 129 | public static void main( String[] args ){...} 130 | 131 | public void run(){ 132 | 133 | Button myButton = new Button(); 134 | myButton.setName("MyButton"); 135 | 136 | // 3. lambda 137 | OnClickListener lambda = button -> { System.out.println(button.getName()+" Clicked! - lambda"); } ; 138 | myButton.setOnClickListener(lambda); 139 | 140 | // click the button 141 | myButton.click(); 142 | } 143 | } 144 | ``` 145 | 146 | *To run the code use* 147 | 148 | ``` 149 | java-lambda>mvn exec:java 150 | ``` 151 | 152 | -------------------------------------------------------------------------------- /java-lambda/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.hmkcode 8 | java-lambda 9 | 1.0-SNAPSHOT 10 | 11 | java-lambda 12 | 13 | 14 | 15 | 16 | maven-compiler-plugin 17 | 3.8.0 18 | 19 | 1.8 20 | 1.8 21 | 22 | 23 | 24 | org.codehaus.mojo 25 | exec-maven-plugin 26 | 1.6.0 27 | 28 | com.hmkcode.App 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /java-lambda/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | public class App implements OnClickListener 5 | { 6 | public static void main( String[] args ){ 7 | System.out.println( "Running App..." ); 8 | new App().run(); 9 | } 10 | 11 | public void run(){ 12 | 13 | Button myButton = new Button(); 14 | myButton.setName("MyButton"); 15 | 16 | // 1. implements onClickListener 17 | //myButton.setOnClickListener(this); 18 | 19 | // 2. anonymous class 20 | /*myButton.setOnClickListener(new OnClickListener() { 21 | @Override 22 | public void onClick(Button button) { 23 | System.out.println(button.getName() +" Clicked! - anonymous class"); 24 | } 25 | }); */ 26 | 27 | // 3. lambda 28 | OnClickListener lambda = button -> { System.out.println(button.getName()+" Clicked! - lambda"); } ; 29 | myButton.setOnClickListener(lambda); 30 | 31 | 32 | // click the button 33 | myButton.click(); 34 | } 35 | 36 | 37 | @Override 38 | public void onClick(Button button) { 39 | System.out.println(button.getName() +" Clicked! - implements interface"); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java-lambda/src/main/java/com/hmkcode/Button.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | public class Button { 4 | 5 | private OnClickListener onClickListener; 6 | private String name; 7 | 8 | public void click(){ 9 | this.onClickListener.onClick(this); 10 | } 11 | 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public OnClickListener getOnClickListener() { 22 | return onClickListener; 23 | } 24 | 25 | public void setOnClickListener(OnClickListener onClickListener) { 26 | this.onClickListener = onClickListener; 27 | } 28 | 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /java-lambda/src/main/java/com/hmkcode/OnClickListener.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | public interface OnClickListener { 5 | void onClick(Button button); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /java-list-map/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /java-list-map/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | java-list-map 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | java-list-map 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 3.8.1 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /java-list-map/src/main/java/com/hmkcode/ListApp.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | 8 | import com.hmkcode.vo.Person; 9 | 10 | public class ListApp 11 | { 12 | 13 | public static void main( String[] args ) 14 | { 15 | 16 | // ( 1 ) List 17 | 18 | // A. Initiate 19 | List arrayList = new ArrayList(); 20 | List linkedList = new LinkedList(); 21 | 22 | // B. Populate 23 | for(Person person:getPersons()){ 24 | arrayList.add(person); 25 | linkedList.add(person); 26 | } 27 | 28 | // --> print 29 | System.out.println("--------- Print All -------------"); 30 | 31 | System.out.println("ArrayList: "+arrayList); 32 | System.out.println("LinkedList: "+linkedList); 33 | 34 | // C. Iterate 35 | System.out.println("--------- Print Iterate by index -------------"); 36 | 37 | for(int i = 0; i < linkedList.size(); i++){ 38 | System.out.println("LinkedList[ "+i+" ]"+linkedList.get(i)); 39 | } 40 | 41 | System.out.println("--------- Print Iterate by for each -------------"); 42 | 43 | //this is an efficient way to iterate 44 | for(Person person:linkedList){ 45 | System.out.println("LinkedList: "+person); 46 | } 47 | 48 | // D. Sort 49 | Collections.sort(linkedList); 50 | 51 | // --> print 52 | System.out.println("--------- Print Sorted List -------------"); 53 | 54 | System.out.println("Sorted LinkedList: "+linkedList); 55 | } 56 | 57 | private static Person[] getPersons(){ 58 | Person[] persons = new Person[5]; 59 | 60 | persons[0] = new Person("Brit", 29); 61 | persons[1] = new Person("John", 32); 62 | persons[2] = new Person("Jack", 27); 63 | persons[3] = new Person("Jenifer", 24); 64 | persons[4] = new Person("Brit", 37); 65 | 66 | return persons; 67 | } 68 | } -------------------------------------------------------------------------------- /java-list-map/src/main/java/com/hmkcode/MapApp.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Map.Entry; 9 | import java.util.TreeMap; 10 | 11 | 12 | import com.hmkcode.vo.Person; 13 | 14 | 15 | public class MapApp 16 | { 17 | 18 | public static void main( String[] args ) 19 | { 20 | 21 | 22 | // ( 1 ) Map 23 | 24 | // A. Initiate 25 | Map hashMap = new HashMap(); 26 | Map treeMap = new TreeMap(); 27 | 28 | // B. Populate 29 | int k = 0 ; 30 | for(Person person:getPersons()){ 31 | hashMap.put(""+k,person); 32 | treeMap.put(""+k++,person); 33 | } 34 | 35 | // --> print 36 | System.out.println("--------- Print All -------------"); 37 | System.out.println("HashMap: "+hashMap); 38 | System.out.println("TreeMap: "+treeMap); 39 | 40 | 41 | // C. Iterate 42 | // --> print 43 | System.out.println("--------- Print Iterate by get(key) -------------"); 44 | for(String key:treeMap.keySet()){ 45 | 46 | System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key)); 47 | } 48 | // --> print 49 | System.out.println("--------- Print Iterate by Entry -------------"); 50 | for(Entry entry:treeMap.entrySet()){ 51 | 52 | System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue()); 53 | } 54 | 55 | // D. Sort by value 56 | TreeMap sorted_map = new TreeMap(new ValueComparator()); 57 | sorted_map.putAll(hashMap); 58 | 59 | 60 | // --> print 61 | System.out.println("--------- Print Sorted Map by Value -------------"); 62 | System.out.println("Sorted HashMap: "+sorted_map); 63 | 64 | 65 | // E. Convert Map to List 66 | 67 | List persons = new ArrayList(sorted_map.values()); 68 | 69 | // --> print 70 | System.out.println("--------- Print List -------------"); 71 | System.out.println("List: "+persons); 72 | } 73 | 74 | private static Person[] getPersons(){ 75 | Person[] persons = new Person[5]; 76 | 77 | persons[0] = new Person("Brit", 29); 78 | persons[1] = new Person("John", 32); 79 | persons[2] = new Person("Jack", 27); 80 | persons[3] = new Person("Jenifer", 24); 81 | persons[4] = new Person("Brit", 37); 82 | 83 | return persons; 84 | } 85 | } 86 | class ValueComparator implements Comparator { 87 | 88 | Map map; 89 | 90 | public ValueComparator(){ 91 | 92 | } 93 | public int compare(Object keyA, Object keyB){ 94 | 95 | return ((String) keyA).compareTo((String) keyB); 96 | 97 | } 98 | } -------------------------------------------------------------------------------- /java-list-map/src/main/java/com/hmkcode/vo/Person.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | public class Person implements Comparable { 4 | 5 | private int age; 6 | private String name; 7 | 8 | public Person(String name, int age){ 9 | this.name = name; 10 | this.age = age; 11 | } 12 | public int getAge() { 13 | return age; 14 | } 15 | public void setAge(int age) { 16 | this.age = age; 17 | } 18 | public String getName() { 19 | return name; 20 | } 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | @Override 25 | public String toString() { 26 | return "Person [age=" + age + ", name=" + name + "]"; 27 | } 28 | @Override 29 | public int compareTo(Person person) { 30 | return this.age-person.getAge(); 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /java-servlet-json/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /java-servlet-json/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | java-servlet-json 7 | 1.0-SNAPSHOT 8 | war 9 | 10 | java-servlet-json 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | javax.servlet 20 | javax.servlet-api 21 | 3.1.0 22 | provided 23 | 24 | 25 | 26 | 27 | com.fasterxml.jackson.core 28 | jackson-core 29 | 2.9.6 30 | 31 | 32 | com.fasterxml.jackson.core 33 | jackson-databind 34 | 2.9.6 35 | 36 | 37 | com.fasterxml.jackson.core 38 | jackson-annotations 39 | 2.9.6 40 | 41 | 42 | 43 | 44 | java-servlet-json 45 | 46 | 47 | org.eclipse.jetty 48 | jetty-maven-plugin 49 | 9.4.11.v20180605 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /java-servlet-json/src/main/java/com/hmkcode/JSONServlet.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.annotation.WebServlet; 10 | import javax.servlet.http.HttpServlet; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import com.fasterxml.jackson.databind.ObjectMapper; 15 | import com.hmkcode.vo.Article; 16 | 17 | @WebServlet("/jsonservlet") 18 | public class JSONServlet extends HttpServlet { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | // This will store all received articles 23 | List
articles = new LinkedList
(); 24 | 25 | /*************************************************** 26 | * URL: /jsonservlet 27 | * doPost(): receives JSON data, parse it, map it and send back as JSON 28 | ****************************************************/ 29 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 30 | throws ServletException, IOException{ 31 | 32 | // 1. get received JSON data from request 33 | BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 34 | String json = ""; 35 | if(br != null){ 36 | json = br.readLine(); 37 | System.out.println(json); 38 | } 39 | 40 | // 2. initiate jackson mapper 41 | ObjectMapper mapper = new ObjectMapper(); 42 | 43 | // 3. Convert received JSON to Article 44 | Article article = mapper.readValue(json, Article.class); 45 | 46 | // 4. Set response type to JSON 47 | response.setContentType("application/json"); 48 | 49 | // 5. Add article to List
50 | articles.add(article); 51 | 52 | // 6. Send List
as JSON to client 53 | mapper.writeValue(response.getOutputStream(), articles); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /java-servlet-json/src/main/java/com/hmkcode/vo/Article.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class Article { 7 | 8 | private String title; 9 | private String url; 10 | private List categories; 11 | private List tags; 12 | 13 | public String getTitle() { 14 | return title; 15 | } 16 | public void setTitle(String title) { 17 | this.title = title; 18 | } 19 | public String getUrl() { 20 | return url; 21 | } 22 | public void setUrl(String url) { 23 | this.url = url; 24 | } 25 | public List getCategories() { 26 | return categories; 27 | } 28 | public void setCategories(List categories) { 29 | this.categories = categories; 30 | } 31 | public List getTags() { 32 | return tags; 33 | } 34 | public void setTags(List tags) { 35 | this.tags = tags; 36 | } 37 | 38 | public void addCategory(String category){ 39 | if(this.categories == null) 40 | this.categories = new LinkedList(); 41 | this.categories.add(category); 42 | } 43 | public void addTag(String tag){ 44 | if(this.tags == null) 45 | this.tags = new LinkedList(); 46 | 47 | this.tags.add(tag); 48 | } 49 | @Override 50 | public String toString() { 51 | return "Article [title=" + title + ", url=" + url + ", categories=" 52 | + categories + ", tags=" + tags + "]"; 53 | } 54 | 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /java-servlet-json/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-servlet-json/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png -------------------------------------------------------------------------------- /java-servlet-json/src/main/webapp/bootstrap/img/glyphicons-halflings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-servlet-json/src/main/webapp/bootstrap/img/glyphicons-halflings.png -------------------------------------------------------------------------------- /java-servlet-json/src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Java Servlet JSON 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |

Java Servlet Send & Receive JSON

20 | 21 | 22 |
23 |
24 | Title 25 | 26 |
27 |
28 |
29 | URL 30 | 31 |
32 |
33 |
34 | Categories 35 | 36 |
37 |
38 |
39 | Tags 40 | 41 |
42 |

43 | 44 |

45 |
46 | 47 | 48 |
49 |
Articles
50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 |
TitleCategoriesTags
58 |
59 | 60 | 61 | -------------------------------------------------------------------------------- /java-servlet-json/src/main/webapp/js/myfunctions.js: -------------------------------------------------------------------------------- 1 | function sendAjax() { 2 | 3 | // get inputs 4 | var article = new Object(); 5 | article.title = $('#title').val(); 6 | article.url = $('#url').val(); 7 | article.categories = $('#categories').val().split(";"); 8 | article.tags = $('#tags').val().split(";"); 9 | 10 | $.ajax({ 11 | url: "jsonservlet", 12 | type: 'POST', 13 | dataType: 'json', 14 | data: JSON.stringify(article), 15 | contentType: 'application/json', 16 | mimeType: 'application/json', 17 | 18 | success: function (data) { 19 | $("tr:has(td)").remove(); 20 | 21 | $.each(data, function (index, article) { 22 | 23 | var td_categories = $(""); 24 | $.each(article.categories, function (i, tag) { 25 | var span = $(""); 26 | span.text(tag); 27 | td_categories.append(span); 28 | }); 29 | 30 | var td_tags = $(""); 31 | $.each(article.tags, function (i, tag) { 32 | var span = $(""); 33 | span.text(tag); 34 | td_tags.append(span); 35 | }); 36 | 37 | $("#added-articles").append($('') 38 | .append($('').html(""+article.title+"")) 39 | .append(td_categories) 40 | .append(td_tags) 41 | ); 42 | 43 | 44 | }); 45 | }, 46 | error:function(data,status,er) { 47 | alert("error: "+data+" status: "+status+" er:"+er); 48 | } 49 | }); 50 | } -------------------------------------------------------------------------------- /java-simple-text-file-reader/src/main/java/com/hmkcode/TextFileReader.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | 8 | public class TextFileReader { 9 | 10 | private BufferedReader buffer; 11 | private String currentLine = ""; 12 | public TextFileReader(){ 13 | 14 | } 15 | 16 | public void open(String file){ 17 | 18 | try { 19 | close(); 20 | 21 | buffer = new BufferedReader(new FileReader(file)); 22 | 23 | } catch (FileNotFoundException e1) { 24 | e1.printStackTrace(); 25 | 26 | } 27 | 28 | } 29 | 30 | public void close(){ 31 | 32 | try { 33 | if(buffer != null){ 34 | buffer.close(); 35 | buffer = null; 36 | } 37 | } catch (IOException e) { 38 | e.printStackTrace(); 39 | } 40 | 41 | } 42 | 43 | public String readLine() throws Exception{ 44 | if(buffer != null){ 45 | currentLine = buffer.readLine(); 46 | 47 | if(currentLine == null) 48 | close(); 49 | 50 | return currentLine; 51 | } 52 | else 53 | throw new Exception("No file to read..."); 54 | } 55 | 56 | public String getCurrent(){ 57 | return this.currentLine; 58 | } 59 | 60 | public boolean isReadable(){ 61 | return (buffer != null && this.currentLine != null); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /java-spi/java-spi-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.hmkcode.api 8 | java-spi-api 9 | 1.0-SNAPSHOT 10 | 11 | java-spi-api 12 | 13 | http://www.example.com 14 | 15 | 16 | UTF-8 17 | 1.7 18 | 1.7 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /java-spi/java-spi-api/src/main/java/com/hmkcode/api/MyService.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.api; 2 | 3 | public interface MyService { 4 | 5 | void doSomething(); 6 | } 7 | -------------------------------------------------------------------------------- /java-spi/java-spi-api/src/main/java/com/hmkcode/api/MyServiceProviderInterface.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.api; 2 | 3 | public interface MyServiceProviderInterface { 4 | 5 | MyService getService(); 6 | } 7 | -------------------------------------------------------------------------------- /java-spi/java-spi-app/lib/java-spi-api-1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-spi/java-spi-app/lib/java-spi-api-1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /java-spi/java-spi-app/lib/java-spi-impl1-1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-spi/java-spi-app/lib/java-spi-impl1-1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /java-spi/java-spi-app/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.hmkcode.app 8 | java-spi-app 9 | 1.0-SNAPSHOT 10 | 11 | java-spi-app 12 | 13 | http://www.example.com 14 | 15 | 16 | UTF-8 17 | 1.7 18 | 1.7 19 | 20 | 21 | 22 | 23 | 24 | com.hmkcode.api 25 | java-spi-api 26 | 1.0-SNAPSHOT 27 | system 28 | ${project.basedir}/lib/java-spi-api-1.0-SNAPSHOT.jar 29 | 30 | 31 | com.hmkcode.impl 32 | java-spi-impl1 33 | 1.0-SNAPSHOT 34 | system 35 | ${project.basedir}/lib/java-spi-impl1-1.0-SNAPSHOT.jar 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /java-spi/java-spi-app/src/main/java/com/hmkcode/app/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.app; 2 | 3 | public class App 4 | { 5 | public static void main( String[] args ) 6 | { 7 | MyServiceLoader.defaultProvider().getService().doSomething(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java-spi/java-spi-app/src/main/java/com/hmkcode/app/MyServiceLoader.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.app; 2 | 3 | import java.nio.file.ProviderNotFoundException; 4 | import java.util.Iterator; 5 | import java.util.ServiceLoader; 6 | 7 | import com.hmkcode.api.MyServiceProviderInterface; 8 | 9 | 10 | public class MyServiceLoader { 11 | 12 | private static final String DEFAULT_PROVIDER = "com.hmkcode.impl.MyServiceProviderImpl1"; 13 | 14 | public static MyServiceProviderInterface defaultProvider() { 15 | return provider(DEFAULT_PROVIDER); 16 | } 17 | 18 | public static MyServiceProviderInterface provider(String providerName) { 19 | ServiceLoader loader = ServiceLoader.load(MyServiceProviderInterface.class); 20 | 21 | Iterator it = loader.iterator(); 22 | while (it.hasNext()) { 23 | MyServiceProviderInterface provider = it.next(); 24 | if (providerName.equals(provider.getClass().getName())) { 25 | return provider; 26 | } 27 | } 28 | throw new ProviderNotFoundException("provider " + providerName + " not found"); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /java-spi/java-spi-impl1/lib/java-spi-api-1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/java-spi/java-spi-impl1/lib/java-spi-api-1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /java-spi/java-spi-impl1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.hmkcode.impl 8 | java-spi-impl1 9 | 1.0-SNAPSHOT 10 | 11 | java-spi-impl1 12 | 13 | http://www.example.com 14 | 15 | 16 | UTF-8 17 | 1.7 18 | 1.7 19 | 20 | 21 | 22 | 23 | com.hmkcode.api 24 | java-spi-api 25 | 1.0-SNAPSHOT 26 | system 27 | ${project.basedir}/lib/java-spi-api-1.0-SNAPSHOT.jar 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /java-spi/java-spi-impl1/src/main/java/com/hmkcode/impl/MyServiceImpl1.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.impl; 2 | 3 | import com.hmkcode.api.MyService; 4 | 5 | public class MyServiceImpl1 implements MyService{ 6 | 7 | @Override 8 | public void doSomething() { 9 | System.out.println("MyServiceImpl1"); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java-spi/java-spi-impl1/src/main/java/com/hmkcode/impl/MyServiceProviderImpl1.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.impl; 2 | 3 | import com.hmkcode.api.MyService; 4 | import com.hmkcode.api.MyServiceProviderInterface; 5 | 6 | public class MyServiceProviderImpl1 implements MyServiceProviderInterface { 7 | 8 | @Override 9 | public MyService getService() { 10 | return new MyServiceImpl1(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /java-spi/java-spi-impl1/src/main/resources/META-INF/services/com.hmkcode.api.MyServiceProviderInterface: -------------------------------------------------------------------------------- 1 | com.hmkcode.impl.MyServiceProviderImpl1 -------------------------------------------------------------------------------- /java-stream/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class App 10 | { 11 | public static void main( String[] args ) 12 | { 13 | String[] arr = new String[]{"a", "b", "c", "d"}; 14 | Stream stream = Arrays.stream(arr); 15 | 16 | stream = Stream.of("a", "b", "c", "d"); 17 | 18 | List list = new LinkedList(); 19 | list.add("a"); 20 | list.add("b"); 21 | stream = list.stream(); 22 | 23 | // forEach() 24 | stream = Stream.of("a", "b", "c", "d"); 25 | stream.forEach(e -> System.out.println(e)); 26 | 27 | // distinct() | count() 28 | stream = Stream.of("a", "b", "c", "d"); 29 | System.out.println(stream.distinct().count()); 30 | 31 | // anyMatch() 32 | stream = Stream.of("a", "b", "c", "d"); 33 | System.out.println(stream.anyMatch(e -> e.contains("a"))); 34 | 35 | // filter() 36 | stream = Stream.of("a", "b", "c", "d"); 37 | stream.filter(e -> e.contains("b")).forEach(e -> System.out.println(e)); 38 | 39 | // map() 40 | stream = Stream.of("a", "b", "c", "d"); 41 | stream.map(e -> e.toUpperCase()).forEach(e -> System.out.println(e)); 42 | 43 | // flatMap() 44 | stream = getBigList().stream().flatMap(lst -> lst.stream()); 45 | stream.forEach(e -> System.out.println(e)); 46 | 47 | //[any|all|none]Match() 48 | System.out.println(Stream.of("a", "b", "c", "d").allMatch( e -> (e.length() == 1))); 49 | System.out.println(Stream.of("a", "b", "c", "d").noneMatch(e -> (e.length() == 2))); 50 | System.out.println(Stream.of("a", "b", "c", "d").anyMatch( e -> e.equals("a") )); 51 | 52 | //reduce() 53 | stream = Stream.of("a", "b", "c", "d"); 54 | System.out.println(stream.reduce("", (x,y) -> apply(x,y))); 55 | 56 | //collect(Collectors) 57 | stream = Stream.of("a", "b", "c", "d"); 58 | System.out.println(stream.collect(Collectors.toList())); 59 | 60 | 61 | } 62 | 63 | private static String apply(String a, String b){ 64 | System.out.println(a+"->"+b); 65 | return a+b; 66 | } 67 | 68 | private static List> getBigList(){ 69 | 70 | List> bigList = new LinkedList>(); 71 | 72 | List list1 = new LinkedList(); 73 | list1.add("a"); 74 | list1.add("b"); 75 | 76 | List list2 = new LinkedList(); 77 | list2.add("c"); 78 | list2.add("d"); 79 | 80 | bigList.add(list1); 81 | bigList.add(list2); 82 | 83 | return bigList; 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /java-unzip/src/main/java/com/hmkcode/Unzip.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.util.zip.ZipEntry; 9 | import java.util.zip.ZipInputStream; 10 | 11 | public class Unzip { 12 | 13 | public static void unzip(String zipFile,String outputPath){ 14 | 15 | if(outputPath == null) 16 | outputPath = ""; 17 | else 18 | outputPath+=File.separator; 19 | 20 | // 1.0 Create output directory 21 | File outputDirectory = new File(outputPath); 22 | 23 | if(outputDirectory.exists()) 24 | outputDirectory.delete(); 25 | 26 | outputDirectory.mkdir(); 27 | 28 | 29 | // 2.0 Unzip (create folders & copy files) 30 | try { 31 | 32 | // 2.1 Get zip input stream 33 | ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile)); 34 | 35 | ZipEntry entry = null; 36 | int len; 37 | byte[] buffer = new byte[1024]; 38 | 39 | // 2.2 Go over each entry "file/folder" in zip file 40 | while((entry = zip.getNextEntry()) != null){ 41 | 42 | if(!entry.isDirectory()){ 43 | System.out.println("-"+entry.getName()); 44 | 45 | // create a new file 46 | File file = new File(outputPath +entry.getName()); 47 | 48 | // create file parent directory if does not exist 49 | if(!new File(file.getParent()).exists()) 50 | new File(file.getParent()).mkdirs(); 51 | 52 | // get new file output stream 53 | FileOutputStream fos = new FileOutputStream(file); 54 | 55 | // copy bytes 56 | while ((len = zip.read(buffer)) > 0) { 57 | fos.write(buffer, 0, len); 58 | } 59 | 60 | fos.close(); 61 | } 62 | 63 | } 64 | 65 | }catch (FileNotFoundException e) { 66 | e.printStackTrace(); 67 | } catch (IOException e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /junit-exception/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /junit-exception/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | junit-exception 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | junit-exception 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 4.11 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /junit-exception/src/test/java/com/hmkcode/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.util.LinkedList; 4 | 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.junit.runner.RunWith; 9 | import org.junit.runners.JUnit4; 10 | 11 | import static org.junit.Assert.assertThat; 12 | import static org.junit.Assert.fail; 13 | import static org.hamcrest.CoreMatchers.is; 14 | 15 | 16 | 17 | @RunWith(JUnit4.class) 18 | public class AppTest 19 | { 20 | 21 | // ( 1 ) Simple way to test exception 22 | @Test(expected= NullPointerException.class) 23 | public void testNull() { 24 | String str = null; 25 | str.toUpperCase(); 26 | } 27 | 28 | // ( 2 ) Test by tyr/catch (test exception message) 29 | @Test 30 | public void testExceptionMessage(){ 31 | try{ 32 | new LinkedList().get(0); 33 | 34 | //if no exception thrown the test will fail with the below message. 35 | fail("Expected an IndexOutOfBoundsException to be thrown"); 36 | 37 | } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) { 38 | 39 | //if no exception message is not the same the test will fail with the below message. 40 | assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0")); 41 | } 42 | 43 | } 44 | 45 | //( 3 ) Test by @Rule & ExpectedException.expect() | ExpectedException.expectMessage() 46 | @Rule 47 | public ExpectedException thrown = ExpectedException.none(); 48 | 49 | @Test 50 | public void testExceptionByRule() throws ArithmeticException { 51 | 52 | thrown.expect(ArithmeticException.class); 53 | thrown.expectMessage("/ by zero"); 54 | 55 | double d = 1 / 0; 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/.classpath: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | mybatis-insert-generatedkey 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | mybatis-insert-generatedkey 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 3.1.0.RELEASE 16 | 17 | 18 | 19 | 20 | com.h2database 21 | h2 22 | 1.3.171 23 | 24 | 25 | junit 26 | junit 27 | 4.11 28 | test 29 | 30 | 31 | org.mybatis 32 | mybatis 33 | 3.2.1 34 | 35 | 36 | org.mybatis 37 | mybatis-spring 38 | 1.2.0 39 | 40 | 41 | org.springframework 42 | spring-core 43 | ${org.springframework.version} 44 | 45 | 46 | org.springframework 47 | spring-expression 48 | ${org.springframework.version} 49 | 50 | 51 | org.springframework 52 | spring-beans 53 | ${org.springframework.version} 54 | 55 | 56 | org.springframework 57 | spring-aop 58 | ${org.springframework.version} 59 | 60 | 61 | org.springframework 62 | spring-context 63 | ${org.springframework.version} 64 | 65 | 66 | org.springframework 67 | spring-context-support 68 | ${org.springframework.version} 69 | 70 | 71 | org.springframework 72 | spring-tx 73 | ${org.springframework.version} 74 | 75 | 76 | org.springframework 77 | spring-jdbc 78 | ${org.springframework.version} 79 | 80 | 81 | org.springframework 82 | spring-orm 83 | ${org.springframework.version} 84 | 85 | 86 | org.springframework 87 | spring-oxm 88 | ${org.springframework.version} 89 | 90 | 91 | org.springframework 92 | spring-web 93 | ${org.springframework.version} 94 | 95 | 96 | org.springframework 97 | spring-webmvc 98 | ${org.springframework.version} 99 | 100 | 101 | org.springframework 102 | spring-webmvc-portlet 103 | ${org.springframework.version} 104 | 105 | 106 | org.springframework 107 | spring-asm 108 | ${org.springframework.version} 109 | 110 | 111 | org.springframework 112 | spring-context-support 113 | ${org.springframework.version} 114 | 115 | 116 | org.springframework 117 | spring-test 118 | ${org.springframework.version} 119 | test 120 | 121 | 122 | 123 | 124 | 125 | maven-compiler-plugin 126 | 2.0.2 127 | 128 | 1.6 129 | 1.6 130 | 131 | 132 | 133 | org.codehaus.mojo 134 | exec-maven-plugin 135 | 136 | 137 | my-execution 138 | compile 139 | 140 | java 141 | 142 | 143 | 144 | 145 | com.hmkcode.spring.mybatis.App 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.spring.mybatis; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.support.ClassPathXmlApplicationContext; 9 | 10 | import com.hmkcode.spring.mybatis.service.Service; 11 | import com.hmkcode.spring.mybatis.vo.MyObject; 12 | 13 | 14 | public class App 15 | { 16 | private static Log log = LogFactory.getLog(App.class); 17 | 18 | public static void main( String[] args ) 19 | { 20 | 21 | ApplicationContext cxt = new ClassPathXmlApplicationContext("spring-config.xml"); 22 | Service service = (Service) cxt.getBean("service"); 23 | 24 | log.info("Running App..."); 25 | 26 | 27 | //( 1 ) INSERT MYOBJECT 28 | System.out.println("( 1 ) insertMyObject(myObject)"); 29 | MyObject myObject = new MyObject(); 30 | myObject.setObjectName("name-2"); 31 | service.insertMyObject(myObject); 32 | System.out.println("myObject.objectId = "+myObject.getObjectId()); 33 | 34 | System.out.println("\n********************************\n"); 35 | 36 | //( 2 ) INSERT MYOBJECT 37 | System.out.println("( 2 ) insertMyObject_Annotation(myObject)"); 38 | myObject = new MyObject(); 39 | myObject.setObjectName("name-3"); 40 | service.insertMyObject_Annotation(myObject); 41 | System.out.println("myObject.objectId = "+myObject.getObjectId()); 42 | 43 | System.out.println("\n********************************\n"); 44 | 45 | //( 3 ) SELECT ALL MYOBJECTS 46 | System.out.println("( 3 ) selectAllMyObjects()"); 47 | List myObjects = service.selectAllMyObjects(); 48 | System.out.println(myObjects); 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/mapper/Mapper.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.spring.mybatis.mapper; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.ibatis.annotations.Insert; 6 | import org.apache.ibatis.annotations.Select; 7 | import org.apache.ibatis.annotations.SelectKey; 8 | 9 | import com.hmkcode.spring.mybatis.vo.MyObject; 10 | 11 | 12 | public interface Mapper { 13 | 14 | //if @Select is used table.column (name) & class.property (name) should be the same 15 | 16 | 17 | @Select("SELECT * FROM myobject_table") 18 | public List selectAllMyObjects(); 19 | 20 | 21 | //SQL query in "Mapper.xml" 22 | public int insertMyObject(MyObject myObject); 23 | 24 | @Insert("INSERT INTO myobject_table (objectId,objectName) VALUES (#{objectId}, #{objectName})") 25 | @SelectKey(statement="SELECT nextVal('my_sequence')", keyProperty="objectId", before=true, resultType=int.class) 26 | int insertMyObject_Annotation(MyObject myObject); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/service/Service.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.spring.mybatis.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.hmkcode.spring.mybatis.mapper.Mapper; 8 | import com.hmkcode.spring.mybatis.vo.MyObject; 9 | 10 | 11 | 12 | public class Service { 13 | 14 | @Autowired 15 | private Mapper mapper; 16 | 17 | public int insertMyObject(MyObject myObject){ 18 | return mapper.insertMyObject(myObject); 19 | } 20 | 21 | public int insertMyObject_Annotation(MyObject myObject){ 22 | return mapper.insertMyObject_Annotation(myObject); 23 | } 24 | public List selectAllMyObjects(){ 25 | return mapper.selectAllMyObjects(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/java/com/hmkcode/spring/mybatis/vo/MyObject.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.spring.mybatis.vo; 2 | 3 | import org.apache.ibatis.type.Alias; 4 | 5 | //@Alias("MyObject") will be used by /src/resources/com/hmkcode/spring/mybatis/mybatis-config.xml 6 | @Alias("MyObject") 7 | public class MyObject { 8 | 9 | private int objectId; 10 | private String objectName; 11 | 12 | public int getObjectId() { 13 | return objectId; 14 | } 15 | 16 | public void setObjectId(int objectId) { 17 | this.objectId = objectId; 18 | } 19 | 20 | public String getObjectName() { 21 | return objectName; 22 | } 23 | 24 | public void setObjectName(String objectName) { 25 | this.objectName = objectName; 26 | } 27 | 28 | public String toString(){ 29 | return "\n Object [ id: "+this.objectId+" - name: "+this.objectName+ "\n]"; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/resources/com/hmkcode/spring/mybatis/mapper/Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | SELECT nextVal('my_sequence') 11 | 12 | 13 | 14 | INSERT INTO myobject_table (objectId,objectName) 15 | VALUES (#{objectId},#{objectName}) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/resources/com/hmkcode/spring/mybatis/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE myobject_table (objectId INT PRIMARY KEY, objectName VARCHAR(255)); 2 | CREATE SEQUENCE my_sequence START WITH 1 INCREMENT BY 1; 3 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/resources/spring-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/main/resources/test-data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO myobject_table (objectId, ObjectName ) VALUES (my_sequence.nextVal,'name-1'); 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /mybatis-insert-generatedkey/src/test/java/com/hmkcode/spring/mybatis/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.spring.mybatis; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.test.context.ContextConfiguration; 11 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 | 13 | import com.hmkcode.spring.mybatis.service.Service; 14 | import com.hmkcode.spring.mybatis.vo.MyObject; 15 | 16 | 17 | 18 | import static org.junit.Assert.assertNotNull; 19 | import static org.junit.Assert.assertTrue;; 20 | 21 | /** 22 | * Unit test for simple App. 23 | */ 24 | 25 | @RunWith(SpringJUnit4ClassRunner.class) 26 | @ContextConfiguration(locations = "/spring-config.xml") 27 | public class AppTest { 28 | 29 | private static Log log = LogFactory.getLog(AppTest.class); 30 | 31 | @Autowired private Service service; 32 | 33 | 34 | @Test 35 | public void testSelectAllMyObjects(){ 36 | log.info("testing selectAllParent()..."); 37 | 38 | List objects = service.selectAllMyObjects(); 39 | 40 | assertNotNull("failure - object is null", objects); 41 | 42 | assertTrue("failure - expected 1 object", objects.size() == 1); 43 | 44 | log.info(objects); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /servlet-file-upload/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /servlet-file-upload/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | servlet-file-upload 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | servlet-file-upload 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | javax.servlet 20 | javax.servlet-api 21 | 3.1.0 22 | 23 | 24 | commons-fileupload 25 | commons-fileupload 26 | 1.3 27 | 28 | 29 | commons-io 30 | commons-io 31 | 2.4 32 | 33 | 34 | com.fasterxml.jackson.core 35 | jackson-core 36 | 2.2.2 37 | 38 | 39 | com.fasterxml.jackson.core 40 | jackson-databind 41 | 2.2.2 42 | 43 | 44 | com.fasterxml.jackson.core 45 | jackson-annotations 46 | 2.2.2 47 | 48 | 49 | 50 | 51 | servlet-file-upload 52 | 53 | 54 | org.eclipse.jetty 55 | jetty-maven-plugin 56 | 9.0.4.v20130625 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/java/com/hmkcode/FileUploadServlet.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.annotation.MultipartConfig; 10 | import javax.servlet.http.HttpServlet; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | import com.fasterxml.jackson.databind.ObjectMapper; 14 | import com.hmkcode.vo.FileMeta; 15 | 16 | //this to be used with Java Servlet 3.0 API 17 | @MultipartConfig 18 | public class FileUploadServlet extends HttpServlet { 19 | 20 | private static final long serialVersionUID = 1L; 21 | 22 | // this will store uploaded files 23 | private static List files = new LinkedList(); 24 | /*************************************************** 25 | * URL: /upload 26 | * doPost(): upload the files and other parameters 27 | ****************************************************/ 28 | protected void doPost(HttpServletRequest request, HttpServletResponse response) 29 | throws ServletException, IOException{ 30 | 31 | // 1. Upload File Using Java Servlet API 32 | //files.addAll(MultipartRequestHandler.uploadByJavaServletAPI(request)); 33 | 34 | // 1. Upload File Using Apache FileUpload 35 | files.addAll(MultipartRequestHandler.uploadByApacheFileUpload(request)); 36 | 37 | // Remove some files 38 | while(files.size() > 20) 39 | { 40 | files.remove(0); 41 | } 42 | 43 | // 2. Set response type to json 44 | response.setContentType("application/json"); 45 | 46 | // 3. Convert List into JSON format 47 | ObjectMapper mapper = new ObjectMapper(); 48 | 49 | // 4. Send resutl to client 50 | mapper.writeValue(response.getOutputStream(), files); 51 | 52 | } 53 | /*************************************************** 54 | * URL: /upload?f=value 55 | * doGet(): get file of index "f" from List as an attachment 56 | ****************************************************/ 57 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 58 | throws ServletException, IOException{ 59 | 60 | // 1. Get f from URL upload?f="?" 61 | String value = request.getParameter("f"); 62 | 63 | // 2. Get the file of index "f" from the list "files" 64 | FileMeta getFile = files.get(Integer.parseInt(value)); 65 | 66 | try { 67 | // 3. Set the response content type = file content type 68 | response.setContentType(getFile.getFileType()); 69 | 70 | // 4. Set header Content-disposition 71 | response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\""); 72 | 73 | // 5. Copy file inputstream to response outputstream 74 | InputStream input = getFile.getContent(); 75 | OutputStream output = response.getOutputStream(); 76 | byte[] buffer = new byte[1024*10]; 77 | 78 | for (int length = 0; (length = input.read(buffer)) > 0;) { 79 | output.write(buffer, 0, length); 80 | } 81 | 82 | output.close(); 83 | input.close(); 84 | }catch (IOException e) { 85 | e.printStackTrace(); 86 | } 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/java/com/hmkcode/MultipartRequestHandler.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.Part; 10 | import org.apache.commons.fileupload.FileItem; 11 | import org.apache.commons.fileupload.FileUploadException; 12 | import org.apache.commons.fileupload.disk.DiskFileItemFactory; 13 | import org.apache.commons.fileupload.servlet.ServletFileUpload; 14 | 15 | import com.hmkcode.vo.FileMeta; 16 | 17 | public class MultipartRequestHandler { 18 | 19 | 20 | 21 | public static List uploadByJavaServletAPI(HttpServletRequest request) throws IOException, ServletException{ 22 | 23 | List files = new LinkedList(); 24 | 25 | // 1. Get all parts 26 | Collection parts = request.getParts(); 27 | 28 | // 2. Get paramter "twitter" 29 | String twitter = request.getParameter("twitter"); 30 | 31 | // 3. Go over each part 32 | FileMeta temp = null; 33 | for(Part part:parts){ 34 | 35 | // 3.1 if part is multiparts "file" 36 | if(part.getContentType() != null){ 37 | 38 | // 3.2 Create a new FileMeta object 39 | temp = new FileMeta(); 40 | temp.setFileName(getFilename(part)); 41 | temp.setFileSize(part.getSize()/1024 +" Kb"); 42 | temp.setFileType(part.getContentType()); 43 | temp.setContent(part.getInputStream()); 44 | temp.setTwitter(twitter); 45 | 46 | // 3.3 Add created FileMeta object to List files 47 | files.add(temp); 48 | 49 | } 50 | } 51 | return files; 52 | } 53 | 54 | public static List uploadByApacheFileUpload(HttpServletRequest request) throws IOException, ServletException{ 55 | 56 | List files = new LinkedList(); 57 | 58 | // 1. Check request has multipart content 59 | boolean isMultipart = ServletFileUpload.isMultipartContent(request); 60 | FileMeta temp = null; 61 | 62 | // 2. If yes (it has multipart "files") 63 | if(isMultipart){ 64 | 65 | // 2.1 instantiate Apache FileUpload classes 66 | DiskFileItemFactory factory = new DiskFileItemFactory(); 67 | ServletFileUpload upload = new ServletFileUpload(factory); 68 | 69 | 70 | // 2.2 Parse the request 71 | try { 72 | 73 | // 2.3 Get all uploaded FileItem 74 | List items = upload.parseRequest(request); 75 | String twitter = ""; 76 | 77 | // 2.4 Go over each FileItem 78 | for(FileItem item:items){ 79 | 80 | // 2.5 if FileItem is not of type "file" 81 | if (item.isFormField()) { 82 | 83 | // 2.6 Search for "twitter" parameter 84 | if(item.getFieldName().equals("twitter")) 85 | twitter = item.getString(); 86 | 87 | } else { 88 | 89 | // 2.7 Create FileMeta object 90 | temp = new FileMeta(); 91 | temp.setFileName(item.getName()); 92 | temp.setContent(item.getInputStream()); 93 | temp.setFileType(item.getContentType()); 94 | temp.setFileSize(item.getSize()/1024+ "Kb"); 95 | 96 | // 2.7 Add created FileMeta object to List files 97 | files.add(temp); 98 | 99 | } 100 | } 101 | 102 | // 2.8 Set "twitter" parameter 103 | for(FileMeta fm:files){ 104 | fm.setTwitter(twitter); 105 | } 106 | 107 | } catch (FileUploadException e) { 108 | e.printStackTrace(); 109 | } 110 | } 111 | return files; 112 | } 113 | 114 | 115 | // this method is used to get file name out of request headers 116 | // 117 | private static String getFilename(Part part) { 118 | for (String cd : part.getHeader("content-disposition").split(";")) { 119 | if (cd.trim().startsWith("filename")) { 120 | String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); 121 | return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix. 122 | } 123 | } 124 | return null; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/java/com/hmkcode/vo/FileMeta.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.io.InputStream; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | 6 | 7 | @JsonIgnoreProperties({"content"}) 8 | public class FileMeta { 9 | 10 | 11 | 12 | private String fileName; 13 | private String fileSize; 14 | private String fileType; 15 | private String twitter; 16 | 17 | 18 | private InputStream content; 19 | 20 | 21 | 22 | public String getFileName() { 23 | return fileName; 24 | } 25 | public void setFileName(String fileName) { 26 | this.fileName = fileName; 27 | } 28 | public String getFileSize() { 29 | return fileSize; 30 | } 31 | public void setFileSize(String fileSize) { 32 | this.fileSize = fileSize; 33 | } 34 | public String getFileType() { 35 | return fileType; 36 | } 37 | public void setFileType(String fileType) { 38 | this.fileType = fileType; 39 | } 40 | public InputStream getContent(){ 41 | return this.content; 42 | } 43 | public void setContent(InputStream content){ 44 | this.content = content; 45 | } 46 | public String getTwitter(){ 47 | return this.twitter; 48 | } 49 | public void setTwitter(String twitter){ 50 | this.twitter = twitter; 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "FileMeta [fileName=" + fileName + ", fileSize=" + fileSize 56 | + ", fileType=" + fileType + "]"; 57 | } 58 | 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | Archetype Created Web Application 8 | 9 | index.html 10 | 11 | 12 | 13 | upload 14 | com.hmkcode.FileUploadServlet 15 | 16 | 17 | upload 18 | /upload 19 | 20 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/bootstrap/img/glyphicons-halflings-white.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/bootstrap/img/glyphicons-halflings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/bootstrap/img/glyphicons-halflings.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/css/dropzone.css: -------------------------------------------------------------------------------- 1 | #dropzone { 2 | background: #ccccc; 3 | width: 150px; 4 | height: 50px; 5 | line-height: 50px; 6 | text-align: center; 7 | font-weight: bold; 8 | } 9 | #dropzone.in { 10 | width: 600px; 11 | height: 200px; 12 | line-height: 200px; 13 | font-size: larger; 14 | } 15 | #dropzone.hover { 16 | background: lawngreen; 17 | } 18 | #dropzone.fade { 19 | -webkit-transition: all 0.3s ease-out; 20 | -moz-transition: all 0.3s ease-out; 21 | -ms-transition: all 0.3s ease-out; 22 | -o-transition: all 0.3s ease-out; 23 | transition: all 0.3s ease-out; 24 | opacity: 1; 25 | } -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/css/mystyle.css: -------------------------------------------------------------------------------- 1 | #main{ 2 | 3 | border:1px #F2F2F2 solid; 4 | padding:10px; 5 | margin:5px; 6 | min-width:1020px; 7 | text-align:center; 8 | 9 | } 10 | 11 | #input-div{ 12 | width:500px; 13 | display:inline-block; 14 | vertical-align:top; 15 | padding:5px; 16 | border:1px #F2F2F2 solid; 17 | 18 | } 19 | 20 | #ref-div{ 21 | width:500px; 22 | display:inline-block; 23 | 24 | vertical-align:top; 25 | padding:5px; 26 | } 27 | 28 | #user_twitter{ 29 | 30 | text-align:center; 31 | } -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/css/style.css: -------------------------------------------------------------------------------- 1 | #header{ 2 | height:95px; 3 | min-width:720px; 4 | border-bottom:1px #E5E5E5 solid; 5 | /*background-color:#F1F1F1; */ 6 | background:white url('../img/tech-stack.jpg') repeat-x; 7 | margin-left:180px; 8 | 9 | } 10 | #site-title-content{ 11 | background-color:#333; 12 | display:inline-block; 13 | float:left; 14 | width:180px; 15 | height:76px; 16 | padding:0px; 17 | padding-top:20px; 18 | 19 | } 20 | #site-title-content:hover{ 21 | background-color:#333; 22 | 23 | } 24 | 25 | h2.latest-post-title{ 26 | font-family: 'Didact Gothic', sans-serif; 27 | } 28 | 29 | h3.site-header { 30 | margin:0; 31 | padding:0; 32 | text-align:center; 33 | 34 | 35 | } 36 | h3.site-header a{ 37 | color:#fff; 38 | text-decoration: none; 39 | 40 | } 41 | h3.site-header a:hover { 42 | color: rgb(33, 117, 155); 43 | text-decoration: none; 44 | } 45 | 46 | h4.site-description{ 47 | font-weight: normal; 48 | font-size: 12px; 49 | line-height: 1.84615; 50 | color: #ccc; 51 | margin:0; 52 | padding:0; 53 | text-align:center; 54 | font-family: "Open Sans",Helvetica,Arial,sans-serif; 55 | } 56 | .social-button{ 57 | padding:10px; 58 | text-align:right; 59 | border-bottom:1px solid rgb(235, 235, 235); 60 | background:rgb(242, 242, 242); 61 | } 62 | .icon img{ 63 | width: 32px; 64 | } 65 | #icon-bar{ 66 | height:40px; 67 | } 68 | .tech-icons { 69 | padding:5px; 70 | border-bottom:1px solid rgb(235, 235, 235); 71 | text-align:center; 72 | } 73 | .tech-icons span{ 74 | padding:2px; 75 | display:inline-block; 76 | width:110px; 77 | border:1px rgb(235, 235, 235) solid; 78 | border-radius:15px; 79 | } 80 | .tech-icons span:hover{ 81 | 82 | border:1px rgb(33, 117, 155) solid; 83 | cursor:pointer; 84 | } -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/img/facebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/img/facebook.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/img/gae-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/img/gae-logo.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/img/googleplus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/img/googleplus.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/img/tech-stack.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/img/tech-stack.jpg -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/img/twitter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/servlet-file-upload/src/main/webapp/img/twitter.png -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jQuery File Upload Example 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 31 |

32 | Code First! 33 |

34 |
35 | 37 | 42 | 43 |

Servlet jQuery File Upload

44 | 45 | 46 |
47 | Your Twitter 48 |
49 | @ 50 | 51 |
52 |
53 |
54 | 55 | 56 | 57 |
Drop files here
58 | 59 |
60 |
61 |
62 |
Max File Size: 2 Mb - Display last 20 files
63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 |
File NameFile SizeFile TypeDownloadUploaded By
73 |
74 | 75 | 76 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/js/jquery.iframe-transport.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery Iframe Transport Plugin 1.6.1 3 | * https://github.com/blueimp/jQuery-File-Upload 4 | * 5 | * Copyright 2011, Sebastian Tschan 6 | * https://blueimp.net 7 | * 8 | * Licensed under the MIT license: 9 | * http://www.opensource.org/licenses/MIT 10 | */ 11 | 12 | /*jslint unparam: true, nomen: true */ 13 | /*global define, window, document */ 14 | 15 | (function (factory) { 16 | 'use strict'; 17 | if (typeof define === 'function' && define.amd) { 18 | // Register as an anonymous AMD module: 19 | define(['jquery'], factory); 20 | } else { 21 | // Browser globals: 22 | factory(window.jQuery); 23 | } 24 | }(function ($) { 25 | 'use strict'; 26 | 27 | // Helper variable to create unique names for the transport iframes: 28 | var counter = 0; 29 | 30 | // The iframe transport accepts three additional options: 31 | // options.fileInput: a jQuery collection of file input fields 32 | // options.paramName: the parameter name for the file form data, 33 | // overrides the name property of the file input field(s), 34 | // can be a string or an array of strings. 35 | // options.formData: an array of objects with name and value properties, 36 | // equivalent to the return data of .serializeArray(), e.g.: 37 | // [{name: 'a', value: 1}, {name: 'b', value: 2}] 38 | $.ajaxTransport('iframe', function (options) { 39 | if (options.async) { 40 | var form, 41 | iframe, 42 | addParamChar; 43 | return { 44 | send: function (_, completeCallback) { 45 | form = $('
'); 46 | form.attr('accept-charset', options.formAcceptCharset); 47 | addParamChar = /\?/.test(options.url) ? '&' : '?'; 48 | // XDomainRequest only supports GET and POST: 49 | if (options.type === 'DELETE') { 50 | options.url = options.url + addParamChar + '_method=DELETE'; 51 | options.type = 'POST'; 52 | } else if (options.type === 'PUT') { 53 | options.url = options.url + addParamChar + '_method=PUT'; 54 | options.type = 'POST'; 55 | } else if (options.type === 'PATCH') { 56 | options.url = options.url + addParamChar + '_method=PATCH'; 57 | options.type = 'POST'; 58 | } 59 | // javascript:false as initial iframe src 60 | // prevents warning popups on HTTPS in IE6. 61 | // IE versions below IE8 cannot set the name property of 62 | // elements that have already been added to the DOM, 63 | // so we set the name along with the iframe HTML markup: 64 | iframe = $( 65 | '' 67 | ).bind('load', function () { 68 | var fileInputClones, 69 | paramNames = $.isArray(options.paramName) ? 70 | options.paramName : [options.paramName]; 71 | iframe 72 | .unbind('load') 73 | .bind('load', function () { 74 | var response; 75 | // Wrap in a try/catch block to catch exceptions thrown 76 | // when trying to access cross-domain iframe contents: 77 | try { 78 | response = iframe.contents(); 79 | // Google Chrome and Firefox do not throw an 80 | // exception when calling iframe.contents() on 81 | // cross-domain requests, so we unify the response: 82 | if (!response.length || !response[0].firstChild) { 83 | throw new Error(); 84 | } 85 | } catch (e) { 86 | response = undefined; 87 | } 88 | // The complete callback returns the 89 | // iframe content document as response object: 90 | completeCallback( 91 | 200, 92 | 'success', 93 | {'iframe': response} 94 | ); 95 | // Fix for IE endless progress bar activity bug 96 | // (happens on form submits to iframe targets): 97 | $('') 98 | .appendTo(form); 99 | form.remove(); 100 | }); 101 | form 102 | .prop('target', iframe.prop('name')) 103 | .prop('action', options.url) 104 | .prop('method', options.type); 105 | if (options.formData) { 106 | $.each(options.formData, function (index, field) { 107 | $('') 108 | .prop('name', field.name) 109 | .val(field.value) 110 | .appendTo(form); 111 | }); 112 | } 113 | if (options.fileInput && options.fileInput.length && 114 | options.type === 'POST') { 115 | fileInputClones = options.fileInput.clone(); 116 | // Insert a clone for each file input field: 117 | options.fileInput.after(function (index) { 118 | return fileInputClones[index]; 119 | }); 120 | if (options.paramName) { 121 | options.fileInput.each(function (index) { 122 | $(this).prop( 123 | 'name', 124 | paramNames[index] || options.paramName 125 | ); 126 | }); 127 | } 128 | // Appending the file input fields to the hidden form 129 | // removes them from their original location: 130 | form 131 | .append(options.fileInput) 132 | .prop('enctype', 'multipart/form-data') 133 | // enctype must be set as encoding for IE: 134 | .prop('encoding', 'multipart/form-data'); 135 | } 136 | form.submit(); 137 | // Insert the file input fields at their original location 138 | // by replacing the clones with the originals: 139 | if (fileInputClones && fileInputClones.length) { 140 | options.fileInput.each(function (index, input) { 141 | var clone = $(fileInputClones[index]); 142 | $(input).prop('name', clone.prop('name')); 143 | clone.replaceWith(input); 144 | }); 145 | } 146 | }); 147 | form.append(iframe).appendTo(document.body); 148 | }, 149 | abort: function () { 150 | if (iframe) { 151 | // javascript:false as iframe src aborts the request 152 | // and prevents warning popups on HTTPS in IE6. 153 | // concat is used to avoid the "Script URL" JSLint error: 154 | iframe 155 | .unbind('load') 156 | .prop('src', 'javascript'.concat(':false;')); 157 | } 158 | if (form) { 159 | form.remove(); 160 | } 161 | } 162 | }; 163 | } 164 | }); 165 | 166 | // The iframe transport returns the iframe content document as response. 167 | // The following adds converters from iframe to text, json, html, and script: 168 | $.ajaxSetup({ 169 | converters: { 170 | 'iframe text': function (iframe) { 171 | return iframe && $(iframe[0].body).text(); 172 | }, 173 | 'iframe json': function (iframe) { 174 | return iframe && $.parseJSON($(iframe[0].body).text()); 175 | }, 176 | 'iframe html': function (iframe) { 177 | return iframe && $(iframe[0].body).html(); 178 | }, 179 | 'iframe script': function (iframe) { 180 | return iframe && $.globalEval($(iframe[0].body).text()); 181 | } 182 | } 183 | }); 184 | 185 | })); 186 | -------------------------------------------------------------------------------- /servlet-file-upload/src/main/webapp/js/myuploadfunction.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | 3 | $('#fileupload').fileupload({ 4 | 5 | dataType: 'json', 6 | 7 | done: function (e, data) { 8 | $("tr:has(td)").remove(); 9 | $.each(data.result, function (index, file) { 10 | 11 | 12 | $("#uploaded-files").append( 13 | $('') 14 | .append($('').text(file.fileName)) 15 | .append($('').text(file.fileSize)) 16 | .append($('').text(file.fileType)) 17 | .append($('').html("Click")) 18 | .append($('').text("@"+file.twitter)) 19 | 20 | )//end $("#uploaded-files").append() 21 | }); 22 | }, 23 | 24 | progressall: function (e, data) { 25 | var progress = parseInt(data.loaded / data.total * 100, 10); 26 | $('#progress .bar').css( 27 | 'width', 28 | progress + '%' 29 | ); 30 | }, 31 | 32 | dropZone: $('#dropzone') 33 | }).bind('fileuploadsubmit', function (e, data) { 34 | // The example input, doesn't have to be part of the upload form: 35 | var twitter = $('#twitter'); 36 | data.formData = {twitter: twitter.val()}; 37 | }); 38 | 39 | }); -------------------------------------------------------------------------------- /simple-junit/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /simple-junit/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | simple-junit 4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. 5 | 6 | 7 | 8 | org.eclipse.jdt.core.javabuilder 9 | 10 | 11 | 12 | org.eclipse.jdt.core.javanature 13 | 14 | -------------------------------------------------------------------------------- /simple-junit/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | simple-junit 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | simple-junit 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 4.11 22 | test 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /simple-junit/src/main/java/com/hmkcode/junit/Math.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.junit; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class Math 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | 14 | public double sum(double x, double y){ 15 | return x+y; 16 | } 17 | public double multiply(double x, double y){ 18 | return x*y; 19 | } 20 | public double divide(double x, double y){ 21 | return x/y; 22 | } 23 | public double subtract(double x, double y){ 24 | return x - y; 25 | } 26 | 27 | 28 | 29 | } -------------------------------------------------------------------------------- /simple-junit/src/test/java/com/hmkcode/junit/MathTest.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.junit; 2 | 3 | import static org.junit.Assert.assertThat; 4 | 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.Ignore; 8 | import org.junit.rules.Timeout; 9 | import org.junit.runner.RunWith; 10 | import org.junit.runners.JUnit4; 11 | import static org.hamcrest.CoreMatchers.not; 12 | import static org.hamcrest.CoreMatchers.is; 13 | 14 | 15 | /** 16 | * Tests for {@link Math}. 17 | * 18 | * @author hmkcode@gmail.com (Hani HMK) 19 | */ 20 | @RunWith(JUnit4.class) 21 | public class MathTest { 22 | 23 | @Rule 24 | public Timeout globalTimeout = new Timeout(3000); // 3 seconds max per method tested 25 | 26 | 27 | com.hmkcode.junit.Math math = new com.hmkcode.junit.Math(); 28 | 29 | 30 | @Test 31 | @Ignore 32 | public void testAssertNotNull() { 33 | org.junit.Assert.assertNotNull("should not be null", math); 34 | } 35 | 36 | @Test 37 | public void testSum(){ 38 | org.junit.Assert.assertTrue("failure - not equal", math.sum(3, 2) == 5); 39 | 40 | //to test timeout 41 | /*for (;;) { 42 | }*/ 43 | } 44 | 45 | @Test 46 | public void testMultiply(){ 47 | org.junit.Assert.assertTrue("failure - not equal", math.multiply(3, 2) == 6); 48 | } 49 | 50 | @Test 51 | public void testDivide(){ 52 | double x = 3,y = 2; 53 | assertThat("failure - can't divide by 0",y, is(not(0.0))); 54 | org.junit.Assert.assertTrue("failure - not equal", math.divide(x, y) == 1.5); 55 | } 56 | 57 | @Test 58 | public void testSubtract(){ 59 | org.junit.Assert.assertTrue("failure - not equal", math.subtract(3, 2) == 1); 60 | } 61 | 62 | 63 | } -------------------------------------------------------------------------------- /simple-junit/target/classes/com/hmkcode/junit/Math.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/simple-junit/target/classes/com/hmkcode/junit/Math.class -------------------------------------------------------------------------------- /simple-junit/target/surefire-reports/TEST-com.hmkcode.junit.MathTest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 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 | -------------------------------------------------------------------------------- /simple-junit/target/surefire-reports/com.hmkcode.junit.MathTest.txt: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------------- 2 | Test set: com.hmkcode.junit.MathTest 3 | ------------------------------------------------------------------------------- 4 | Tests run: 5, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.06 sec 5 | -------------------------------------------------------------------------------- /simple-junit/target/test-classes/com/hmkcode/junit/MathTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/22alo/Java5/6c5c149014c5686b3abb51c9f0e0c0165740d793/simple-junit/target/test-classes/com/hmkcode/junit/MathTest.class -------------------------------------------------------------------------------- /webservlet-annotation/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /webservlet-annotation/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 4.0.0 6 | 7 | com.hmkcode 8 | webservlet-annotation 9 | 1.0-SNAPSHOT 10 | war 11 | 12 | webservlet-annotation 13 | 14 | 15 | 16 | 17 | javax 18 | javaee-api 19 | 7.0-b82 20 | provided 21 | 22 | 23 | 24 | 25 | 26 | 27 | org.apache.maven.plugins 28 | maven-compiler-plugin 29 | 2.3.2 30 | 31 | 1.6 32 | 1.6 33 | 34 | 35 | 36 | org.eclipse.jetty 37 | jetty-maven-plugin 38 | 9.0.3.v20130506 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /webservlet-annotation/src/main/java/com/hmkcode/MyServlet.java: -------------------------------------------------------------------------------- 1 | 2 | package com.hmkcode; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | 7 | import javax.servlet.annotation.WebServlet; 8 | import javax.servlet.http.HttpServlet; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | 13 | @WebServlet(urlPatterns = {"/servlet"}) 14 | public class MyServlet extends HttpServlet { 15 | 16 | 17 | private static final long serialVersionUID = 1L; 18 | 19 | @Override 20 | protected void doGet(HttpServletRequest request, HttpServletResponse response) { 21 | response.setContentType("text/html;charset=UTF-8"); 22 | try{ 23 | PrintWriter out = response.getWriter(); 24 | out.println("

Hello @WebServlet

"); 25 | } catch (IOException ioe) { 26 | 27 | } 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /webservlet-annotation/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | webservlet-annotation 9 | 10 | index.jsp 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /webservlet-annotation/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 3 | 5 | 6 | 7 | 8 | 9 | @WebServlet 10 | 11 | 12 |

@WebServlet

13 | 14 | Test MyAnnotatedServlet
15 | 16 | 17 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-app-client/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-app-client/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | com.hmkcode 6 | websocket-app-client 7 | 1.0-SNAPSHOT 8 | jar 9 | 4.0.0 10 | websocket-app-client 11 | 12 | 13 | 14 | 15 | java.net-promoted 16 | https://maven.java.net/content/groups/promoted/ 17 | 18 | 19 | 20 | 21 | 22 | javax 23 | javaee-api 24 | 7.0-b82 25 | 26 | 27 | org.glassfish.tyrus 28 | tyrus-client 29 | 1.0-rc3 30 | 31 | 32 | org.glassfish.tyrus 33 | tyrus-container-grizzly 34 | 1.0-rc3 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.apache.maven.plugins 42 | maven-compiler-plugin 43 | 2.3.2 44 | 45 | 1.7 46 | 1.7 47 | 48 | 49 | 50 | org.codehaus.mojo 51 | exec-maven-plugin 52 | 53 | 54 | my-execution 55 | compile 56 | 57 | java 58 | 59 | 60 | 61 | 62 | com.hmkcode.App 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-app-client/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | 2 | package com.hmkcode; 3 | 4 | import java.io.BufferedReader; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | import java.net.URI; 8 | import javax.websocket.ContainerProvider; 9 | import javax.websocket.DeploymentException; 10 | import javax.websocket.Session; 11 | import javax.websocket.WebSocketContainer; 12 | 13 | public class App { 14 | 15 | public Session session; 16 | 17 | protected void start() 18 | { 19 | 20 | WebSocketContainer container = ContainerProvider.getWebSocketContainer(); 21 | 22 | String uri = "ws://localhost:8080/websocket-glassfish-server/websocket/desktop-client"; 23 | System.out.println("Connecting to " + uri); 24 | try { 25 | session = container.connectToServer(MyClient.class, URI.create(uri)); 26 | } catch (DeploymentException e) { 27 | e.printStackTrace(); 28 | } catch (IOException e) { 29 | e.printStackTrace(); 30 | } 31 | 32 | } 33 | public static void main(String args[]){ 34 | App client = new App(); 35 | client.start(); 36 | 37 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 38 | String input = ""; 39 | try { 40 | do{ 41 | input = br.readLine(); 42 | if(!input.equals("exit")) 43 | client.session.getBasicRemote().sendText(input); 44 | 45 | }while(!input.equals("exit")); 46 | 47 | } catch (IOException e) { 48 | // TODO Auto-generated catch block 49 | e.printStackTrace(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-app-client/src/main/java/com/hmkcode/MyClient.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | import javax.websocket.ClientEndpoint; 5 | import javax.websocket.OnError; 6 | import javax.websocket.OnMessage; 7 | import javax.websocket.OnOpen; 8 | import javax.websocket.Session; 9 | 10 | @ClientEndpoint 11 | public class MyClient { 12 | @OnOpen 13 | public void onOpen(Session session) { 14 | System.out.println("Connected to endpoint: " + session.getBasicRemote()); 15 | try { 16 | session.getBasicRemote().sendText("Hello"); 17 | } catch (IOException ex) { 18 | } 19 | } 20 | 21 | @OnMessage 22 | public void onMessage(String message) { 23 | System.out.println(message); 24 | } 25 | 26 | @OnError 27 | public void onError(Throwable t) { 28 | t.printStackTrace(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | com.hmkcode 6 | websocket-glassfish-server 7 | 1.0-SNAPSHOT 8 | war 9 | 4.0.0 10 | websocket-glassfish-server 11 | 12 | 13 | 14 | java.net-promoted 15 | https://maven.java.net/content/groups/promoted/ 16 | 17 | 18 | 19 | 20 | 21 | javax 22 | javaee-api 23 | 7.0-b82 24 | provided 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.apache.maven.plugins 33 | maven-compiler-plugin 34 | 2.3.2 35 | 36 | 1.7 37 | 1.7 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/src/main/java/com/hmkcode/MyServerEndpoint.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | import java.io.IOException; 4 | import java.util.LinkedList; 5 | import javax.websocket.EncodeException; 6 | import javax.websocket.OnClose; 7 | import javax.websocket.OnMessage; 8 | import javax.websocket.OnOpen; 9 | import javax.websocket.Session; 10 | import javax.websocket.server.PathParam; 11 | import javax.websocket.server.ServerEndpoint; 12 | 13 | @ServerEndpoint(value="/websocket/{client-id}") 14 | public class MyServerEndpoint { 15 | 16 | private static final LinkedList clients = new LinkedList(); 17 | 18 | @OnOpen 19 | public void onOpen(Session session) { 20 | clients.add(session); 21 | } 22 | @OnMessage 23 | public void onMessage(String message,@PathParam("client-id") String clientId) { 24 | for (Session client : clients) { 25 | try { 26 | client.getBasicRemote().sendObject(clientId+": "+message); 27 | 28 | } catch (IOException e) { 29 | e.printStackTrace(); 30 | } catch (EncodeException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | @OnClose 36 | public void onClose(Session peer) { 37 | clients.remove(peer); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | websocket-glassfish-server 9 | 10 | index.htm 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/src/main/webapp/index.htm: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Java API for WebSocket (JSR-356) 7 | 8 | 9 | 10 | 11 | 12 |
13 |

Java API for WebSocket (JSR-356)

14 |
15 | Not Connected 16 |
17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
#SenderMessage
29 |
30 | 31 | 32 | -------------------------------------------------------------------------------- /websocket-java-api/websocket-glassfish-server/src/main/webapp/websocket.js: -------------------------------------------------------------------------------- 1 | var URL = "ws://localhost:8080/websocket-glassfish-server/websocket/web-client"; 2 | var websocket; 3 | 4 | $(document).ready(function(){ 5 | connect(); 6 | }); 7 | 8 | function connect(){ 9 | websocket = new WebSocket(URL); 10 | websocket.onopen = function(evnt) { onOpen(evnt) }; 11 | websocket.onmessage = function(evnt) { onMessage(evnt) }; 12 | websocket.onerror = function(evnt) { onError(evnt) }; 13 | } 14 | function sendMessage() { 15 | websocket.send($("#message").val()); 16 | } 17 | function onOpen() { 18 | updateStatus("connected") 19 | } 20 | function onMessage(evnt) { 21 | if (typeof evnt.data == "string") { 22 | 23 | $("#received_messages").append( 24 | $('') 25 | .append($('').text("1")) 26 | .append($('').text(evnt.data.substring(0,evnt.data.indexOf(":")))) 27 | .append($('').text(evnt.data.substring(evnt.data.indexOf(":")+1)))); 28 | } 29 | } 30 | function onError(evnt) { 31 | alert('ERROR: ' + evnt.data); 32 | } 33 | function updateStatus(status){ 34 | if(status == "connected"){ 35 | $("#status").removeClass (function (index, css) { 36 | return (css.match (/\blabel-\S+/g) || []).join(' ') 37 | }); 38 | $("#status").text(status).addClass("label-success"); 39 | } 40 | } -------------------------------------------------------------------------------- /xstream-java-xml/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /xstream-java-xml/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hmkcode 6 | xstream-java-xml 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | xstream-java-xml 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | com.thoughtworks.xstream 20 | xstream 21 | 1.4.4 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /xstream-java-xml/src/main/java/com/hmkcode/App.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode; 2 | 3 | 4 | import com.hmkcode.vo.Article; 5 | import com.thoughtworks.xstream.XStream; 6 | 7 | 8 | public class App 9 | { 10 | public static void main( String[] args ) 11 | { 12 | 13 | XStream xs = new XStream(); 14 | xs.autodetectAnnotations(true); 15 | 16 | // -->
17 | //xs.alias("article", Article.class); 18 | // -->
19 | // xs.aliasField("address", Article.class, "url"); 20 | 21 | // OBJECT --> XML 22 | String xml = xs.toXML(createArticle()); 23 | 24 | System.out.println("OBJECT --> XML"); 25 | System.out.println(xml); 26 | 27 | System.out.println("\n--------------------------------\n"); 28 | 29 | // XML --> OBJECT 30 | Article article = (Article) xs.fromXML(xml); 31 | 32 | System.out.println("XML --> OBJECT"); 33 | System.out.println(article); 34 | } 35 | 36 | private static Article createArticle(){ 37 | 38 | Article article = new Article(); 39 | 40 | article.setTitle("XStream - Java Object to XML & XML to Object Mapping"); 41 | article.setUrl("http://hmkcode.com/xstream-java-object-xml"); 42 | article.setPublished(true); 43 | 44 | article.addCategory("Java"); 45 | article.addTag("Java"); 46 | article.addTag("Xstream"); 47 | article.addTag("XML"); 48 | article.addTag("Marshalling"); 49 | article.addTag("Unmarshalling"); 50 | 51 | return article; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /xstream-java-xml/src/main/java/com/hmkcode/vo/Article.java: -------------------------------------------------------------------------------- 1 | package com.hmkcode.vo; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import com.thoughtworks.xstream.annotations.XStreamAlias; 7 | import com.thoughtworks.xstream.annotations.XStreamAsAttribute; 8 | import com.thoughtworks.xstream.annotations.XStreamConverter; 9 | import com.thoughtworks.xstream.annotations.XStreamImplicit; 10 | import com.thoughtworks.xstream.annotations.XStreamOmitField; 11 | import com.thoughtworks.xstream.converters.basic.BooleanConverter; 12 | 13 | @XStreamAlias("article") 14 | public class Article { 15 | 16 | @XStreamAsAttribute 17 | private String title; 18 | 19 | @XStreamAlias("address") 20 | private String url; 21 | 22 | @XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"}) 23 | private boolean published; 24 | 25 | @XStreamOmitField 26 | private List categories; 27 | 28 | @XStreamImplicit(itemFieldName="tag") 29 | private List tags; 30 | 31 | public String getTitle() { 32 | return title; 33 | } 34 | public void setTitle(String title) { 35 | this.title = title; 36 | } 37 | public String getUrl() { 38 | return url; 39 | } 40 | public void setUrl(String url) { 41 | this.url = url; 42 | } 43 | 44 | public boolean isPublished() { 45 | return published; 46 | } 47 | public void setPublished(boolean published) { 48 | this.published = published; 49 | } 50 | public List getCategories() { 51 | return categories; 52 | } 53 | public void setCategories(List categories) { 54 | this.categories = categories; 55 | } 56 | public List getTags() { 57 | return tags; 58 | } 59 | public void setTags(List tags) { 60 | this.tags = tags; 61 | } 62 | 63 | public void addCategory(String category){ 64 | if(this.categories == null) 65 | this.categories = new LinkedList(); 66 | this.categories.add(category); 67 | } 68 | public void addTag(String tag){ 69 | if(this.tags == null) 70 | this.tags = new LinkedList(); 71 | 72 | this.tags.add(tag); 73 | } 74 | @Override 75 | public String toString() { 76 | return "Article [title=" + title + ",\nurl=" + url + ",\npublished=" 77 | + published + ",\ncategories=" + categories + ",\ntags=" + tags 78 | + "]"; 79 | } 80 | 81 | 82 | 83 | 84 | } 85 | --------------------------------------------------------------------------------