Java tutorial
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.albert.javatest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; //import org.apache.ws.commons.schema.XmlSchema; //import org.apache.ws.commons.schema.XmlSchemaCollection; //import org.apache.ws.commons.schema.XmlSchemaElement; //import org.apache.ws.commons.schema.XmlSchemaObject; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.albert.service.MyService; import com.albert.si.gateway.HelloService; import com.albert.si.gateway.MyHelloService; import com.bns.soa.common.logging.LogManager; import com.bns.soa.common.logging.ServiceLoggingAdvice; import com.bns.soa.common.validation.schema.PayloadValidationHandler; import com.bns.soa.common.validation.schema.PayloadValidatorInfo; import com.jsfsample.util.StringUtil; /**** * * @author liuzi * */ @ContextConfiguration(locations = { "classpath:com/albert/si/gateway/context.xml", "classpath:com/albert/service/applicationContext.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @Configuration @ComponentScan public class JavaTestExample { private static final Logger log = Logger.getLogger(JavaTestExample.class.getName()); public static final String RESOURCE_URI = "ONekeyTAI.properties"; @Autowired private HelloService helloGateway; @Autowired private MyService myService; public static void main(String args[]) { String cfg = "com/albert/si/gateway/context.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(cfg); try { HelloService helloService = context.getBean("helloGateway", HelloService.class); System.out.println("Printing in HelloWorldExample by helloGateway: " + helloService.sayHello("World")); } finally { ((ConfigurableApplicationContext) context).close(); } } @Ignore @Test public void testChannelHelloWorld() { ApplicationContext context = new AnnotationConfigApplicationContext(MyHelloService.class); HelloService myHelloService = context.getBean("myHelloService", HelloService.class); System.out.println("Printing by HelloService: " + myHelloService.sayHello("abc")); System.out .println("Printing in HelloWorldExample JUnit, by helloGateway: " + helloGateway.sayHello("World")); ((ConfigurableApplicationContext) context).close(); } @Ignore @Test public void testClassLoaderPath() { log.entering("OnekeyTAI", "loading Properties ..."); // load values InputStream in = null; BufferedReader br = null; Set<String> tmpIps = new HashSet<String>(), tmpApps = new HashSet<String>(); String newHeaderValue = null; try { /**** * If you use Class.getResourceAsStream( name ), name is resolved * internally. "test.txt" is transformed into "my/package/test.txt" * and "/test.txt" is transformed into "test.txt". Then * ClassLoader.getResourceAsStream() is called with the transformed * name. Your code should work with both methods, but you have to * check that your file "test.txt" stays in the right place (inside * your classpath). With your call, you have to put "test.txt" * inside your top level package directory. tangens Feb 4 '10 at */ in = JavaTestExample.class.getClassLoader().getResourceAsStream(RESOURCE_URI); // in = HelloWorldExample.class.getResourceAsStream(RESOURCE_URI); br = new BufferedReader(new InputStreamReader(in)); // The default JDK property/ResourceBundle cannot handle Array in // the property file, and we don't want to add dependence to Apache // Common Configuration lib // read configuration file manually. String line; while ((line = br.readLine()) != null) { // Deal with the line String[] arr = line.split("="); if (2 != arr.length) { // the assumption/limitation here is that // the key or value should NOT contain // "=" continue; } String key = arr[0].trim(); if ("header".equals(key)) { newHeaderValue = arr[1]; } else if ("managementIp".equals(key)) { tmpIps.add(arr[1].trim()); } else if ("app".equals(key)) { tmpApps.add(arr[1].trim()); } } } catch (Exception e) { e.printStackTrace(); return; } finally { if (null != br) { try { br.close(); br = null; } catch (Exception e) { } } if (null != in) { try { in.close(); in = null; } catch (Exception e) { } } } Assert.assertTrue(tmpIps.size() > 0); Assert.assertTrue(tmpApps.size() > 0); } @Ignore @Test public void testJacksonStream() { log.entering("OnekeyTAI", "loading Properties ..."); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("C:\\Projects\\sts-351-osap\\AlbertWeb\\src\\file.json")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name"); System.out.println(name); long age = (Long) jsonObject.get("age"); System.out.println(age); // loop array JSONArray msg = (JSONArray) jsonObject.get("messages"); Iterator<String> iterator = msg.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } @Ignore @Test public void testOenWsSimulatorValidData() { JSONParser parser = new JSONParser(); FileReader fileReader = null; BufferedReader bufferedReader = null; try { File file = new File("C:\\Projects\\sts-351-osap\\AlbertWeb\\src\\OenWsSimulatorValidData.txt"); fileReader = new FileReader(file); bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null && !"".equals(line.trim())) { Object obj = parser.parse(line); JSONObject jsonObject = (JSONObject) obj; String dateOfBirth = (String) jsonObject.get("dateOfBirth"); System.out.println(dateOfBirth); String gender = (String) jsonObject.get("gender"); System.out.println(gender); String firstName = (String) jsonObject.get("firstName"); System.out.println(firstName); String surName = (String) jsonObject.get("surName"); System.out.println(surName); String oen = (String) jsonObject.get("oen"); System.out.println(oen); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { try { fileReader.close(); bufferedReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } @Ignore @Test public void testSpringPropertiesFile() { String result = myService.showFieldInPropertiesFile(); System.out.println(result); } @Ignore @Test public void testClassDecompile() { System.out.println("abc"); LogManager logManager = new LogManager(); ServiceLoggingAdvice serviceLoggingAdvice = null; PayloadValidationHandler PayloadValidationHandler = null; PayloadValidatorInfo PayloadValidatorInfo = null; } @Ignore @Test public void testString() { String result = String.format("%09d", null); System.out.println("####################" + String.format("%09d", null)); } @Ignore @Test public void testStringUtilIsNumerical() { boolean result = StringUtil.isNumerical(" "); Assert.assertTrue(result); } @Ignore @Test public void testPrintOutCollections() { List<TestObj> list = new ArrayList<TestObj>(); for (int i = 0; i < 3; i++) { String firstName = "firstName" + i; String lastName = "lastName" + i; TestObj testObj = new TestObj(); testObj.setFirstName(firstName); testObj.setLastName(lastName); list.add(testObj); } System.out.println("###################" + Arrays.toString(list.toArray())); print(list); } private static <S, T extends Iterable<S>> void print(T list) { if (list == null) { System.out.println("Passed in list is null or empty!"); } System.out.println( "------------------------------------ print collectioin start ------------------------------------"); for (Object element : list) { System.out.println(ToStringBuilder.reflectionToString(element)); } System.out.println( "------------------------------------ print collectioin end ------------------------------------"); } private class TestObj { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } @Test public void testCompareTo() { String year1415 = "year1415"; String year1516 = "year1516"; System.out.println("##################### compareTo result = " + year1516.compareTo(null)); Assert.assertTrue(year1516.compareTo(year1415) > 0); } @Ignore @Test public void testOenValidator() { String oen = " "; boolean result = true; if (StringUtils.isNotEmpty(oen)) { if (oen.length() != 9) { result = false; } else if (!org.apache.commons.lang.StringUtils.isNumeric(oen)) { result = false; } else if (!isOENVerificationPassed(oen)) { result = false; } } Assert.assertFalse(result); } private static final String OEN_MASK = "0246813579135792468024680357913579146802468025791357913680246802479135791358024680246913579135702468"; private static final int MIN_OEN = 60000000; private boolean isOENVerificationPassed(String oen) { if (Integer.parseInt(oen) < MIN_OEN) { return false; } int maskValue = 0; int checkDigit = 0; String oenNumber = oen; String[] oenGroup = null; oenGroup = oenNumber.split("(?<=\\G.{2})"); for (int i = 0; i < 4; i++) { maskValue = maskValue + Integer.parseInt(Character.toString(OEN_MASK.charAt((Integer.parseInt(oenGroup[i]))))); } checkDigit = ((maskValue / 10 + 1) * 10) - maskValue; if (checkDigit == 10) { checkDigit = 0; } return (Integer.parseInt(oenGroup[oenGroup.length - 1]) == checkDigit); } }