diff --git a/.classpath b/.classpath deleted file mode 100644 index cf81d48..0000000 --- a/.classpath +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 7ed7b1c..a0ab1af 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ -/bin/ -<<<<<<< HEAD -/target/ -======= -/target ->>>>>>> 4d33b120c4e9b0cc0e23dd32b7e352b99d17350c +**/target/* +.idea +**/*.iml +*.iml +/jdk-study/*.iml diff --git a/.gitignore.BASE.gitignore b/.gitignore.BASE.gitignore deleted file mode 100644 index ae3c172..0000000 --- a/.gitignore.BASE.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/.gitignore.LOCAL.gitignore b/.gitignore.LOCAL.gitignore deleted file mode 100644 index 09e3bc9..0000000 --- a/.gitignore.LOCAL.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/bin/ -/target/ diff --git a/.gitignore.REMOTE.gitignore b/.gitignore.REMOTE.gitignore deleted file mode 100644 index e0e1cc4..0000000 --- a/.gitignore.REMOTE.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/bin/ -/target diff --git a/.idea/libraries/Maven__com_google_guava_guava_18_0.xml b/.idea/libraries/Maven__com_google_guava_guava_18_0.xml deleted file mode 100644 index 967a097..0000000 --- a/.idea/libraries/Maven__com_google_guava_guava_18_0.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_io_commons_io_1_3_2.xml b/.idea/libraries/Maven__commons_io_commons_io_1_3_2.xml deleted file mode 100644 index 0e57856..0000000 --- a/.idea/libraries/Maven__commons_io_commons_io_1_3_2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__junit_junit_4_10.xml b/.idea/libraries/Maven__junit_junit_4_10.xml deleted file mode 100644 index 58342e5..0000000 --- a/.idea/libraries/Maven__junit_junit_4_10.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__log4j_log4j_1_2_17.xml b/.idea/libraries/Maven__log4j_log4j_1_2_17.xml deleted file mode 100644 index 354599b..0000000 --- a/.idea/libraries/Maven__log4j_log4j_1_2_17.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_commons_commons_collections4_4_0.xml b/.idea/libraries/Maven__org_apache_commons_commons_collections4_4_0.xml deleted file mode 100644 index 6656636..0000000 --- a/.idea/libraries/Maven__org_apache_commons_commons_collections4_4_0.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_1.xml b/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_1.xml deleted file mode 100644 index 4ccc14b..0000000 --- a/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_1.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml b/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml deleted file mode 100644 index 57da5a5..0000000 --- a/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_jboss_weld_se_weld_se_2_2_6_Final.xml b/.idea/libraries/Maven__org_jboss_weld_se_weld_se_2_2_6_Final.xml deleted file mode 100644 index 9755096..0000000 --- a/.idea/libraries/Maven__org_jboss_weld_se_weld_se_2_2_6_Final.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_mozilla_rhino_1_7R4.xml b/.idea/libraries/Maven__org_mozilla_rhino_1_7R4.xml deleted file mode 100644 index 4cff9ad..0000000 --- a/.idea/libraries/Maven__org_mozilla_rhino_1_7R4.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 23bd0d0..0000000 --- a/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - study_java_8 - - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - org.eclipse.wst.common.project.facet.core.nature - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 13b3428..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,13 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index ab295be..0000000 --- a/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/java-ee-study/pom.xml b/java-ee-study/pom.xml new file mode 100644 index 0000000..f2bc113 --- /dev/null +++ b/java-ee-study/pom.xml @@ -0,0 +1,40 @@ + + + + java-study + java-study + 0.1.2 + + 4.0.0 + + java-ee-study + 0.1.2 + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + + org.jboss.weld.se + weld-se-core + 3.1.2.Final + + + java-study + jdk-study + 0.1.2 + test + + + + javax.validation + validation-api + LATEST + + + \ No newline at end of file diff --git a/java-ee-study/src/test/java/study/commons/MiscUtils.java b/java-ee-study/src/test/java/study/commons/MiscUtils.java new file mode 100644 index 0000000..0369721 --- /dev/null +++ b/java-ee-study/src/test/java/study/commons/MiscUtils.java @@ -0,0 +1,468 @@ +package study.commons; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.collections4.iterators.ObjectArrayIterator; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.CharUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.DateFormatUtils; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.*; +import java.lang.management.ManagementFactory; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class MiscUtils { + public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); + + public static long getPropertyNumber(String name, long defaultValue) { + String str = System.getProperty(name); + if (StringUtils.isNumeric(str)) { + return Long.parseLong(str); + } + return defaultValue; + } + + public static String invocationInfo() { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + int i = 2; + return String.format("%s\t%s.%s", ste[i].getFileName(), ste[i].getClassName(), ste[i].getMethodName()); + } + + public static String invocInfo() { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + int i = 2; + return String.format("%s\t%s.%s", ste[i].getFileName(), StringUtils.substringAfterLast(ste[i].getClassName(), "."), ste[i].getMethodName()); + } + + public static String invocationInfo(final int i) { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + return String.format("%s\t%s.%s", ste[i].getFileName(), ste[i].getClassName(), ste[i].getMethodName()); + } + + public static String byteCountToDisplaySize(long size) { + if (size > 1073741824L) return String.valueOf(size / 1073741824L) + " GB"; + if (size > 1048576L) return String.valueOf(size / 1048576L) + " MB"; + if (size > 1024L) return String.valueOf(size / 1024L) + " KB"; + return String.valueOf(size) + " bytes"; + } + + public static List pi2Longs(Integer n) { + return pi(n).toString().substring(0, n).chars().filter(i -> CharUtils.isAsciiNumeric((char) i)).map(i -> i - 48).mapToObj(Long::valueOf).collect(Collectors.toList()); + } + + public static List pi2Longs(Integer n, int range) { + List nums = pi2Longs(n); + List _nums = new ArrayList<>(); + Random rand = new Random(); + for (ListIterator it = nums.listIterator(); it.hasNext(); ) { + Long num = it.next(); + for (int i = 0, step = rand.nextInt(range); i < step && it.hasNext(); i++) { + num = num * 10 + it.next(); + } +// System.out.println(step + "\t" + num); + _nums.add(num); + } + return _nums; + } + + public static BigDecimal pi(Integer n) { + if (n == null) { + n = 0; + } + + if (n == 0) + return null; + if (n == 1) + return new BigDecimal(3); + if (n == 2) + return new BigDecimal(3.1); + if (n == 3) + return new BigDecimal(3.14); + + MathContext mc = new MathContext(n); + BigDecimal pi = new BigDecimal(BigInteger.ZERO, n, mc); + BigDecimal one = new BigDecimal(BigInteger.ONE, n, mc); + BigDecimal two = new BigDecimal(new BigInteger("2"), n, mc); + BigDecimal four = new BigDecimal(new BigInteger("4"), n, mc); + for (int k = 0; k < n; k++) { + BigDecimal tmp1 = one.divide(new BigDecimal(16).pow(k, mc), mc); + + BigDecimal tmp2_1 = four.divide(new BigDecimal(8 * k + 1, mc), mc); + BigDecimal tmp2_2 = two.divide(new BigDecimal(8 * k + 4, mc), mc); + BigDecimal tmp2_3 = one.divide(new BigDecimal(8 * k + 5, mc), mc); + BigDecimal tmp2_4 = one.divide(new BigDecimal(8 * k + 6, mc), mc); + + BigDecimal tmp2 = tmp2_1.subtract(tmp2_2, mc).subtract(tmp2_3, mc).subtract(tmp2_4, mc); + pi = pi.add(tmp1.multiply(tmp2, mc)); + } + + // pi.setScale(n, BigDecimal.ROUND_UP); + pi.scaleByPowerOfTen(n); + + return pi; + } + + public static long getProcessId() { + // Note: may fail in some JVM implementations + // therefore fallback has to be provided + + // something like '@', at least in SUN / Oracle JVMs + final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + final int index = jvmName.indexOf('@'); + String pidStr = jvmName.substring(0, index); + + if (index < 1 || !NumberUtils.isNumber(pidStr)) { + // part before '@' empty (index = 0) / '@' not found (index = -1) + return 0; + } + + return Long.parseLong(pidStr); + } + + public static void easySleep(long i) { + try { + Thread.sleep(i); + } catch (InterruptedException e) { + } + } + + public static String stackInfo() { + final StringBuilder sb = new StringBuilder(); + final StackTraceElement[] stes = Thread.currentThread().getStackTrace(); + ArrayUtils.reverse(stes); + Stream.of(stes).forEach(ste -> sb.append(String.format("%s\t%s.%s\n", ste.getFileName(), ste.getClassName(), ste.getMethodName()))); + return sb.toString(); + } + + public static String now() { + return DateFormatUtils.format(Calendar.getInstance(), "yy-MM-dd hh:mm:ss"); + } + + public static String toBinStr(final byte _b) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 7; i >= 0; i--) { + sb.append((_b & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(final int _i) { + final StringBuilder sb = new StringBuilder(); + sb.append(_i < 0 ? 1 : 0); + for (byte i = 31; i >= 0; i--) { + sb.append((_i & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(final short _s) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 16; i >= 0; i--) { + sb.append((_s & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(long _l) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 64; i >= 0; i--) { + sb.append((_l & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static class LoopingArrayIterator extends ObjectArrayIterator { + @SafeVarargs + public LoopingArrayIterator(final E... array) { + super(array, 0, array.length); + } + + public LoopingArrayIterator(final E array[], final int start) { + super(array, start, array.length); + } + + public E loop() { + final E[] array = this.getArray(); + loopIdx.compareAndSet(array.length, 0); + return array[loopIdx.getAndIncrement() % array.length]; + } + + private AtomicInteger loopIdx = new AtomicInteger(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static Map map(Object... keyAndVals) { + return MapUtils.putAll(new HashMap(), keyAndVals); + } + + public static long HOST_HASH = System.currentTimeMillis(); + + static { + try { + HOST_HASH = InetAddress.getLocalHost().getHostAddress().hashCode(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + } + + public static long uniqueLong() { + return Math.abs(UUID.randomUUID().hashCode()); + } + + public static ThreadFactory namedThreadFactory(final String name) { + return new BasicThreadFactory.Builder().namingPattern(name + "_%d").build(); + } + + public static String lineNumber(final String str) { + if (str == null) { + return null; + } + + final StringReader sr = new StringReader(str); + final BufferedReader br = new BufferedReader(sr); + + final StringBuilder sb = new StringBuilder(0); + AtomicLong lineNumber = new AtomicLong(0); + br.lines().forEach(line -> sb.append(lineNumber.incrementAndGet()).append("\t").append(line).append('\n')); + + return sb.toString(); + } + + private static final Logger log = LoggerFactory.getLogger(MiscUtils.class); + + public static String mapToJson(Map paramMap) { + if (MapUtils.isEmpty(paramMap)) { + return "{}"; + } + + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(paramMap); + } catch (Exception e) { + log.error(e.getMessage(), e); + return paramMap.toString(); + } + } + + public static String toXML(final Object bean) { + final StringWriter sw = new StringWriter(); + + try { + JAXBContext jc = JAXBContext.newInstance(bean.getClass()); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FRAGMENT, true); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(bean, sw); + } catch (Exception e) { + log.error(String.valueOf(bean), e); + } + return sw.toString(); + } + + public static T toObj(final String xmlStr, final Class cls) { + if (StringUtils.isBlank(xmlStr) || cls == null) { + return null; + } + + try { + JAXBContext jc = JAXBContext.newInstance(cls); + Unmarshaller um = jc.createUnmarshaller(); + return um.unmarshal(new StreamSource(new StringReader(xmlStr)), cls).getValue(); + } catch (JAXBException e) { + log.error(xmlStr, e); + } + + return null; + } + +// public static Map extractParams(MultivaluedMap params) { +// Map paramsMap = new HashMap(); +// params.keySet().forEach(key -> paramsMap.put(key, params.getFirst(key))); +// return paramsMap; +// } +// +// public static Map toParamMap(MultivaluedMap params) { +// Map paramsMap = new HashMap(); +// params.keySet().forEach(key -> paramsMap.put(key, params.get(key).toArray(new String[0]))); +// return paramsMap; +// } + + public static Map extractParams(Map params) { + Map paramsMap = new HashMap(); + params.keySet().forEach(key -> { + final String[] vals = params.get(key); + paramsMap.put(key, ArrayUtils.isEmpty(vals) ? null : vals[0]); + }); + return paramsMap; + } + + public static String generate(final String text) { + final StringBuffer sb = new StringBuffer(); + try { + final byte[] intext = text.getBytes(); + final MessageDigest md5 = MessageDigest.getInstance("MD5"); + final byte[] md5rslt = md5.digest(intext); + for (int i = 0; i < md5rslt.length; i++) { + final int val = 0xff & md5rslt[i]; + if (val < 16) { + sb.append("0"); + } + sb.append(Integer.toHexString(val)); + } + } catch (final Exception e) { + log.error(e.getMessage(), e); + } + return sb.toString(); + } + + public static String loadResAsString(final Class cls, final String fileName) { + if (cls == null || StringUtils.isBlank(fileName)) { + return StringUtils.EMPTY; + } + + try { + return IOUtils.toString(cls.getClassLoader().getResourceAsStream(fileName)); + } catch (IOException e) { + log.error("", e); + } + return StringUtils.EMPTY; + } + + public static String getEncodedText(String plainText) { + String encodedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(plainText.getBytes()); + encodedPassword = new String(Hex.encodeHex(md.digest())); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return encodedPassword; + } + + public static void writeToMappedFile(File file, byte[] data) throws IOException { + try (FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) { + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, data.length); + mbb.put(data); + mbb.force(); + } + } + + public static byte[] readFromMappedFile(File file) throws IOException { + try (FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.READ)) { + long length = file.length(); + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, length); + if (!mbb.load().isLoaded()) { + throw new IllegalStateException(String.format("%s can not be loaded", file.getAbsolutePath())); + } + + byte[] data = new byte[(int) length]; + mbb.get(data); + return data; + } + } + + public static Class[] getParameterizedClzz(Type type) { + if (type == null) return null; + if (type instanceof Class) { + Class aClass = (Class) type; + return new Class[]{aClass}; + } + if (type instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) type; + return Stream.of(pt.getActualTypeArguments()).filter(_type -> _type instanceof Class).toArray(Class[]::new); + } + return null; + } + + public static HttpResponse easyGet(String urlStr, String... params) { + if (StringUtils.isBlank(urlStr)) { + return null; + } + + try (CloseableHttpClient hc = HttpClients.createDefault()) { + URIBuilder ub = new URIBuilder(urlStr); + if (!ArrayUtils.isEmpty(params)) { + IntStream.range(0, params.length).filter(i -> i % 2 == 1).forEach(i -> ub.addParameter(params[i - 1], params[i])); + } + + HttpGet hg = new HttpGet(ub.build()); + try (CloseableHttpResponse hr = hc.execute(hg)) { + BasicHttpResponse bhr = new BasicHttpResponse(hr.getStatusLine()); + bhr.setEntity(new InputStreamEntity(new ByteArrayInputStream(EntityUtils.toByteArray(hr.getEntity())))); + return bhr; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static HttpResponse easyPost(String urlStr, String... params) { + if (StringUtils.isBlank(urlStr)) { + return null; + } + + try (CloseableHttpClient hc = HttpClients.createDefault()) { + URIBuilder ub = new URIBuilder(urlStr); + HttpPost hp = new HttpPost(ub.build()); + List nvps = new ArrayList(); + if (!ArrayUtils.isEmpty(params)) { + IntStream.range(0, params.length).filter(i -> i % 2 == 1).forEach(i -> nvps.add(new BasicNameValuePair(params[i - 1], params[i]))); + } + hp.setEntity(new UrlEncodedFormEntity(nvps)); + + try (CloseableHttpResponse hr = hc.execute(hp)) { + BasicHttpResponse bhr = new BasicHttpResponse(hr.getStatusLine()); + bhr.setEntity(new InputStreamEntity(new ByteArrayInputStream(EntityUtils.toByteArray(hr.getEntity())))); + return bhr; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/java-ee-study/src/test/java/study/javax/cdi/weld/WeldTests.java b/java-ee-study/src/test/java/study/javax/cdi/weld/WeldTests.java new file mode 100644 index 0000000..67b0e49 --- /dev/null +++ b/java-ee-study/src/test/java/study/javax/cdi/weld/WeldTests.java @@ -0,0 +1,60 @@ +package study.javax.cdi.weld; + +import org.jboss.weld.context.RequestContext; +import org.jboss.weld.context.unbound.UnboundLiteral; +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; +import org.junit.jupiter.api.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import study.javax.cdi.weld.beans.AppBean; + +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.CDI; + +public class WeldTests { + static final Logger log = LoggerFactory.getLogger(WeldTests.class); + + public static Weld weld; + public static WeldContainer container; + public static BeanManager bm; + @SuppressWarnings("rawtypes") + public static CDI _CDI; + + @BeforeAll + public static void setUp() { + try { + weld = new Weld(); + container = weld.initialize(); + bm = container.getBeanManager(); + _CDI = CDI.current(); + } catch (final Exception e) { + log.error("failed to initiate...", e); + System.exit(-1); + } + } + + @AfterAll + public static void tearDown() { + if (weld != null) + weld.shutdown(); + } + + @BeforeEach + public void activateCtx() { + RequestContext reqCtx = (RequestContext) _CDI.select(RequestContext.class, UnboundLiteral.INSTANCE).get(); + reqCtx.activate(); + } + + public static T getBean(Class cls) { + return CDI.current().select(cls).get(); + } + + @Test + public void testCDI() { + AppBean app = getBean(AppBean.class); + Assertions.assertNotNull(app); + log.info("AppBean:\t{}", app); + } + +} diff --git a/java-ee-study/src/test/java/study/javax/cdi/weld/beans/AppBean.java b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/AppBean.java new file mode 100644 index 0000000..9eb345d --- /dev/null +++ b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/AppBean.java @@ -0,0 +1,8 @@ +package study.javax.cdi.weld.beans; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class AppBean extends BaseBean { + +} diff --git a/java-ee-study/src/test/java/study/javax/cdi/weld/beans/BaseBean.java b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/BaseBean.java new file mode 100644 index 0000000..e7043ea --- /dev/null +++ b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/BaseBean.java @@ -0,0 +1,67 @@ +package study.javax.cdi.weld.beans; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import study.commons.MiscUtils; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.enterprise.context.Dependent; +import javax.inject.Inject; +import java.util.Objects; + +@Dependent +public class BaseBean { + static final Logger log = LoggerFactory.getLogger(BaseBean.class); + protected Long createdTime = System.currentTimeMillis(); + @Inject + protected Long id; + + protected String name; + + public Long getCreatedTime() { + return createdTime; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + @PostConstruct + public void postConstruct() { + log.info(MiscUtils.invocationInfo() + "\n\t" + this); + } + + @PreDestroy + public void preDestroy() { + log.info(MiscUtils.invocationInfo() + "\n\t" + this); + } + + public void setName(String name) { + this.name = name; + } + + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof BaseBean)) return false; + BaseBean baseBean = (BaseBean) o; + return Objects.equals(getId(), baseBean.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } + +} diff --git a/java-ee-study/src/test/java/study/javax/cdi/weld/beans/SeqGenerator.java b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/SeqGenerator.java new file mode 100644 index 0000000..743e360 --- /dev/null +++ b/java-ee-study/src/test/java/study/javax/cdi/weld/beans/SeqGenerator.java @@ -0,0 +1,43 @@ +package study.javax.cdi.weld.beans; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import study.commons.MiscUtils; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import java.util.Calendar; +import java.util.Date; +import java.util.concurrent.atomic.AtomicLong; + +@ApplicationScoped +public class SeqGenerator { + private static Logger log = LoggerFactory.getLogger(SeqGenerator.class); + private AtomicLong seq; + + @Produces + public Long getSeq() { + final long newId = seq.incrementAndGet(); + log.info("{} \t-> \t{newId: {}}", MiscUtils.invocationInfo(), newId); + return newId; + } + + @Produces + public Date getTimeStamp() { + return Calendar.getInstance().getTime(); + } + + @PostConstruct + public void postConstruct() { + log.info(MiscUtils.invocationInfo()); + seq = new AtomicLong(); + } + + @PreDestroy + public void preDestroy() { + log.info(MiscUtils.invocationInfo()); + log.info("last id: {}", seq.get()); + } +} diff --git a/java-ee-study/src/test/resources/META-INF/beans.xml b/java-ee-study/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000..df1e633 --- /dev/null +++ b/java-ee-study/src/test/resources/META-INF/beans.xml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/java-ee-study/src/test/resources/log4j2.xml b/java-ee-study/src/test/resources/log4j2.xml new file mode 100644 index 0000000..739f19f --- /dev/null +++ b/java-ee-study/src/test/resources/log4j2.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jdk-study/pom.xml b/jdk-study/pom.xml new file mode 100644 index 0000000..ccface1 --- /dev/null +++ b/jdk-study/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + java-study + jdk-study + 0.1.2 + + + java-study + java-study + 0.1.2 + + + \ No newline at end of file diff --git a/jdk-study/src/test/java/study/JdkStudyUtils.java b/jdk-study/src/test/java/study/JdkStudyUtils.java new file mode 100644 index 0000000..bae2bff --- /dev/null +++ b/jdk-study/src/test/java/study/JdkStudyUtils.java @@ -0,0 +1,62 @@ +package study; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sun.misc.Unsafe; + +import java.lang.reflect.Field; + +public class JdkStudyUtils { + static final Logger log = LoggerFactory.getLogger(JdkStudyUtils.class); + + public static String toBinStr(final byte _b) { + final StringBuilder sb = new StringBuilder(Byte.SIZE); + for (byte i = Byte.SIZE - 1; i >= 0; i--) { + sb.append((_b & (1 << i)) != 0 ? '1' : '0'); + } + return sb.toString(); + } + + public static String toBinStr(final int _i) { + final StringBuilder sb = new StringBuilder(Integer.SIZE); + sb.append(_i < 0 ? '1' : '0'); + for (byte i = Integer.SIZE - 2; i >= 0; i--) { + sb.append((_i & (1 << i)) != 0 ? '1' : '0'); + } + return sb.toString(); + } + + public static String toBinStr(final short _s) { + final StringBuilder sb = new StringBuilder(Short.SIZE); + for (byte i = Short.SIZE - 1; i >= 0; i--) { + sb.append((_s & (1 << i)) != 0 ? '1' : '0'); + } + return sb.toString(); + } + + public static String toBinStr(long _l) { + final StringBuilder sb = new StringBuilder(Long.SIZE); + for (byte i = Long.SIZE; i >= 0; i--) { + sb.append((_l & (1 << i)) != 0 ? '1' : '0'); + } + return sb.toString(); + } + + public static Unsafe getUnsafe() { + try { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (Unsafe) f.get(null); + } catch (Exception e) { + log.error("failed to get Unsafe", e); + return null; + } + } + + public static void easySleep(long i) { + try { + Thread.sleep(i); + } catch (InterruptedException e) { + } + } +} diff --git a/jdk-study/src/test/java/study/commons/MiscUtils.java b/jdk-study/src/test/java/study/commons/MiscUtils.java new file mode 100644 index 0000000..b202372 --- /dev/null +++ b/jdk-study/src/test/java/study/commons/MiscUtils.java @@ -0,0 +1,471 @@ +package study.commons; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.collections4.iterators.ObjectArrayIterator; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.CharUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.DateFormatUtils; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.*; +import java.lang.management.ManagementFactory; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class MiscUtils { + public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); + + public static long getPropertyNumber(String name, long defaultValue) { + String str = System.getProperty(name); + if (StringUtils.isNumeric(str)) { + return Long.parseLong(str); + } + return defaultValue; + } + + public static String invocationInfo() { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + int i = 2; + return String.format("%s\t%s.%s", ste[i].getFileName(), ste[i].getClassName(), ste[i].getMethodName()); + } + + public static String invocInfo() { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + int i = 2; + return String.format("%s\t%s.%s", ste[i].getFileName(), StringUtils.substringAfterLast(ste[i].getClassName(), "."), ste[i].getMethodName()); + } + + public static String invocationInfo(final int i) { + StackTraceElement[] ste = Thread.currentThread().getStackTrace(); + ste = ArrayUtils.subarray(ste, 0, i); + return Stream.of(ste) + .map(st -> String.format("%s\t%s.%s", st.getFileName(), st.getClassName(), st.getMethodName())) + .collect(Collectors.joining("\n")); + } + + public static String byteCountToDisplaySize(long size) { + if (size > 1073741824L) return String.valueOf(size / 1073741824L) + " GB"; + if (size > 1048576L) return String.valueOf(size / 1048576L) + " MB"; + if (size > 1024L) return String.valueOf(size / 1024L) + " KB"; + return String.valueOf(size) + " bytes"; + } + + public static List pi2Longs(Integer n) { + return pi(n).toString().substring(0, n).chars().filter(i -> CharUtils.isAsciiNumeric((char) i)).map(i -> i - 48).mapToObj(Long::valueOf).collect(Collectors.toList()); + } + + public static List pi2Longs(Integer n, int range) { + List nums = pi2Longs(n); + List _nums = new ArrayList<>(); + Random rand = new Random(); + for (ListIterator it = nums.listIterator(); it.hasNext(); ) { + Long num = it.next(); + for (int i = 0, step = rand.nextInt(range); i < step && it.hasNext(); i++) { + num = num * 10 + it.next(); + } +// System.out.println(step + "\t" + num); + _nums.add(num); + } + return _nums; + } + + public static BigDecimal pi(Integer n) { + if (n == null) { + n = 0; + } + + if (n == 0) + return null; + if (n == 1) + return new BigDecimal(3); + if (n == 2) + return new BigDecimal(3.1); + if (n == 3) + return new BigDecimal(3.14); + + MathContext mc = new MathContext(n); + BigDecimal pi = new BigDecimal(BigInteger.ZERO, n, mc); + BigDecimal one = new BigDecimal(BigInteger.ONE, n, mc); + BigDecimal two = new BigDecimal(new BigInteger("2"), n, mc); + BigDecimal four = new BigDecimal(new BigInteger("4"), n, mc); + for (int k = 0; k < n; k++) { + BigDecimal tmp1 = one.divide(new BigDecimal(16).pow(k, mc), mc); + + BigDecimal tmp2_1 = four.divide(new BigDecimal(8 * k + 1, mc), mc); + BigDecimal tmp2_2 = two.divide(new BigDecimal(8 * k + 4, mc), mc); + BigDecimal tmp2_3 = one.divide(new BigDecimal(8 * k + 5, mc), mc); + BigDecimal tmp2_4 = one.divide(new BigDecimal(8 * k + 6, mc), mc); + + BigDecimal tmp2 = tmp2_1.subtract(tmp2_2, mc).subtract(tmp2_3, mc).subtract(tmp2_4, mc); + pi = pi.add(tmp1.multiply(tmp2, mc)); + } + + // pi.setScale(n, BigDecimal.ROUND_UP); + pi.scaleByPowerOfTen(n); + + return pi; + } + + public static long getProcessId() { + // Note: may fail in some JVM implementations + // therefore fallback has to be provided + + // something like '@', at least in SUN / Oracle JVMs + final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + final int index = jvmName.indexOf('@'); + String pidStr = jvmName.substring(0, index); + + if (index < 1 || !NumberUtils.isNumber(pidStr)) { + // part before '@' empty (index = 0) / '@' not found (index = -1) + return 0; + } + + return Long.parseLong(pidStr); + } + + public static void easySleep(long i) { + try { + Thread.sleep(i); + } catch (InterruptedException e) { + } + } + + public static String stackInfo() { + final StringBuilder sb = new StringBuilder(); + final StackTraceElement[] stes = Thread.currentThread().getStackTrace(); + ArrayUtils.reverse(stes); + Stream.of(stes).forEach(ste -> sb.append(String.format("%s\t%s.%s\n", ste.getFileName(), ste.getClassName(), ste.getMethodName()))); + return sb.toString(); + } + + public static String now() { + return DateFormatUtils.format(Calendar.getInstance(), "yy-MM-dd hh:mm:ss"); + } + + public static String toBinStr(final byte _b) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 7; i >= 0; i--) { + sb.append((_b & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(final int _i) { + final StringBuilder sb = new StringBuilder(); + sb.append(_i < 0 ? 1 : 0); + for (byte i = 31; i >= 0; i--) { + sb.append((_i & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(final short _s) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 16; i >= 0; i--) { + sb.append((_s & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static String toBinStr(long _l) { + final StringBuilder sb = new StringBuilder(); + for (byte i = 64; i >= 0; i--) { + sb.append((_l & (1 << i)) != 0 ? 1 : 0); + } + return sb.toString(); + } + + public static class LoopingArrayIterator extends ObjectArrayIterator { + @SafeVarargs + public LoopingArrayIterator(final E... array) { + super(array, 0, array.length); + } + + public LoopingArrayIterator(final E array[], final int start) { + super(array, start, array.length); + } + + public E loop() { + final E[] array = this.getArray(); + loopIdx.compareAndSet(array.length, 0); + return array[loopIdx.getAndIncrement() % array.length]; + } + + private AtomicInteger loopIdx = new AtomicInteger(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static Map map(Object... keyAndVals) { + return MapUtils.putAll(new HashMap(), keyAndVals); + } + + public static long HOST_HASH = System.currentTimeMillis(); + + static { + try { + HOST_HASH = InetAddress.getLocalHost().getHostAddress().hashCode(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + } + + public static long uniqueLong() { + return Math.abs(UUID.randomUUID().hashCode()); + } + + public static ThreadFactory namedThreadFactory(final String name) { + return new BasicThreadFactory.Builder().namingPattern(name + "_%d").build(); + } + + public static String lineNumber(final String str) { + if (str == null) { + return null; + } + + final StringReader sr = new StringReader(str); + final BufferedReader br = new BufferedReader(sr); + + final StringBuilder sb = new StringBuilder(0); + AtomicLong lineNumber = new AtomicLong(0); + br.lines().forEach(line -> sb.append(lineNumber.incrementAndGet()).append("\t").append(line).append('\n')); + + return sb.toString(); + } + + private static final Logger log = LoggerFactory.getLogger(MiscUtils.class); + + public static String mapToJson(Map paramMap) { + if (MapUtils.isEmpty(paramMap)) { + return "{}"; + } + + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(paramMap); + } catch (Exception e) { + log.error(e.getMessage(), e); + return paramMap.toString(); + } + } + + public static String toXML(final Object bean) { + final StringWriter sw = new StringWriter(); + + try { + JAXBContext jc = JAXBContext.newInstance(bean.getClass()); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FRAGMENT, true); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(bean, sw); + } catch (Exception e) { + log.error(String.valueOf(bean), e); + } + return sw.toString(); + } + + public static T toObj(final String xmlStr, final Class cls) { + if (StringUtils.isBlank(xmlStr) || cls == null) { + return null; + } + + try { + JAXBContext jc = JAXBContext.newInstance(cls); + Unmarshaller um = jc.createUnmarshaller(); + return um.unmarshal(new StreamSource(new StringReader(xmlStr)), cls).getValue(); + } catch (JAXBException e) { + log.error(xmlStr, e); + } + + return null; + } + +// public static Map extractParams(MultivaluedMap params) { +// Map paramsMap = new HashMap(); +// params.keySet().forEach(key -> paramsMap.put(key, params.getFirst(key))); +// return paramsMap; +// } +// +// public static Map toParamMap(MultivaluedMap params) { +// Map paramsMap = new HashMap(); +// params.keySet().forEach(key -> paramsMap.put(key, params.get(key).toArray(new String[0]))); +// return paramsMap; +// } + + public static Map extractParams(Map params) { + Map paramsMap = new HashMap(); + params.keySet().forEach(key -> { + final String[] vals = params.get(key); + paramsMap.put(key, ArrayUtils.isEmpty(vals) ? null : vals[0]); + }); + return paramsMap; + } + + public static String generate(final String text) { + final StringBuffer sb = new StringBuffer(); + try { + final byte[] intext = text.getBytes(); + final MessageDigest md5 = MessageDigest.getInstance("MD5"); + final byte[] md5rslt = md5.digest(intext); + for (int i = 0; i < md5rslt.length; i++) { + final int val = 0xff & md5rslt[i]; + if (val < 16) { + sb.append("0"); + } + sb.append(Integer.toHexString(val)); + } + } catch (final Exception e) { + log.error(e.getMessage(), e); + } + return sb.toString(); + } + + public static String loadResAsString(final Class cls, final String fileName) { + if (cls == null || StringUtils.isBlank(fileName)) { + return StringUtils.EMPTY; + } + + try { + return IOUtils.toString(cls.getClassLoader().getResourceAsStream(fileName)); + } catch (IOException e) { + log.error("", e); + } + return StringUtils.EMPTY; + } + + public static String getEncodedText(String plainText) { + String encodedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(plainText.getBytes()); + encodedPassword = new String(Hex.encodeHex(md.digest())); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return encodedPassword; + } + + public static void writeToMappedFile(File file, byte[] data) throws IOException { + try (FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) { + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, data.length); + mbb.put(data); + mbb.force(); + } + } + + public static byte[] readFromMappedFile(File file) throws IOException { + try (FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.READ)) { + long length = file.length(); + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, length); + if (!mbb.load().isLoaded()) { + throw new IllegalStateException(String.format("%s can not be loaded", file.getAbsolutePath())); + } + + byte[] data = new byte[(int) length]; + mbb.get(data); + return data; + } + } + + public static Class[] getParameterizedClzz(Type type) { + if (type == null) return null; + if (type instanceof Class) { + Class aClass = (Class) type; + return new Class[]{aClass}; + } + if (type instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) type; + return Stream.of(pt.getActualTypeArguments()).filter(_type -> _type instanceof Class).toArray(Class[]::new); + } + return null; + } + + public static HttpResponse easyGet(String urlStr, String... params) { + if (StringUtils.isBlank(urlStr)) { + return null; + } + + try (CloseableHttpClient hc = HttpClients.createDefault()) { + URIBuilder ub = new URIBuilder(urlStr); + if (!ArrayUtils.isEmpty(params)) { + IntStream.range(0, params.length).filter(i -> i % 2 == 1).forEach(i -> ub.addParameter(params[i - 1], params[i])); + } + + HttpGet hg = new HttpGet(ub.build()); + try (CloseableHttpResponse hr = hc.execute(hg)) { + BasicHttpResponse bhr = new BasicHttpResponse(hr.getStatusLine()); + bhr.setEntity(new InputStreamEntity(new ByteArrayInputStream(EntityUtils.toByteArray(hr.getEntity())))); + return bhr; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static HttpResponse easyPost(String urlStr, String... params) { + if (StringUtils.isBlank(urlStr)) { + return null; + } + + try (CloseableHttpClient hc = HttpClients.createDefault()) { + URIBuilder ub = new URIBuilder(urlStr); + HttpPost hp = new HttpPost(ub.build()); + List nvps = new ArrayList(); + if (!ArrayUtils.isEmpty(params)) { + IntStream.range(0, params.length).filter(i -> i % 2 == 1).forEach(i -> nvps.add(new BasicNameValuePair(params[i - 1], params[i]))); + } + hp.setEntity(new UrlEncodedFormEntity(nvps)); + + try (CloseableHttpResponse hr = hc.execute(hp)) { + BasicHttpResponse bhr = new BasicHttpResponse(hr.getStatusLine()); + bhr.setEntity(new InputStreamEntity(new ByteArrayInputStream(EntityUtils.toByteArray(hr.getEntity())))); + return bhr; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/jdk-study/src/test/java/study/env/EnvTests.java b/jdk-study/src/test/java/study/env/EnvTests.java new file mode 100644 index 0000000..80d11b0 --- /dev/null +++ b/jdk-study/src/test/java/study/env/EnvTests.java @@ -0,0 +1,121 @@ +package study.env; + + +import org.junit.jupiter.api.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.DynamicTest.dynamicTest; + +/** + * This class is meant to test logging settings + * as well as some new feature of JUnit5 + */ +public class EnvTests { + static final Logger log = LoggerFactory.getLogger(EnvTests.class); + + int testCount = 0; + + @TestFactory + Collection dynamicTestsFromCollection() { + return Arrays.asList( + dynamicTest("1st dynamic test", () -> assertTrue(true)), + dynamicTest("2nd dynamic test", () -> assertEquals(4, 2 * 2)) + ); + } + + /** + *
+     * Denotes that the annotated method should be executed before all
+     * @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class;
+     * analogous to JUnit 4’s @BeforeClass. Such methods are inherited (unless they are hidden or overridden)
+     * and must be static (unless the "per-class" test instance lifecycle is used).
+     * 
+ */ + @BeforeAll + public static void beforeAll() { + log.info("this is run before all test cases"); + } + + @BeforeEach + public void beforeEach() { + log.info("this is run before each test case: {}", testCount++); + } + + @AfterEach + public void afterEach() { + log.info("this is run after each test case: {}", testCount); + } + + /** + *
+     * Denotes that a method is a test method. Unlike JUnit 4’s @Test annotation,
+     * this annotation does not declare any attributes,
+     * since test extensions in JUnit Jupiter operate based on their own dedicated annotations.
+     * Such methods are inherited unless they are overridden.
+     * 
+ */ + @Test + public void testCase1() { + log.info("this is a test run for junit @Test"); + } + + @Test + public void testCase2() { + log.info("this is a test run for junit @Test"); + } + + @Test + @Disabled + public void testAbort() { + log.info("this test aborts the junit"); + System.exit(1); + } + + @RepeatedTest(3) + public void testRepeated() { + log.info("I am not sure how many times I am repeated"); + } + + @RepeatedTest(3) + public void testRepeated1(RepetitionInfo rpi) { + log.info("I am being repeated the {}-th time out of {} times", rpi.getCurrentRepetition(), rpi.getTotalRepetitions()); + } + + @RepeatedTest(value = 3) + public void testRepeated2(RepetitionInfo rpi) { + log.info("I am being repeated the {}-th time out of {} times", rpi.getCurrentRepetition(), rpi.getTotalRepetitions()); + if (rpi.getCurrentRepetition() == 2) { + throw new RuntimeException("enough! stop!"); + } + } + + @Test + public void testWhatInfo(TestInfo ti) { + log.info("what is in the TestInfo:\n\t{}", ti); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2, 3, 4}) + public void testParamsFromValueSrc(int arg) { + log.info("what parameter is it? \n\t{}", arg); + } + +// @ParameterizedTest +// @ValueSource(ints = {1, 2, 3, 4}) +// public void testParamsFromValueSrcExt(int arg, ParameterContext aa) { +// log.info("what parameter is it? \n\t{}\n\t among {}", arg, aa); +// } + + @AfterAll + public static void afterAll() { + log.info("this is run after all test cases"); + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/ArithmeticTests.java b/jdk-study/src/test/java/study/java/lang/base/ArithmeticTests.java new file mode 100644 index 0000000..f4df07c --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/ArithmeticTests.java @@ -0,0 +1,64 @@ +package study.java.lang.base; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ArithmeticTests { + static final Logger log = LoggerFactory.getLogger(ArithmeticTests.class); + + @Test + public void testAdd() { + { + log.info("add different types of numbers to integer"); + int _i = Integer.MAX_VALUE; + log.info("1 + {} = {}", _i, 1 + _i); + long _l = Long.MAX_VALUE; + log.info("1 + {} = {}", _l, 1 + _l); + short _s = Short.MAX_VALUE; + log.info("1 + {} = {}", _s, 1 + _s); + byte _b = Byte.MAX_VALUE; + log.info("1 + {} = {}", _b, 1 + _b); + double _f = Float.MAX_VALUE; + log.info("1 + {} = {}", _f, 1 + _f); + double _d = Double.MAX_VALUE; + log.info("1 + {} = {}", _d, 1 + _d); + } + } + + @Test + public void testMod() { + { + log.info("-3 % 2 = {}", -3 % 2); + log.info("3 % -2 = {}", 3 % -2); + + int _i = Integer.MAX_VALUE; + long _l = Long.MAX_VALUE; + log.info("{} % {} = {}", _l, (_l - _i), _l % (_l - _i)); + } + + { + log.info("5 % 4 = {}", 5 % 4); + log.info("5 % 2 + 2 = {}", 5 % 2 + 2); + log.info("5 % 2 * 2 = {}", 5 % 2 * 2); + log.info("2 + 5 % 2 = {}", 2 + 5 % 2); + log.info("2 * 5 % 2 = {}", 2 * 5 % 2); + } + + { + log.info("0.75 % 0.5 = {}", 0.75 % 0.5); + log.info("0.75 % 1.5 = {}", 0.75 % 1.5); + log.info("(2/3) % (5/7) = {}", (2 / 3.0) % (5 / 7.0)); + log.info("(5/3) % (5/7) = {} \t 5 / 21.0 = {}", (5 / 3.0) % (5 / 7.0), 5 / 21.0); + log.info("(4/3) % (5/7) = {} \t 5 / 21.0 = {}", (4 / 3.0) % (5 / 7.0), 13 / 21.0); + } + + try { + log.info("3 % 0 = {}", 3 % 0); + Assertions.fail("should be ArithmeticException"); + } catch (Exception e) { + log.error("can not mod by 0, {}", e.getMessage()); + } + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/IntTests.java b/jdk-study/src/test/java/study/java/lang/base/IntTests.java new file mode 100644 index 0000000..61fa671 --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/IntTests.java @@ -0,0 +1,115 @@ +package study.java.lang.base; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import study.JdkStudyUtils; +import sun.misc.Unsafe; + +import java.lang.reflect.Field; +import java.nio.ByteOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static study.JdkStudyUtils.toBinStr; + +public class IntTests { + static final Logger log = LoggerFactory.getLogger(IntTests.class); + static final Unsafe us = JdkStudyUtils.getUnsafe(); + + int b; + int intValue = 0xAA << 24 | 0xCC << 16 | 0xEE << 8 | 0xFF; + + @Test + public void testUnsafeOper() throws Exception { + + Field f = IntTests.class.getDeclaredField("intValue"); + long offset = us.objectFieldOffset(f); + byte b1 = us.getByte(this, offset); + byte b2 = us.getByte(this, offset + 1); + byte b3 = us.getByte(this, offset + 2); + byte b4 = us.getByte(this, offset + 3); + + log.info("{}\t{}", intValue, toBinStr(intValue)); + log.info("{}\t{}\t{}\t{}", toBinStr(b1), toBinStr(b2), toBinStr(b3), toBinStr(b4)); + log.info(ByteOrder.nativeOrder().toString()); + } + + @Test + public void testIntDef() { + int a = 0; + assertEquals(a, 0); + a = 1; + assertEquals(a, 1); +// int b, c = 5; //compile error, b is not initialized + assertEquals(b, 0); +// int d=e=4; //e is not defined + int d = 0, e = 0; + d = e = 3; + assertEquals(d, e); + } + + @Test + public void testValueRange() { + assertEquals(32, Integer.SIZE); + assertEquals(4, Integer.BYTES); + + log.info("Integer.MAX_VALUE ={}\t{}", Integer.MAX_VALUE, toBinStr(Integer.MAX_VALUE)); + log.info("Integer.MIN_VALUE = {}\t{}", Integer.MIN_VALUE, toBinStr(Integer.MIN_VALUE)); + + { + int i = Integer.MAX_VALUE + 1; + log.info("Integer.MAX_VALUE + 1 = {}\t{}", i, toBinStr(i)); + i = Integer.MAX_VALUE + 2; + log.info("Integer.MAX_VALUE + 2 = {}\t{}", i, toBinStr(i)); + } + + { + int i = Integer.MIN_VALUE - 1; + log.info("Integer.MIN_VALUE - 1 = {}\t{}", i, toBinStr(i)); + i = Integer.MIN_VALUE - 2; + log.info("Integer.MIN_VALUE - 2 = {}\t{}", i, toBinStr(i)); + } + + { + int i = Integer.MAX_VALUE + Integer.MAX_VALUE; + log.info("Integer.MAX_VALUE + Integer.MAX_VALUE = {}\t{}", i, toBinStr(i)); + i = Integer.MAX_VALUE + Integer.MIN_VALUE; + log.info("Integer.MAX_VALUE + Integer.MIN_VALUE = {}\t{}", i, toBinStr(i)); + i = Integer.MIN_VALUE + Integer.MIN_VALUE; + log.info("Integer.MIN_VALUE + Integer.MIN_VALUE = {}\t{}", i, toBinStr(i)); + } + + { + int i = Integer.MAX_VALUE - Integer.MAX_VALUE; + log.info("Integer.MAX_VALUE - Integer.MAX_VALUE = {}\t{}", i, toBinStr(i)); + i = Integer.MAX_VALUE - Integer.MIN_VALUE; + log.info("Integer.MAX_VALUE - Integer.MIN_VALUE = {}\t{}", i, toBinStr(i)); + i = Integer.MIN_VALUE - Integer.MIN_VALUE; + log.info("Integer.MIN_VALUE - Integer.MIN_VALUE = {}\t{}", i, toBinStr(i)); + } + } + + @Test + public void testCasting() { + int i = Integer.MAX_VALUE; + { + short s = (short) i; + log.info("int {}|{} to short {}|{}", i, toBinStr(i), s, toBinStr(s)); + int j = s; + log.info("short {}|{} to int {}|{}", s, toBinStr(s), j, toBinStr(j)); + } + { + byte b = (byte) i; + log.info("int {}|{} to byte {}|{}", i, toBinStr(i), b, toBinStr(b)); + int j = b; + log.info("byte {}|{} to int {}|{}", b, toBinStr(b), j, toBinStr(j)); + } + } + + @Test + public void testComplement() { + log.info("{}\t{}", 4, toBinStr(4)); + log.info("{}\t{}", ~4, toBinStr(~4)); + log.info("{}\t{}", -4, toBinStr(-4)); + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/Java12FeatureTests.java b/jdk-study/src/test/java/study/java/lang/base/Java12FeatureTests.java new file mode 100644 index 0000000..e0574fa --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/Java12FeatureTests.java @@ -0,0 +1,25 @@ +package study.java.lang.base; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.DayOfWeek; + +public class Java12FeatureTests { + + static final Logger log = LoggerFactory.getLogger(Java12FeatureTests.class); + + @ParameterizedTest + @EnumSource(value = DayOfWeek.class, names = {"MONDAY", "SUNDAY"}) + public void switchExp(DayOfWeek d) { +// log.info("{} is {}", +// d, +// switch (d) { +// case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "weekday"; +// case SATURDAY, SUNDAY -> "weekend"; +// default -> throw new IllegalArgumentException("what is " + d); +// }); + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/KeywordAndGrammaTests.java b/jdk-study/src/test/java/study/java/lang/base/KeywordAndGrammaTests.java new file mode 100644 index 0000000..41383b7 --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/KeywordAndGrammaTests.java @@ -0,0 +1,134 @@ +package study.java.lang.base; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Comparator; +import java.util.Random; +import java.util.concurrent.Callable; + +public class KeywordAndGrammaTests { + static final Logger log = LoggerFactory.getLogger(KeywordAndGrammaTests.class); + + public static final String[] KEY_WORDS = {"abstract", // checked + "assert", // checked + "boolean", "break", // checked + "byte", "case", // checked + "catch", "char", "class", "const", // checked + "continue", "default", // checked + "do", "double", "else", // checked + "enum", "extends", "final", "finally", "float", "for", "goto", "if", // checked + "implements", "import", // checked + "instanceof", "int", "interface", "long", "native", "new", "package", // checked + "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", // checked + "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"}; + + static int cmp(C cmp1, C cmp2, String mark) { + log.info("comparing {} to {} with mark:\t{}", cmp1, cmp2, mark); + return Comparator.nullsFirst(Comparator.naturalOrder()).compare(cmp1, cmp2); + } + + @Test + public void testIfAndElse() { + if (true) log.info("if (true)"); + if (false) log.info("if (false)"); + + if (false) ; + else log.info("no true"); + + int i = 5; + + if (cmp(i, 0, "i == 0") == 0) { + log.info("i:{} == 0", i); + } else if (cmp(i, 0, "i > 0") > 0) { + log.info("i:{} > 0", i); + } else { + log.info("i:{} < 0", i); + } + + int j = 0; + Random rand = new Random(); + if ((j = rand.nextInt()) > 10) { + log.info("j: {} > 10", j); + } + Assertions.assertNotEquals(0, j); + log.info("j: {} changed", j); + + //invalid +// if ((int k = rand.nextInt()) >10){ +// log.info("k: {} > 10", k); +// } +// log.info("k: {} changed", k); + } + + @Test + public void testAssert() throws Exception { + assert true; + log.info("assert true"); +// assert false; // run java with "-ea", this throws AssertError +// log.info("assert false"); + + Assertions.assertThrows(AssertionError.class, () -> { + assert cmp(1, 2, "false") > 0 : "1 is not greater than 2"; + }, "got you, AssertionError"); + + //invalid +// assert null; + + Assertions.assertThrows(NullPointerException.class, () -> { + Boolean nullBoolean = null; + assert nullBoolean; + }, "got you, NullPointerException"); + + Assertions.assertThrows(RuntimeException.class, () -> { + Callable foo = () -> { + throw new RuntimeException("Boom"); + }; + assert false : foo.call(); + }, "got you, RuntimeException"); + } + + @Test + public void testBreak() { + // break; break can't be used outside of loop or switch + for (int i = 0; i < 1; i++) { + break; + } + do { + break; + } while (true); + + while (true) { + break; + } + + switch (1) { + case 1: + break; + default: + break; + } + + _outer: + for (int i = 0; i < 3; i++) { + log.info("outer begins: " + i); + _inner: for (int j = 0; j < i; j++) { + log.info("\t" + j); + break _inner; // jump out of outer loop too + } + log.info("outer ends: " + i); + } + + _outer: + for (int i = 0; i < 3; i++) { + log.info("outer begins: " + i); + _inner: for (int j = 0; j < i; j++) { + log.info("\t" + j); + break _outer; // jump out of outer loop too + } + log.info("outer ends: " + i); + } + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/ThreadLocalTests.java b/jdk-study/src/test/java/study/java/lang/base/ThreadLocalTests.java new file mode 100644 index 0000000..8d3a722 --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/ThreadLocalTests.java @@ -0,0 +1,58 @@ +package study.java.lang.base; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import study.commons.MiscUtils; + +import java.lang.ref.Cleaner; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class ThreadLocalTests { + static final Logger log = LoggerFactory.getLogger(ThreadLocalTests.class); + static ThreadLocal tl = null; + + static final Cleaner cleaner = Cleaner.create(); + + static class DummyEntry { + Cleaner.Cleanable c = null; + + public DummyEntry() { +// log.info(MiscUtils.invocInfo()); + c = cleaner.register(this, this::getCleaned); + } + + public void getCleaned() { + log.info(MiscUtils.invocationInfo(5)); + } + } + + @BeforeClass + public static void initThreadLocal() { + tl = ThreadLocal.withInitial(DummyEntry::new); + } + + @Test + public void testLocalValueFinalization() throws InterruptedException { + tl.get(); + tl.remove(); + tl.get(); + tl.get(); + tl.get(); + + { + ExecutorService es = Executors.newCachedThreadPool(); //.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + for (int i = 0; i < 1000; i++) { + es.submit(() -> { + tl.get(); + }); + } + es.shutdownNow(); + while (!es.isTerminated()) + es.awaitTermination(2, TimeUnit.SECONDS); + } + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/ThreadTests.java b/jdk-study/src/test/java/study/java/lang/base/ThreadTests.java new file mode 100644 index 0000000..b20e5d9 --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/ThreadTests.java @@ -0,0 +1,240 @@ +package study.java.lang.base; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static study.commons.MiscUtils.easySleep; + +public class ThreadTests { + static final Logger log = LoggerFactory.getLogger(ThreadTests.class); + + public static class DaemonThreadTest { + static { + log.info("first in static {}", Thread.currentThread()); + Thread.currentThread().setDaemon(true); + } + + public static void main(String[] args) { + log.info("first in main"); + try { + new ThreadTests().testDaemon(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Test + public void testDaemon() throws Exception { + log.info("starting Daemon thread"); + + Thread thread = new Thread(() -> { + log.info("thread started"); + try { + Thread.sleep(1000); + log.info("sleep 1"); + Thread.sleep(1000); + log.info("sleep 2"); + Thread.sleep(1000); + log.info("sleep 3"); + } catch (Exception e) { + log.error("?", e); + } + log.info("thread stopped"); + }); + + thread.setDaemon(false); + thread.start(); + Thread.sleep(10); +// thread.join(); + log.info("exit"); + } + + @Test + public void testDaemonInfiniteLoop() throws Exception { + log.info("starting Daemon thread"); + + Thread thread = new Thread(() -> { + log.info("thread started"); + try { + while (true) { + Thread.sleep(1000); + log.info("sleep 1"); + Thread.sleep(1000); + log.info("sleep 2"); + Thread.sleep(1000); + log.info("sleep 3"); + } + } catch (Exception e) { + log.error("?", e); + } + log.info("thread stopped"); + }); + + Thread waitForThread = new Thread(() -> { + try { + thread.join(); + } catch (InterruptedException e) { + log.error("?", e); + } + }); + +// thread.setDaemon(true); + thread.start(); + waitForThread.start(); + Thread.sleep(1010); + } + + @Test + public void testThreadHoldingMain() throws Exception { + log.info("starting test"); + Thread thread = new Thread(() -> { + jam(2000); + }); + thread.start(); + Thread.sleep(1000); + thread.join(); + log.info("I go first"); + } + + private static void jam(int millisec) { + log.info("start jamming"); + long now = System.currentTimeMillis(); + while (System.currentTimeMillis() - now < millisec) { + double d = Math.pow(Math.PI, Math.E); + } + log.info("stop jamming"); + } + + @Test + public void testInterrupt() { + Thread th = new Thread(() -> { + try { + for (int i = 0; i < 5; i++) { +// Thread.sleep(1000); + jam(1000); + log.info("am I interrupted? {}", Thread.currentThread().isInterrupted()); + } + } catch (Exception e) { + log.error("I am interrupted by {}", e); + } + }); + th.start(); + try { + Thread.sleep(3500); + th.interrupt(); + th.join(); + } catch (InterruptedException e) { + log.error("I am interrupted by {}", e); + } + } + + @Test + public void testDeadLock() { + String a = "a"; + String b = "b"; + + Thread th1 = new Thread(() -> { + log.info("going to get a"); + try { + synchronized (a) { + easySleep(1000); + log.info("I have a, going to get b"); + synchronized (b) { + log.info("I have both a and b"); + } + log.info("what happened?"); + } + } catch (Exception e) { + log.error("what happened? \n{}", e); + } + }); + + Thread th2 = new Thread(() -> { + log.info("going to get b"); + try { + synchronized (b) { + easySleep(1000); + log.info("I have b, going to get a"); + synchronized (a) { + log.info("I have both a and b"); + } + } + } catch (Exception e) { + log.error("what happened? \n{}", e); + } + }); + + th1.start(); + th2.start(); + try { + th1.join(3000); + log.info("state of th1 {}", th1.getState()); + th2.join(3000); + log.info("state of th2 {}", th1.getState()); + th1.interrupt(); + easySleep(1000); + log.info("state of th1 {} after interruption", th1.getState()); + } catch (InterruptedException e) { + log.error("I am interrupted by {}", e); + } + log.info("I go first"); + } + + @Test + public void testAvertDeadLock() { + String a = "a"; + String b = "b"; + + Thread th1 = new Thread(() -> { + log.info("going to get a"); + try { + synchronized (a) { + easySleep(1000); + log.info("I had a, give up a now, going to get b"); + a.wait(); + synchronized (b) { + log.info("I have both a and b"); + } + log.info("what happened?"); + } + } catch (Exception e) { + log.error("what happened? \n{}", e, e); + } + }); + + Thread th2 = new Thread(() -> { + log.info("going to get b"); + try { + synchronized (b) { + easySleep(1000); + log.info("I had b, going to get a"); + synchronized (a) { + log.info("I have both a and b"); + a.notifyAll(); + } + log.info("now you can take b"); + b.wait(); + } + } catch (Exception e) { + log.error("what happened? \n{}", e); + } + }); + + th1.start(); + th2.start(); + try { + th1.join(3000); + log.info("state of th1 {}", th1.getState()); + th2.join(3000); + log.info("state of th2 {}", th1.getState()); + th1.interrupt(); + easySleep(1000); + log.info("state of th1 {} after interruption", th1.getState()); + } catch (InterruptedException e) { + log.error("I am interrupted by {}", e); + } + log.info("I go first"); + } +} diff --git a/jdk-study/src/test/java/study/java/lang/base/VarScopeTests.java b/jdk-study/src/test/java/study/java/lang/base/VarScopeTests.java new file mode 100644 index 0000000..aa4ab1d --- /dev/null +++ b/jdk-study/src/test/java/study/java/lang/base/VarScopeTests.java @@ -0,0 +1,77 @@ +package study.java.lang.base; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.function.Function; +import java.util.function.Supplier; + +public class VarScopeTests { + static final Logger log = LoggerFactory.getLogger(VarScopeTests.class); + + static int i = 0; + + // int i = 1; //conflict with static i + { + log.info("what is i before initial block? \n\t{}", i); + int i = 2; + log.info("what is i after initial block? \n\t{}\n\t or VarScopeTests.i: {}", i, VarScopeTests.i); + } + + @Test + public void testScope() { + int i = 3; + log.info("i inside testScope() is \n\t{}", i); + { +// int i = 4;//i is already defined in outer scope + int j = 4; + log.info("j inside { } inside testScope() is \n\t{}", j); + } + int j = 5; + log.info("j inside testScope() is \n\t{}", j); + + Runnable r = () -> { + log.info("check j from inside Runnable inside testScope() is \n\t{}", j); +// int j = 6; //conflict with j in outer scope + }; + r.run(); + + stub(() -> { + int k = 8; + log.info("check k from inside Runnable inside testScope() is \n\t{}", k); + }); + +// Function f = (Runnable r)->{ /* r is already defined at line 338*/}; + Function f = (Runnable _r) -> { + int k = 9; + _r.run(); + log.info("check k from inside lambda f() is \n\t{}", k); + return null; + }; + + f.apply(() -> { + int k = 10; + log.info("check k from inside Runnable passed to f inside testScope() is \n\t{}", k); + }); + + Supplier> s = () -> { + Integer l = 11; + return () -> l; + }; + int l = 12; + + for (int a = 0; a < 1; a++) { + log.info("check a from for loop: {}", a); + } +// log.info("check a after for loop: {}", a); + int a = -1; + log.info("check new a after for loop: {}", a); + } + + void stub(Runnable r) { + int k = 7; + r.run(); + log.info("check k from inside stub() is \n\t{}", k); + } +} diff --git a/jdk-study/src/test/java/study/java/util/LinkedHashMapTests.java b/jdk-study/src/test/java/study/java/util/LinkedHashMapTests.java new file mode 100644 index 0000000..00e4b67 --- /dev/null +++ b/jdk-study/src/test/java/study/java/util/LinkedHashMapTests.java @@ -0,0 +1,34 @@ +package study.java.util; + +import org.apache.commons.collections4.IteratorUtils; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.LinkedHashMap; + +public class LinkedHashMapTests { + static final Logger log = LoggerFactory.getLogger(LinkedHashMapTests.class); + + @Test + public void testOrder1() { + LinkedHashMap lhm = new LinkedHashMap<>(16,0.75f,true); + lhm.put("banana", "yellow"); + lhm.put("apple", "red"); + lhm.put("watermelon", "green"); + lhm.put("plum", "purple"); + + log.info("Order: \n\tkeys:\t{}\n\tvalues:\t{}\n\tentries:\t{}", + lhm.keySet(), + lhm.values(), + IteratorUtils.toString(lhm.entrySet().iterator())); + + lhm.get("banana"); + lhm.get("watermelon"); + + log.info("Order: \n\tkeys:\t{}\n\tvalues:\t{}\n\tentries:\t{}", + lhm.keySet(), + lhm.values(), + IteratorUtils.toString(lhm.entrySet().iterator())); + } +} diff --git a/jdk-study/src/test/java/study/java/util/ListTests.java b/jdk-study/src/test/java/study/java/util/ListTests.java new file mode 100644 index 0000000..ad7dba9 --- /dev/null +++ b/jdk-study/src/test/java/study/java/util/ListTests.java @@ -0,0 +1,27 @@ +package study.java.util; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class ListTests { + static final Logger log = LoggerFactory.getLogger(ListTests.class); + + @Test + public void testRemoveInForeach() { + List list = new ArrayList<>(); + list.add("1"); + list.add("2"); + + for (String str : list) { + if ("2".equals(str)) { + list.remove(str); + } + } + log.info("list is {}", list); + } + +} diff --git a/jdk-study/src/test/resources/log4j2.xml b/jdk-study/src/test/resources/log4j2.xml new file mode 100644 index 0000000..739f19f --- /dev/null +++ b/jdk-study/src/test/resources/log4j2.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 4623b77..08ff401 100644 --- a/pom.xml +++ b/pom.xml @@ -1,151 +1,161 @@ - - 4.0.0 - study_java_8 - study_java_8 - 0.0.1-SNAPSHOT - - - - com.fasterxml.jackson.core - jackson-databind - 2.5.0-rc1 - - - junit - junit - 4.10 - - - org.apache.commons - commons-lang3 - 3.1 - - - org.apache.commons - commons-collections4 - 4.0 - - - org.apache.commons - commons-io - 1.3.2 - - - - org.jboss - jandex - 1.2.0.Final - - - - - - org.jboss.weld.se - weld-se - 2.2.6.Final - - - - - - com.google.guava - guava - 18.0 - - - log4j - log4j - 1.2.17 - - - - - - - - org.mozilla - rhino - 1.7R4 - - - - - - - - - org.hibernate.javax.persistence - hibernate-jpa-2.1-api - 1.0.0.Final - - - - org.hibernate - hibernate-entitymanager - 4.3.7.Final - - - - - org.glassfish.hk2 - class-model - 2.4.0-b07 - - - - org.apache.xbean - xbean-classloader - 4.1 - - - - org.python - jython - 2.7-b1 - - - - org.apache.lucene - lucene-queries - 4.10.3 - - - - org.hsqldb - hsqldb - 2.3.2 - - - - - src/main/java - src/main/java - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=256m - - - - always - - - - - + + 4.0.0 + java-study + java-study + 0.1.2 + pom + + + 5.5.1 + + + + jdk-study + java-ee-study + testing-study + + + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + + org.junit.vintage + junit-vintage-engine + ${junit.jupiter.version} + + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.12.1 + + + + org.apache.commons + commons-lang3 + 3.9 + + + + org.apache.commons + commons-collections4 + 4.4 + + + + com.fasterxml.jackson.core + jackson-databind + 2.10.0.pr2 + + + + org.apache.commons + commons-io + 1.3.2 + + + commons-io + commons-io + + + + + + org.apache.commons + commons-compress + 1.4.1 + + + + commons-codec + commons-codec + LATEST + + + + org.apache.httpcomponents + fluent-hc + LATEST + + + + javax.xml.bind + jaxb-api + LATEST + + + com.sun.xml.bind + jaxb-core + LATEST + + + com.sun.xml.bind + jaxb-impl + LATEST + + + + + + + maven-compiler-plugin + 3.8.1 + + 12 + 12 + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + false + 3.0 + false + true + true + true + + + false + UTF-8 + false + + + false + false + true + true + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.8.2 + + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 3.0.0-M4 + + + diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/WeldTest.java b/src/main/java/cf/study/java8/javax/cdi/weld/WeldTest.java deleted file mode 100644 index 4d23796..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/WeldTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package cf.study.java8.javax.cdi.weld; - -import java.util.Set; -import java.util.function.Consumer; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.spi.Bean; -import javax.enterprise.inject.spi.BeanManager; -import javax.enterprise.inject.spi.CDI; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.jboss.weld.context.RequestContext; -import org.jboss.weld.context.unbound.UnboundLiteral; -import org.jboss.weld.environment.se.Weld; -import org.jboss.weld.environment.se.WeldContainer; -import org.jboss.weld.literal.AnyLiteral; -import org.jboss.weld.literal.NamedLiteral; -import org.jboss.weld.literal.NormalScopeLiteral; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import cf.study.java8.javax.cdi.weld.beans.AppBean; -import cf.study.java8.javax.cdi.weld.beans.BizRequest; - -public class WeldTest { - - static Weld weld; - static WeldContainer container; - static BeanManager bm; - static CDI cdi; - - // @Inject - - @BeforeClass - public static void setUp() { - try { - weld = new Weld(); - container = weld.initialize(); - bm = container.getBeanManager(); - cdi = CDI.current(); - } catch (final Exception e) { - e.printStackTrace(); - System.exit(-1); - } - } - - @Test - public void testAppBean() throws Exception { - System.out.println(bm.getBeans("appBean")); - Set> appBeans = bm.getBeans(AppBean.class); - System.out.println(appBeans); - appBeans.forEach((bean) -> { - System.out.println(ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE)); - System.out.println(bm.getReference(bean, AppBean.class, bm.createCreationalContext(bean))); - }); - } - - @Test - public void testBizReq() throws Exception { - /** - * In this case Weld is using unbound RequestContext that is associated with a thread (RequestContext). - * You need to manually initialize new RequestContext in a thread that You're creating - */ - RequestContext reqCtx = (RequestContext) cdi.select(RequestContext.class, UnboundLiteral.INSTANCE).get(); - reqCtx.activate(); - - System.out.println(bm.getBeans("bizRequest")); - Set> bizReqs = bm.getBeans(BizRequest.class); - System.out.println(bizReqs); - bizReqs.forEach((bean) -> { - System.out.println(ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE)); - System.out.println(bm.getReference(bean, BizRequest.class, bm.createCreationalContext(bean))); - }); - } - - @SuppressWarnings("unchecked") - @Test - public void testSelectClzzByScope() { - Consumer printer = (i) -> { - try { - System.out.println(ToStringBuilder.reflectionToString(i, ToStringStyle.MULTI_LINE_STYLE)); - } catch (Exception e) { - e.printStackTrace(); - } - }; - -// cdi.forEach(printer); - - bm.getBeans(Object.class, AnyLiteral.INSTANCE).forEach(printer); - } - - @AfterClass - public static void tearDown() { - - if (weld != null) - weld.shutdown(); - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/AppBean.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/AppBean.java deleted file mode 100644 index c816c99..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/AppBean.java +++ /dev/null @@ -1,27 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.enterprise.context.ApplicationScoped; - -import misc.MiscUtils; - -import org.apache.log4j.Logger; - -@ApplicationScoped -public class AppBean extends BasicBean { - - private static Logger log = Logger.getLogger(AppBean.class); - - @PostConstruct - public void postConstruct() { - log.info(MiscUtils.invocationInfo() + "\n\t" + this); - } - - @PreDestroy - public void preDestroy() { - log.info(MiscUtils.invocationInfo() + "\n\t" + this); - } - - -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/BasicBean.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/BasicBean.java deleted file mode 100644 index 16f9a6e..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/BasicBean.java +++ /dev/null @@ -1,84 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.enterprise.context.Dependent; -import javax.inject.Inject; - -import misc.MiscUtils; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.apache.log4j.Logger; - -@Dependent -public class BasicBean { - - private static Logger log = Logger.getLogger(BasicBean.class); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getCreatedTime() { - return createdTime; - } - - @Inject - protected Long id; - protected Long createdTime = System.currentTimeMillis(); - protected String name; - - public Long getId() { - return id; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof BasicBean)) - return false; - BasicBean other = (BasicBean) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - public BasicBean() { - //log.info(MiscUtils.invocationInfo() + "\n\t" + this); - } - - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } - - @PostConstruct - public void postConstruct() { - log.info(MiscUtils.invocationInfo() + "\n\t" + this); - } - - @PreDestroy - public void preDestroy() { - log.info(MiscUtils.invocationInfo() + "\n\t" + this); - } - - -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/BizRequest.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/BizRequest.java deleted file mode 100644 index 48ca72b..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/BizRequest.java +++ /dev/null @@ -1,21 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import javax.enterprise.context.RequestScoped; - -import org.apache.log4j.Logger; - -@RequestScoped -public class BizRequest extends BasicBean { - - private static Logger log = Logger.getLogger(BizRequest.class); - - private Object param; - - public Object getParam() { - return param; - } - - public void setParam(Object param) { - this.param = param; - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/IBizProcessor.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/IBizProcessor.java deleted file mode 100644 index e2ae03d..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/IBizProcessor.java +++ /dev/null @@ -1,8 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import javax.inject.Named; - -@Named -public interface IBizProcessor { - R proc(final P param); -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/InterfaceProcessor.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/InterfaceProcessor.java deleted file mode 100644 index f2c4a7b..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/InterfaceProcessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Named; - -@SuppressWarnings("rawtypes") -@ApplicationScoped -@Named("infProc") -public class InterfaceProcessor implements IBizProcessor> { - - @Override - public List proc(final Object param) { - if (param == null) { - return Collections.emptyList(); - } - - return Arrays.asList(param.getClass().getInterfaces()); - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/MethodProcessor.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/MethodProcessor.java deleted file mode 100644 index e6afeee..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/MethodProcessor.java +++ /dev/null @@ -1,26 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Named; - -@SuppressWarnings("rawtypes") -@ApplicationScoped -@Named("mdProc") -public class MethodProcessor implements IBizProcessor> { - - @Override - public List proc(final Object param) { - if (param == null) { - return Collections.emptyList(); - } - - final Class cls = param.getClass(); - - return Arrays.asList(cls.getMethods()); - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/SeqGenerator.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/SeqGenerator.java deleted file mode 100644 index 35c7fbe..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/SeqGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import java.util.concurrent.atomic.AtomicLong; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.inject.Inject; - -import misc.MiscUtils; - -import org.apache.log4j.Logger; - -//@Singleton -@ApplicationScoped -public class SeqGenerator { - private static Logger log = Logger.getLogger(SeqGenerator.class); - - private AtomicLong seq; - - public SeqGenerator() {} - - @Produces - public Long getSeq() { - final long newId = seq.incrementAndGet(); - log.info(String.format("%s \t-> \t{newId: %d}", MiscUtils.invocationInfo(), newId)); - return newId; - } - - @PostConstruct - public void postConstruct() { - log.info(MiscUtils.invocationInfo()); - seq = new AtomicLong(); - } - - @PreDestroy - public void preDestroy() { - log.info(MiscUtils.invocationInfo()); - log.info(String.format("last id: %d", seq.get())); - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/StatefulBizBean.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/StatefulBizBean.java deleted file mode 100644 index 38445e2..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/StatefulBizBean.java +++ /dev/null @@ -1,25 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import java.io.Serializable; - -import javax.enterprise.context.SessionScoped; - -import org.apache.log4j.Logger; - -@SessionScoped -public class StatefulBizBean extends BasicBean implements Serializable { - - private static final long serialVersionUID = 1L; - - private static Logger log = Logger.getLogger(StatefulBizBean.class); - - private Object state; - - public Object getState() { - return state; - } - - public void setState(Object state) { - this.state = state; - } -} diff --git a/src/main/java/cf/study/java8/javax/cdi/weld/beans/TypeProcessor.java b/src/main/java/cf/study/java8/javax/cdi/weld/beans/TypeProcessor.java deleted file mode 100644 index 251cd90..0000000 --- a/src/main/java/cf/study/java8/javax/cdi/weld/beans/TypeProcessor.java +++ /dev/null @@ -1,29 +0,0 @@ -package cf.study.java8.javax.cdi.weld.beans; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Named; - -@SuppressWarnings("rawtypes") -@ApplicationScoped -@Named("typeProc") -public class TypeProcessor implements IBizProcessor> { - - @Override - public List proc(final Object param) { - if (param == null) { - return Collections.emptyList(); - } - - final List reList = new ArrayList(); - for (Class cls = param.getClass(); !cls.getSuperclass().equals(Object.class); cls = cls.getSuperclass()) { - reList.add(cls); - } - reList.add(Object.class); - return reList; - } - -} diff --git a/src/main/java/cf/study/java8/javax/jndi/JndiTest.java b/src/main/java/cf/study/java8/javax/jndi/JndiTest.java deleted file mode 100644 index 6063326..0000000 --- a/src/main/java/cf/study/java8/javax/jndi/JndiTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package cf.study.java8.javax.jndi; - -import java.util.Hashtable; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingEnumeration; - -import org.junit.Test; - -public class JndiTest { - - public static void traverseContext(final Context ctx) throws Exception { - if (ctx == null) { - return; - } - -// final NamingEnumeration list = ctx.list("/"); - final NamingEnumeration list = ctx.listBindings(""); - while (list != null && list.hasMore()) { - final Binding next = list.next(); - System.out.println(next); - - final Object _lookup = next.getObject(); - if (_lookup instanceof Context) { - Context _ctx = (Context) _lookup; - traverseContext(_ctx); - } - } - } - - @Test - public void example_1() throws Exception { - - //create an initial context - Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); - Context ctx = new InitialContext(env); - - traverseContext(ctx); - - ctx.close(); - } -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ClazzEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ClazzEn.java deleted file mode 100644 index 97c01f5..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ClazzEn.java +++ /dev/null @@ -1,104 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import java.lang.annotation.Annotation; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Stream; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.Element; -import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.type.TypeVisitor; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - -@Entity -public class ClazzEn implements DeclaredType { - - public ClazzEn() { - } - - public ClazzEn(Class clz) { - typeEn = new TypeElementEn(clz); - -// if (clz.) - } - - @Id - public long id; - - @OneToOne(cascade = { CascadeType.REFRESH }) - public TypeElementEn typeEn; - - @Enumerated(EnumType.STRING) - public TypeKind kind; - - @OneToOne - public ClazzEn enclosingType; - - @OneToMany - public List typeArguments = new LinkedList(); - - public TypeKind getKind() { - return kind; - } - - public R accept(TypeVisitor v, P p) { - return null; - } - - public List getAnnotationMirrors() { - return null; - } - - public A getAnnotation(Class annotationType) { - return null; - } - - public A[] getAnnotationsByType(Class annotationType) { - return null; - } - - public Element asElement() { - return typeEn; - } - - public TypeMirror getEnclosingType() { - return enclosingType; - } - - public List getTypeArguments() { - return typeArguments; - } - - public Class getClazz() { - try { - return Class.forName(typeEn.getQualifiedName().toString()); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - public static class Factory { - public static Class[] toArray(Collection col) { - return col.stream().map((clazzEn) -> clazzEn.getClazz()).toArray(Class[]::new); - } - - public static ClazzEn[] toList(Class... clss) { - if (clss == null) - return new ClazzEn[0]; - return Stream.of(clss).map((cls) -> { - return new ClazzEn(cls); - }).toArray(ClazzEn[]::new); - } - } -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ElementEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ElementEn.java deleted file mode 100644 index 6ebd96b..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/ElementEn.java +++ /dev/null @@ -1,85 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import java.lang.annotation.Annotation; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.element.ElementVisitor; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.Name; -import javax.lang.model.type.TypeMirror; -import javax.persistence.Basic; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; - -@Entity -public class ElementEn implements Element { - - @Id - public long id; - - @Basic - public String simpleName; - - @Basic - public String modifierStr; - - @Enumerated(EnumType.STRING) - public ElementKind kind; - - @ManyToOne(cascade = { CascadeType.REFRESH }, optional = true) - public ElementEn enclosingElement; - - @OneToMany(cascade = { CascadeType.REFRESH }) - public List enclosedElements = new LinkedList(); - - public A[] getAnnotationsByType(Class annotationType) { - return null; - } - - public TypeMirror asType() { - return null; - } - - public ElementKind getKind() { - return kind; - } - - public Set getModifiers() { - return null; - } - - public Name getSimpleName() { - return new NameImpl(simpleName); - } - - public Element getEnclosingElement() { - return enclosingElement; - } - - public List getEnclosedElements() { - return enclosedElements; - } - - public List getAnnotationMirrors() { - return null; - } - - public A getAnnotation(Class annotationType) { - return null; - } - - public R accept(ElementVisitor v, P p) { - return null; - } - -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MemberEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MemberEn.java deleted file mode 100644 index 06313ed..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MemberEn.java +++ /dev/null @@ -1,47 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import java.lang.reflect.Member; - -import javax.lang.model.element.Modifier; -import javax.persistence.Basic; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class MemberEn implements Member { - - @Id - public long id; - - @ManyToOne - public ClazzEn declaringClass; - - @Basic - public String name; - - @Enumerated(EnumType.STRING) - public Modifier modifier; - - @Basic - public boolean synthetic; - - public Class getDeclaringClass() { - return declaringClass.getClazz(); - } - - public String getName() { - return name; - } - - public int getModifiers() { - return modifier.ordinal(); - } - - public boolean isSynthetic() { - return synthetic; - } - -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MethodEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MethodEn.java deleted file mode 100644 index 9b6478e..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/MethodEn.java +++ /dev/null @@ -1,50 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedType; -import java.lang.reflect.TypeVariable; -import java.util.LinkedList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.OneToMany; - -@Entity -public class MethodEn extends MemberEn { - - @OneToMany - public List parameterTypes = new LinkedList(); - - @OneToMany - public List exceptionTypes = new LinkedList(); - - public TypeVariable[] getTypeParameters() { - // TODO Auto-generated method stub - return null; - } - - - public Class[] getParameterTypes() { - return ClazzEn.Factory.toArray(parameterTypes); - } - - - public Class[] getExceptionTypes() { - return ClazzEn.Factory.toArray(exceptionTypes); - } - - - public String toGenericString() { - return null; - } - - public Annotation[][] getParameterAnnotations() { - return null; - } - - public AnnotatedType getAnnotatedReturnType() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/NameImpl.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/NameImpl.java deleted file mode 100644 index 894c5aa..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/NameImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import javax.lang.model.element.Name; - -public class NameImpl implements Name { - public final CharSequence content; - - public NameImpl(CharSequence content) { - super(); - this.content = content; - } - - public int length() { - return content.length(); - } - - public char charAt(int index) { - return content.charAt(index); - } - - public CharSequence subSequence(int start, int end) { - return content.subSequence(start, end); - } - - public boolean contentEquals(CharSequence cs) { - return content.equals(cs); - } - - public String toString() { - return String.valueOf(content); - } -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/PackageEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/PackageEn.java deleted file mode 100644 index 152a374..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/PackageEn.java +++ /dev/null @@ -1,25 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import javax.lang.model.element.Name; -import javax.lang.model.element.PackageElement; -import javax.persistence.Basic; -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class PackageEn extends ElementEn implements PackageElement { - - @Basic - public String qualifiedName; - - @Basic - public boolean unnamed = false; - - public Name getQualifiedName() { - return new NameImpl(qualifiedName); - } - - public boolean isUnnamed() { - return unnamed; - } -} diff --git a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/TypeElementEn.java b/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/TypeElementEn.java deleted file mode 100644 index ad9785a..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/ex/reflects/entity/TypeElementEn.java +++ /dev/null @@ -1,63 +0,0 @@ -package cf.study.java8.javax.persistence.ex.reflects.entity; - -import java.util.LinkedList; -import java.util.List; - -import javax.lang.model.element.Name; -import javax.lang.model.element.NestingKind; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.TypeParameterElement; -import javax.lang.model.type.TypeMirror; -import javax.persistence.Basic; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - -@Entity -public class TypeElementEn extends ElementEn implements TypeElement { - - public TypeElementEn() { - } - - public TypeElementEn(Class clz) { - qualifiedName = clz.getName(); - } - - @Basic - public String qualifiedName; - - @OneToOne - public ClazzEn clazz; - - @OneToOne(cascade= {CascadeType.REFRESH}) - public ClazzEn superClazz; - - @OneToMany(cascade= {CascadeType.REFRESH}) - public List interfaces = new LinkedList(); - - @Override - public NestingKind getNestingKind() { - return null; - } - - @Override - public Name getQualifiedName() { - return new NameImpl(qualifiedName); - } - - @Override - public TypeMirror getSuperclass() { - return superClazz; - } - - @Override - public List getInterfaces() { - return interfaces; - } - - @Override - public List getTypeParameters() { - return null; - } -} diff --git a/src/main/java/cf/study/java8/javax/persistence/multi_tables/MultiTablesTests.java b/src/main/java/cf/study/java8/javax/persistence/multi_tables/MultiTablesTests.java deleted file mode 100644 index 5776ba6..0000000 --- a/src/main/java/cf/study/java8/javax/persistence/multi_tables/MultiTablesTests.java +++ /dev/null @@ -1,5 +0,0 @@ -package cf.study.java8.javax.persistence.multi_tables; - -public class MultiTablesTests { - -} diff --git a/src/main/java/cf/study/java8/javax/script/ScriptTest.java b/src/main/java/cf/study/java8/javax/script/ScriptTest.java deleted file mode 100644 index eefb987..0000000 --- a/src/main/java/cf/study/java8/javax/script/ScriptTest.java +++ /dev/null @@ -1,298 +0,0 @@ -package cf.study.java8.javax.script; - -import javax.script.Bindings; -import javax.script.Compilable; -import javax.script.CompiledScript; -import javax.script.Invocable; -import javax.script.ScriptContext; -import static javax.script.ScriptContext.*; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.SimpleBindings; -import javax.script.SimpleScriptContext; - -import junit.framework.Assert; -import misc.MiscUtils; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.apache.commons.lang3.time.StopWatch; -import org.junit.Test; - -public class ScriptTest { - @Test - public void testInvocable() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - - ScriptEngine se = sem.getEngineByExtension("js"); - - Object evaluated = se.eval(MiscUtils.loadResAsString(ScriptTest.class, "invocable.js")); - - System.out.println(ToStringBuilder.reflectionToString(evaluated, ToStringStyle.MULTI_LINE_STYLE)); - - Invocable inv = (Invocable) se; - - Runnable runnable = inv.getInterface(Runnable.class); - - System.out.println(runnable); - } - - @Test - public void testRunnable() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - - ScriptEngine se = sem.getEngineByExtension("js"); - - Object evaluated = se.eval(MiscUtils.loadResAsString(ScriptTest.class, "runnable.js")); - - System.out.println(ToStringBuilder.reflectionToString(evaluated, ToStringStyle.MULTI_LINE_STYLE)); - - Invocable inv = (Invocable) se; - - Runnable runnable = inv.getInterface(Runnable.class); - - System.out.println(runnable); - } - - @Test - public void testPreformance() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - ScriptEngine se = sem.getEngineByExtension("js"); - String loadResAsString = MiscUtils.loadResAsString(ScriptTest.class, "pref_sqrt.js"); - - System.out.println(se.eval(loadResAsString)); - } - - @Test - public void testCompilable() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - - ScriptEngine se = sem.getEngineByExtension("js"); - - Assert.assertTrue(se instanceof Compilable); - - Compilable cpl = (Compilable) se; - - String loadResAsString = MiscUtils.loadResAsString(ScriptTest.class, "pref.js"); - CompiledScript compiled = cpl.compile(loadResAsString); - - StopWatch sw = new StopWatch(); - - for (int t = 0; t < 5; t++) { - System.out.println(); - - sw.reset(); - sw.start(); - for (int i = 0; i < 1000; i++) { - compiled.eval(); - } - sw.stop(); - System.out.println("compiled: " + sw.getTime()); - - sw.reset(); - sw.start(); - for (int i = 0; i < 1000; i++) { - se.eval(loadResAsString); - } - sw.stop(); - System.out.println("eval: " + sw.getTime()); - - sw.reset(); - sw.start(); - for (int i = 0; i < 1000; i++) { - for (int _i = 0; _i < 1000; _i++) { - double re = Math.sqrt(_i); - } - } - sw.stop(); - System.out.println("native: " + sw.getTime()); - } - } - - @Test - public void testCompiledInDifferentScriptEngine() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - - CompiledScript compiled = null; - { - ScriptEngine se = sem.getEngineByExtension("js"); - Compilable cpl = (Compilable) se; - String loadResAsString = MiscUtils.loadResAsString(ScriptTest.class, "compiled.js"); - compiled = cpl.compile(loadResAsString); - } - - Assert.assertNotNull(compiled); - - { - ScriptEngine se = sem.getEngineByExtension("js"); - String loadResAsString = MiscUtils.loadResAsString(ScriptTest.class, "context.js"); - se.eval(loadResAsString); - compiled.eval(se.getContext()); - } - - { - ScriptEngine se = sem.getEngineByExtension("js"); - String loadResAsString = MiscUtils.loadResAsString(ScriptTest.class, "context_another.js"); - se.eval(loadResAsString); - compiled.eval(se.getContext()); - } - - // ScriptEngine se1 = sem.getEngineByExtension("js"); - // String loadResAsString1 = MiscUtils.loadResAsString(ScriptTest.class, - // "compiled.js"); - // CompiledScript compiled1 = cpl.compile(loadResAsString1); - // - // compiled1.eval(se.getContext()); - } - - @Test - public void testContextBetweenEngines() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - -// { -// ScriptContext sc = new SimpleScriptContext(); -// -// sc.getBindings(ScriptContext.GLOBAL_SCOPE); -// ScriptEngine jse = sem.getEngineByExtension("js"); -// jse.eval("this.shared = 'abc'", sc); -// -// ScriptEngine jse1 = sem.getEngineByExtension("js"); -// jse1.eval("print(this.shared)", jse.getContext()); -// } -// -// { -// ScriptEngine jse = sem.getEngineByExtension("js"); -// jse.eval("this.shared = 'abc'", sem.getBindings()); -// -// ScriptEngine jse1 = sem.getEngineByExtension("js"); -// jse1.eval("print(this.shared)", sem.getBindings()); -// } -// -// { -// ScriptEngine jse = sem.getEngineByExtension("js"); -// jse.eval("var shared = 'abc'"); -// -// ScriptEngine jse1 = sem.getEngineByExtension("js"); -// jse1.eval("print(this.shared)", jse.getContext()); -// -// ScriptEngine pse = sem.getEngineByExtension("py"); -// pse.eval("print(shared)", jse.getContext()); -// } - -// { -// ScriptContext sc = new SimpleScriptContext(); -// ScriptEngine jse = sem.getEngineByExtension("js"); -// jse.eval("this.shared = 'abc'", sc); -// -// sc.getBindings(ScriptContext.ENGINE_SCOPE).putAll(jse.getBindings(ScriptContext.ENGINE_SCOPE)); -// -// ScriptEngine jse1 = sem.getEngineByExtension("js"); -// jse1.eval("print(this.shared)", sc.getBindings(ScriptContext.ENGINE_SCOPE)); -// jse1.eval("print(this.shared)", jse.getBindings(ScriptContext.ENGINE_SCOPE)); -// jse1.eval("print(this.shared)", sc); -// -// -//// ScriptEngine pse = sem.getEngineByExtension("py"); -//// pse.eval("print(shared)", sc); -// } - -// { -// ScriptContext sc = new SimpleScriptContext(); -// sc.setBindings(new SimpleBindings(), ScriptContext.GLOBAL_SCOPE); -// -// Bindings gb = sc.getBindings(ScriptContext.GLOBAL_SCOPE); -// gb.put("bound", 123); -// -// ScriptEngine jse = sem.getEngineByExtension("js"); -// jse.eval("shared = 'abc'", sc); -// -//// bd.putAll(jse.getBindings(ScriptContext.ENGINE_SCOPE)); -// Bindings jseEngineBindings = jse.getBindings(ScriptContext.ENGINE_SCOPE); -// System.out.println(ToStringBuilder.reflectionToString(jseEngineBindings)); -// System.out.println(jseEngineBindings.keySet()); -// System.out.println(jseEngineBindings.values()); -// gb.putAll(jseEngineBindings); -// -// ScriptEngine jse1 = sem.getEngineByExtension("js"); -// jse1.eval("print(this.shared); print(bound);", sc); -// -// -//// ScriptEngine pse = sem.getEngineByExtension("py"); -//// pse.eval("print(shared)", sc); -// } - - - } - - @Test - public void testSharedBindingsBetweenEngines() throws Exception { - ScriptEngineManager sem = new ScriptEngineManager(); - - if (false) { - ScriptEngine jse = sem.getEngineByExtension("js"), jse1 = sem.getEngineByExtension("js"); - - Bindings bindings = new SimpleBindings(); - - bindings.put("bound", 123); - - jse.eval("shared = 'abc';", bindings); - - bindings.putAll(jse.getBindings(ENGINE_SCOPE)); - - jse1.eval("print(shared); print(bound);", bindings); - } - - { - ScriptEngine jse = sem.getEngineByExtension("js"), jse1 = sem.getEngineByExtension("js"); - - Bindings bindings = new SimpleBindings(); - - bindings.put("bound", 123); - - jse.eval("shared = 'abc';", bindings); - -// bindings.putAll(jse.getBindings(ENGINE_SCOPE)); - -// jse1.setBindings(jse.getBindings(ENGINE_SCOPE), ENGINE_SCOPE); - - jse1.eval("print(shared); print(bound);", jse.getContext()); - } - } - - @Test - public void example() throws Exception { - // Create a ScriptEngineManager that discovers all script engine - // factories (and their associated script engines) that are visible to - // the current thread's classloader. - - ScriptEngineManager manager = new ScriptEngineManager(); - - // Obtain a ScriptEngine that supports the JavaScript short name. - ScriptEngine engine = manager.getEngineByName("javascript"); - - // Initialize the color and shape script variables. - engine.put("color", "red"); - engine.put("shape", "rectangle"); - - // Evaluate a script that outputs the values of these variables. - engine.eval("print(color); print(shape);"); - - // Save the current bindings object. - Bindings oldBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); - - // Replace the bindings with a new bindings that overrides color and shape. - Bindings newBindings = engine.createBindings(); - newBindings.put("color", "blue"); - engine.setBindings(newBindings, ScriptContext.ENGINE_SCOPE); - engine.put("shape", "triangle"); - - // Evaluate the script. - engine.eval("print(color); print(shape);"); - - // Restore the original bindings. - engine.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE); - - // Evaluate the script. - engine.eval("print(color); print(shape);"); - } -} diff --git a/src/main/java/cf/study/java8/javax/script/compiled.js b/src/main/java/cf/study/java8/javax/script/compiled.js deleted file mode 100644 index f458293..0000000 --- a/src/main/java/cf/study/java8/javax/script/compiled.js +++ /dev/null @@ -1,9 +0,0 @@ -/** - * - */ - - -print(typeof(fooInContext)); -if (typeof(fooInContext) == 'function') { - print(fooInContext()); -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/context.js b/src/main/java/cf/study/java8/javax/script/context.js deleted file mode 100644 index 398f542..0000000 --- a/src/main/java/cf/study/java8/javax/script/context.js +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ - -function fooInContext() { - return "context.js.fooInContext"; -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/context_another.js b/src/main/java/cf/study/java8/javax/script/context_another.js deleted file mode 100644 index 1ebe7ca..0000000 --- a/src/main/java/cf/study/java8/javax/script/context_another.js +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ - -function fooInContext() { - return "context.another.js.fooInContext"; -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/invocable.js b/src/main/java/cf/study/java8/javax/script/invocable.js deleted file mode 100644 index 8bce842..0000000 --- a/src/main/java/cf/study/java8/javax/script/invocable.js +++ /dev/null @@ -1,3 +0,0 @@ -for (var i = 0; i < 100; i++) { - var re = Math.sqrt(i); -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/nashorn/NashornTests.java b/src/main/java/cf/study/java8/javax/script/javascript/nashorn/NashornTests.java deleted file mode 100644 index 217259d..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/nashorn/NashornTests.java +++ /dev/null @@ -1,378 +0,0 @@ -package cf.study.java8.javax.script.javascript.nashorn; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.junit.Test; - -public class NashornTests { - static ScriptEngineManager sem = new ScriptEngineManager(); - static final String NASHORN = "nashorn"; - - public static void prepare(ScriptEngine se) throws Exception { - se.eval("function inspect(obj) { " - + "print(typeof(obj) + ': \t' + obj); " - + "print('class: \t' + obj.class); " - + "print('prototype: \t' + obj.prototype); " - + "print('constructor: \t' + obj.constructor); " - + "print('json: \t' + JSON.stringify(obj)); " - + "print('length: \t' + obj.length); " - + "for (var p in obj) {print(p + ': \t' + obj[p]);} " - + "print();" - + "}"); - - } - - @Test - public void helloWorld() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - - se.eval("print('Hello, World!');"); - } - - @Test - public void whatIsPackages() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - final Object _packages = se.eval("Packages"); - - /* - * jdk.nashorn.api.scripting.ScriptObjectMirror@4d49af10[ - sobj=[JavaPackage ] - global=jdk.nashorn.internal.objects.Global@5e25a92e - strict=false - ] - */ - System.out.println(ToStringBuilder.reflectionToString(_packages, ToStringStyle.MULTI_LINE_STYLE)); - - - se.eval("print(typeof(Packages));"); - - //{"toJSON":{"toJSON":{"toJSON":{"toJSON":{"toJSON":{"toJSON":{"toJSON":{"toJSON":{}}}}}}}}} - se.eval("print(JSON.stringify(Packages));"); - - //toJSON: [object JavaPackage] - se.eval("for (var p in Packages) {print(p + ': ' + Packages[p]);}"); - } - - @Test - public void whatAreInPackages() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - System.out.println(ToStringBuilder.reflectionToString(se.eval("Packages.java.lang"), ToStringStyle.MULTI_LINE_STYLE)); - se.eval("inspect(Packages.java.lang);"); - } - - @Test - public void whatIsJava() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - System.out.println(ToStringBuilder.reflectionToString(se.eval("Packages.java.lang"), ToStringStyle.MULTI_LINE_STYLE)); - se.eval("inspect(Java)"); - } - - @Test - public void whatIsJavaClassLike() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("inspect(java.lang.System);"); - se.eval("inspect(java.lang.String);"); - se.eval("inspect(java.lang.Integer);"); - } - - @Test - public void whatIsJavaObjectLike() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("inspect(java.lang.System);"); - se.eval("inspect(java.lang.String);"); - se.eval("inspect(java.lang.Integer);"); - } - - @Test - public void createJavaObject() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("var Integer = Java.type('java.lang.Integer');inspect(new Integer(15));"); - se.eval("var Long = Java.type('java.lang.Long');inspect(new Long(15));"); - se.eval("var Short = Java.type('java.lang.Short');inspect(new Short(15));"); - se.eval("var Float = Java.type('java.lang.Float');inspect(new Float(15.51));"); - se.eval("var Double = Java.type('java.lang.Double');inspect(new Double(15.51));"); - - //String is converted into javascript string type - se.eval("var _String = Java.type('java.lang.String');inspect(new _String(\"Hello, String!\"));"); - } - - @Test - public void accessClassMembers() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - System.out.println("class member and methods\n"); - - se.eval("inspect(Java.type(\"java.lang.Math\").PI);"); - se.eval("inspect(Java.type(\"java.lang.System\").currentTimeMillis());"); - - System.out.println("inner class\n"); - se.eval("inspect(Java.type(\"java.util.Map\").Entry);"); - se.eval("inspect(Java.type(\"java.util.Map.Entry\"));"); - } - - public static class TestBean { - public int publicMember; - private int privateMember; - - public TestBean(int publicMember, int privateMember) { - super(); - this.publicMember = publicMember; - this.privateMember = privateMember; - System.out.println(this); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("{class:\"TestBean\", publicMember:'").append(publicMember).append("', privateMember:'").append(privateMember).append("'}"); - return builder.toString(); - } - - public TestBean() { - System.out.println(this); - } - - public int getPrivateMember() { - return privateMember; - } - - public void setPrivateMember(int _privateMember) { - System.out.println("setPrivateMember(" + _privateMember + ")"); - this.privateMember = _privateMember; - } - - public void setPrivateMember(double value) { - privateMember = (int) Math.ceil(value); - } - } - - @Test - public void accessInstanceMembers() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("Java.type(\"java.lang.System\").out.println('java.lang.System.out.println');"); - se.eval("Java.type(\"java.lang.System\").out.println(100);"); - se.eval("Java.type(\"java.lang.System\").out.println(100.001);"); - - se.eval("var TestBean = Java.type(\"cf.study.java8.javax.script.javascript.nashorn.NashornTests.TestBean\"); " - + "var _bean = new TestBean(), _bean1 = new TestBean(15, 20); " - + "inspect(_bean1);" - + "inspect(_bean1.publicMember);" - + "inspect(_bean1.privateMember);" - + "_bean1.publicMember = 16;" - + "print(_bean1);" - + "_bean1.publicMember++;" - + "print(_bean1); " - + "_bean1.privateMember = 24; " - + "print(_bean1); " - + "_bean1.setPrivateMember(25); " - + "print(_bean1); " - + "_bean1.privateMember--; " - + "print(_bean1); " - + "_bean1[\"setPrivateMember(double)\"](21.5); " - + "print(_bean1)"); - - } - - @Test - public void workWithJavaArrays() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("inspect(Java.type(\"int[]\"));"); - se.eval("inspect(Java.type(\"long[]\"));"); - se.eval("inspect(Java.type(\"float[]\"));"); - se.eval("inspect(Java.type(\"java.lang.String[]\"));"); - - se.eval("var IntArrayType = Java.type(\"int[]\");" - + "var iArr = new IntArrayType(10); " - + "inspect(iArr); " - + "iArr[1] = 123; " - + "iArr[2] = 321; " - + "print(iArr[1] + iArr[2]); "); - - se.eval("var jsArr = ['a', 'b', 'c']; " - + "inspect(jsArr); " - + "var StrArrType = Java.type('java.lang.String[]'); " - + "var javaStrArr = Java.to(jsArr, StrArrType); " - + "inspect(javaStrArr); " - + "\n " -// + "var _jsArr = Java.to(javaStrArr, Array); " //can't work reversely -// + "inspect(_jsArr); " - + " "); - - se.eval("for (var i = 0, j = iArr.length; i < j; i++) { " - + "print(i + ':\t' + iArr[i]); }"); - - se.eval("for (var i in iArr) { " - + "print(iArr[i]); }"); - - } - - @Test - public void workWithJavaString() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("var a = \"abc\"; " - + "inspect(a); " - + "var b = a + \"def\"; " - + "inspect(b); " - + "var c = String(b); " - + "inspect(c); "); - } - - @Test - public void workWithNumbers() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("var intNum = 10; " - + "inspect(intNum); " - + "var dblNum = Number(intNum); " - + "inspect(dblNum); "); - } - - @Test - public void workWithJavaCollections() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("var ArrayList = Java.type(\"java.util.ArrayList\"); " - + "var aList = new ArrayList(); " - + "inspect(aList); " - + "aList.add(\"a\"); " - //+ "aList.push(\"b\"); " //though the ArrayList is treated as Array in Javascript, but it doesn't have Javascript Array's methods like push..... - + "aList.add(\"c\"); " - + "print(aList[1]); " - + "for each (var e in aList) { " - + "print(e);} print(); "); - - se.eval("var HashSet = Java.type(\"java.util.HashSet\"); " - + "var _set = new HashSet(); " - + "_set.add(\"a\"); " - + "_set.add(\"b\"); " - + "_set.add(\"c\"); " - + "_set.add(\"a\"); " - + "print(_set[2]); " //though the Set is treated as Array in Javascript, but it doesn't have index like Array - + "inspect(_set); " - + "for (var i in _set) {print(i);} " - + "print(); " - + "for each (var i in _set) {print(i);} " - + "print(); " - + " "); - - se.eval("var HashMap = Java.type(\"java.util.HashMap\"); " - + "var _map = new HashMap(); " - + "_map.put(\"name\", \"fan\"); " - + "_map.put(\"height\", 1.75); " - + "_map.put(\"weight\", 80); " - + "print(_map[\"name\"]); " //This could work, but it isn't an Object - + "inspect(_map); "); // - } - - @Test - public void forInAndForEachIn() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval(" var arr = ['a', 'b', 'c', 'd', 'e']; " - + "for (var i in arr) {print(i);} " - + "print(); " - + "for each (var i in arr) {print(i);} " - + "print(); "); - - se.eval(" var point = {x: 100, y:200, z: 200}; " - + "for (var i in point) {print(i);} " - + "print(); " - + "for each (var i in point) {print(i);} "); - - } - - @Test - public void inheritance() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - Object obj = se.eval("var TestBean = Java.type(\"cf.study.java8.javax.script.javascript.nashorn.NashornTests.TestBean\"); \n " - + " var JsTestBean = Java.extend(TestBean, { " - + " jsObjMember : {}, " - + " jsNumMember : 17, " - + " jsArrMember : [], " - + " jsMethodCallSuper : function() { " - + " var _super_ = Java.super(this); " - + " print('super.getPrivateMember: \t' + _super_.getPrivateMember()); " - + " }, " - + " toString : function() {return JSON.stringify(this);}, " - + " jsMethodAccessSuper : function() {print('super.publicMember: \t' + this.publicMember);} " - + " }); \n " - + " inspect(JsTestBean); " - + " var jsTestBean = new JsTestBean(); \n " - //+ " print(typeof(jsTestBean.jsMethodCallSuper)); \n " //jsMethodCallSuper disappears! - + " jsTestBean.jsMethodCallSuper = function() { " - + " var _super_ = Java.super(this); " - + " print('super.getPrivateMember: \t' + _super_.getPrivateMember()); " - + " }; \n" - + " print(typeof(jsTestBean.jsMethodCallSuper)); " - //+ " print(\"super.getPrivateMember: \" + jsTestBean.jsMethodCallSuper()); \n " - + " inspect(jsTestBean); " - + " jsTestBean;"); - - System.out.println(obj); - System.out.println(obj.getClass()); - System.out.println((obj instanceof TestBean)); - } - - @Test - public void implementsInterface() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - // Create an object that implements the Runnable interface by implementing - // the run() method as a JavaScript function - se.eval("var r = new java.lang.Runnable() { " - + "run: function() { print('running...');} " - + "};"); - - // The r variable can be passed to Java methods that expect an object implementing - // the java.lang.Runnable interface - se.eval("var th = new java.lang.Thread(r); " - + " th.start(); " - + " th.join(); "); - - // Define a JavaScript function - se.eval("function func() {print(\"I am func!\");};"); - // Pass the JavaScript function instead of an object that implements - // the java.lang.Runnable interface - se.eval("var th = new java.lang.Thread(func); " - + " th.start(); " - + " th.join(); "); - } - - @Test - public void extendsAbstractClass() throws Exception { - ScriptEngine se = sem.getEngineByName(NASHORN); - prepare(se); - - se.eval("var TimerTask = Java.type(\"java.util.TimerTask\");"); - se.eval("var task = new TimerTask({ run: function() { print(\"Hello World!\") } });"); - se.eval("var Timer = Java.type(\"java.util.Timer\");"); - se.eval("var timer = new Timer();"); - se.eval("timer.schedule(task, 1);"); - - } - - -} diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/Foo.java b/src/main/java/cf/study/java8/javax/script/javascript/rhino/Foo.java deleted file mode 100644 index fd3ec24..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/Foo.java +++ /dev/null @@ -1,147 +0,0 @@ -package cf.study.java8.javax.script.javascript.rhino; - -import org.mozilla.javascript.Context; -import org.mozilla.javascript.Function; -import org.mozilla.javascript.Scriptable; -import org.mozilla.javascript.ScriptableObject; -import org.mozilla.javascript.annotations.JSFunction; -import org.mozilla.javascript.annotations.JSGetter; - -/** - * An example host object class. - * - * Here's a shell session showing the Foo object in action: - * - *
- * js> defineClass("Foo")
- * js> foo = new Foo();         A constructor call, see Foo below.
- * [object Foo]                 The "Foo" here comes from getClassName.
- * js> foo.counter;             The counter property is defined by the defineProperty
- * 0                            call below and implemented by the getCounter
- * js> foo.counter;             method below.
- * 1
- * js> foo.counter;
- * 2
- * js> foo.resetCounter();      Results in a call to resetCounter.
- * js> foo.counter;             Now the counter has been reset.
- * 0
- * js> foo.counter;
- * 1
- * js> bar = new Foo(37);       Create a new instance.
- * [object Foo]
- * js> bar.counter;             This instance's counter is distinct from
- * 37                           the other instance's counter.
- * js> foo.varargs(3, "hi");    Calls varargs.
- * this = [object Foo]; args = [3, hi]
- * js> foo[7] = 34;             Since we extended ScriptableObject, we get
- * 34                           all the behavior of a JavaScript object
- * js> foo.a = 23;              for free.
- * 23
- * js> foo.a + foo[7];
- * 57
- * js>
- * 
- * - * @see org.mozilla.javascript.Context - * @see org.mozilla.javascript.Scriptable - * @see org.mozilla.javascript.ScriptableObject - * - * @author Norris Boyd - */ - -public class Foo extends ScriptableObject { - private static final long serialVersionUID = -3833489808933339159L; - - /** - * The zero-parameter constructor. - * - * When Context.defineClass is called with this class, it will construct - * Foo.prototype using this constructor. - */ - public Foo() { - } - - /** - * The Java method defining the JavaScript Foo constructor. - * - * Takes an initial value for the counter property. Note that in the example - * Shell session above, we didn't supply a argument to the Foo constructor. - * This means that the Undefined value is used as the value of the argument, - * and when the argument is converted to an integer, Undefined becomes 0. - */ - public Foo(int counterStart) { - counter = counterStart; - } - - /** - * Returns the name of this JavaScript class, "Foo". - */ - @Override - public String getClassName() { - return "Foo"; - } - - /** - * The Java method defining the JavaScript resetCounter function. - * - * Resets the counter to 0. - */ - @JSFunction - public void resetCounter() { - counter = 0; - } - - /** - * The Java method implementing the getter for the counter property. - *

- * If "setCounter" had been defined in this class, the runtime would call - * the setter when the property is assigned to. - */ - @JSGetter - public int getCounter() { - return counter++; - } - - /** - * An example of a variable-arguments method. - * - * All variable arguments methods must have the same number and types of - * parameters, and must be static. - *

- * - * @param cx - * the Context of the current thread - * @param thisObj - * the JavaScript 'this' value. - * @param args - * the array of arguments for this call - * @param funObj - * the function object of the invoked JavaScript function This - * value is useful to compute a scope using - * Context.getTopLevelScope(). - * @return computes the string values and types of 'this' and of each of the - * supplied arguments and returns them in a string. - * - * @see org.mozilla.javascript.ScriptableObject#getTopLevelScope - */ - @JSFunction - public static Object varargs(Context cx, Scriptable thisObj, Object[] args, Function funObj) { - StringBuffer buf = new StringBuffer(); - buf.append("this = "); - buf.append(Context.toString(thisObj)); - buf.append("; args = ["); - for (int i = 0; i < args.length; i++) { - buf.append(Context.toString(args[i])); - if (i + 1 != args.length) - buf.append(", "); - } - buf.append("]"); - return buf.toString(); - } - - /** - * A piece of private data for this class. - */ - private int counter; - -} diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/JSTests.java b/src/main/java/cf/study/java8/javax/script/javascript/rhino/JSTests.java deleted file mode 100644 index 0fc1eb1..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/JSTests.java +++ /dev/null @@ -1,306 +0,0 @@ -package cf.study.java8.javax.script.javascript.rhino; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.mozilla.javascript.Context; -import org.mozilla.javascript.ContextFactory; -import org.mozilla.javascript.Function; -import org.mozilla.javascript.Script; -import org.mozilla.javascript.Scriptable; -import org.mozilla.javascript.ScriptableObject; -import org.mozilla.javascript.annotations.JSConstructor; -import org.mozilla.javascript.annotations.JSFunction; -import org.mozilla.javascript.annotations.JSGetter; - -public class JSTests { - - public static Logger log = Logger.getLogger(JSTests.class.getSimpleName()); - - private static final ScriptEngineManager sem = new ScriptEngineManager(); - - public static String getScript(final String fileName) { - try { - return IOUtils.toString(JSTests.class.getResourceAsStream(fileName)); - } catch (IOException e) { - log.log(Level.SEVERE, e.getMessage(), e); - } - return StringUtils.EMPTY; - } - - public static Object runScript(final String scriptStr) throws Exception { - final ScriptEngine se = sem.getEngineByName("Nashorn"); - return se.eval(scriptStr); - } - - @Test - public void control() throws Exception { - Context cx = Context.enter(); - - //Set version to Javascript1.2 so that we get object-literal style - // printing instead of "[object Object]" - cx.setLanguageVersion(Context.VERSION_1_2); - - //Initialize the standard objects (Object, Function, etc.) - //This must be done before scripts can be executed. - Scriptable scope = cx.initStandardObjects(); - - //Now we can evaluate a script. Let's create a new Object - //using the object literal notation - Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", "MySource", 1, null); - - Scriptable obj = (Scriptable) scope.get("obj", scope); - - // Should print "obj == result" (Since the result of an assignment - // expression is the value that was assigned - System.out.println(String.format("obj %s result", obj == result ? "==" : "!=")); - - // Should print "obj.a == 1" - System.out.println("obj.a == " + obj.get("a", obj)); - - Scriptable b = (Scriptable) obj.get("b", obj); - - //Should print "obj.b[0] == x" - System.out.println("obj.b[0] == " + b.get(0, b)); - - //Should print "obj.b[1] == y" - System.out.println("obj.b[1] == " + b.get(1, b)); - - // Should print {a:1, b:["x", "y"]} - Function fn = (Function) ScriptableObject.getProperty(obj, "toString"); - System.out.println(fn.call(cx, scope, obj, new Object[0])); - - Context.exit(); - } - - public static class Counter extends ScriptableObject { - private static final long serialVersionUID = 1L; - - @Override - public String getClassName() { - return Counter.class.getSimpleName(); - } - - // The zero-argument constructor used by Rhino runtimes to create instances - public Counter() {} - - //@JSConstructor annotation defines the JavaScript constructor - @JSConstructor - public Counter(int a) { count = a;} - - // The method getCount defines the count property - @JSGetter - public int getCount() { - return count++; - } - - // Methods can be defined the @JSFunction annotation. - // Here we define resetCount for JavaScript - @JSFunction - public void resetCount() { count = 0; } - - private int count; - } - - /** - * An example illustrating how to create a JavaScript object and retrieve - * properties and call methods. - *

- * Output should be: - *

-	 * count = 0
-	 * count = 1
-	 * resetCount
-	 * count = 0
-	 * 
- */ - @Test - public void counter() throws Exception { - Context cx = Context.enter(); - try { - Scriptable scope = cx.initStandardObjects(); - ScriptableObject.defineClass(scope, Counter.class); - - Scriptable testCounter = cx.newObject(scope, "Counter"); - - Object count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - - count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - - ScriptableObject.callMethod(testCounter, "resetCount", new Object[0]); - System.out.println("resetCount"); - - count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - } finally { - Context.exit(); - } - } - - public static class MyFactory extends ContextFactory { - public static boolean useDynamicScope; - protected boolean hasFeature(Context cx, int featureIndex) { - if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) { - return useDynamicScope; - } - return super.hasFeature(cx, featureIndex); - } - - static { - ContextFactory.initGlobal(new MyFactory()); - } - - public static void runScripts(Context cx, Script script) { - //Initialize the standard objects (Object, Function, etc.) - //This must be done before scripts can be executed. The call - //returns a new scope that we will share. - ScriptableObject sharedScope = cx.initStandardObjects(null, true); - - //Now we can execute the precompiled script against the scope - //to define x variable and f function in the shared scope - script.exec(cx, sharedScope); - - // Now we spawn some threads that execute a script that calls the - // function 'f'. The scope chain looks like this: - //
-	        //            ------------------                ------------------
-	        //           | per-thread scope | -prototype-> |   shared scope   |
-	        //            ------------------                ------------------
-	        //                    ^
-	        //                    |
-	        //               parentScope
-	        //                    |
-	        //            ------------------
-	        //           | f's activation   |
-	        //            ------------------
-	        // 
- // Both the shared scope and the per-thread scope have variables 'x' - // defined in them. If 'f' is compiled with dynamic scope enabled, - // the 'x' from the per-thread scope will be used. Otherwise, the 'x' - // from the shared scope will be used. The 'x' defined in 'g' (which - // calls 'f') should not be seen by 'f'. - final int threadCount = 3; - Thread[] t = new Thread[threadCount]; - String scriptStr = getScript("thread_scope.js"); - for (int i = 0; i < threadCount; i++) { - t[i] = new Thread(new PerThread(sharedScope, scriptStr, "thread" + i)); - } - - for (Thread _t : t) { - _t.start(); - } - - //Don't return in this thread until all the spawned threads have - //completed. - for (Thread _t : t) { - try { - _t.join(); - } catch (InterruptedException e) { - } - } - } - } - - /** - * Main entry point. - * - * Set up the shared scope and then spawn new threads that execute - * relative to that shared scope. Try to run functions with and - * without dynamic scope to see the effect. - * - * The expected output is - *
-    * sharedScope
-    * nested:sharedScope
-    * sharedScope
-    * nested:sharedScope
-    * sharedScope
-    * nested:sharedScope
-    * thread0
-    * nested:thread0
-    * thread1
-    * nested:thread1
-    * thread2
-    * nested:thread2
-    * 
- * The final three lines may be permuted in any order depending on - * thread scheduling. - */ - @Test - public void testDynamicScope() throws Exception { - Context cx = Context.enter(); - try { - //Precompile souce only once - String source = getScript("dynamic.js"); - Script script = cx.compileString(source, "sharedScript", 1, null); - - MyFactory.useDynamicScope = false; - MyFactory.runScripts(cx, script); - MyFactory.useDynamicScope = true; - MyFactory.runScripts(cx, script); - } finally { - Context.exit(); - } - } - - private static class PerThread implements Runnable { - - @Override - public void run() { - //We need a new Context for this thread. - Context cx = Context.enter(); - try { - //We can share the scope. - Scriptable threadScope = cx.newObject(sharedScope); - threadScope.setPrototype(sharedScope); - - // We want "threadScope" to be a new top-level - // scope, so set its parent scope to null. This means - // that any variables created by assignments - // will be properties of "threadScope" - threadScope.setParentScope(null); - - //Create a Javascript property of the thread scope named - //'x' and save a value for it. - threadScope.put("x", threadScope, x); - cx.evaluateString(threadScope, source, "threadScript", 1, null); - - } finally { - Context.exit(); - } - } - - private Scriptable sharedScope; - private String source; - private String x; - public PerThread(Scriptable sharedScope, String source, String x) { - super(); - this.sharedScope = sharedScope; - this.source = source; - this.x = x; - } - } - - @Test - public void fooTest() throws Exception { - JSTests.runScript(getScript("foo.js")); - } - - @Test - public void wrapFactoryTest() throws Exception { -// RhinoTests.runScript(getScript("wrap_factory.js")); - String scriptStr = getScript("wrap_factory.js"); - - final ScriptEngine se = sem.getEngineByName("Nashorn"); - se.eval(scriptStr); - } -} diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/Matrix.java b/src/main/java/cf/study/java8/javax/script/javascript/rhino/Matrix.java deleted file mode 100644 index 6768afd..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/Matrix.java +++ /dev/null @@ -1,253 +0,0 @@ -package cf.study.java8.javax.script.javascript.rhino; - -import org.mozilla.javascript.*; -import java.util.List; -import java.util.ArrayList; - -/** - * Matrix: An example host object class that implements the Scriptable - * interface. - * - * Built-in JavaScript arrays don't handle multiple dimensions gracefully: the - * script writer must create every array in an array of arrays. The Matrix class - * takes care of that by automatically allocating arrays for every index that is - * accessed. What's more, the Matrix constructor takes a integer argument that - * specifies the dimension of the Matrix. If m is a Matrix with dimension 3, - * then m[0] will be a Matrix with dimension 1, and m[0][0] will be an Array. - * - * Here's a shell session showing the Matrix object in action: - * - *
- * js> defineClass("Matrix")
- * js> var m = new Matrix(2); // A constructor call, see "Matrix(int dimension)"
- * js> m                      // Object.toString will call "Matrix.getClassName()"
- * [object Matrix]
- * js> m[0][0] = 3;
- * 3
- * js> uneval(m[0]);          // an array was created automatically!
- * [3]
- * js> uneval(m[1]);          // array is created even if we don't set a value
- * []
- * js> m.dim;                 // we can access the "dim" property
- * 2
- * js> m.dim = 3;
- * 3
- * js> m.dim;                 // but not modify the "dim" property
- * 2
- * 
- * - * @see org.mozilla.javascript.Context - * @see org.mozilla.javascript.Scriptable - * - * @author Norris Boyd - */ -public class Matrix implements Scriptable { - - /** - * The zero-parameter constructor. - * - * When ScriptableObject.defineClass is called with this class, it will - * construct Matrix.prototype using this constructor. - */ - public Matrix() { - } - - /** - * The Java constructor, also used to define the JavaScript constructor. - */ - public Matrix(int dimension) { - if (dimension <= 0) { - throw Context.reportRuntimeError("Dimension of Matrix must be greater than zero"); - } - dim = dimension; - list = new ArrayList(); - } - - /** - * Returns the name of this JavaScript class, "Matrix". - */ - public String getClassName() { - return "Matrix"; - } - - /** - * Defines the "dim" property by returning true if name is equal to "dim". - *

- * Defines no other properties, i.e., returns false for all other names. - * - * @param name - * the name of the property - * @param start - * the object where lookup began - */ - public boolean has(String name, Scriptable start) { - return name.equals("dim"); - } - - /** - * Defines all numeric properties by returning true. - * - * @param index - * the index of the property - * @param start - * the object where lookup began - */ - public boolean has(int index, Scriptable start) { - return true; - } - - /** - * Get the named property. - *

- * Handles the "dim" property and returns NOT_FOUND for all other names. - * - * @param name - * the property name - * @param start - * the object where the lookup began - */ - public Object get(String name, Scriptable start) { - if (name.equals("dim")) - return new Integer(dim); - - return NOT_FOUND; - } - - /** - * Get the indexed property. - *

- * Look up the element in the associated list and return it if it exists. If - * it doesn't exist, create it. - *

- * - * @param index - * the index of the integral property - * @param start - * the object where the lookup began - */ - public Object get(int index, Scriptable start) { - while (index >= list.size()) { - list.add(null); - } - Object result = list.get(index); - if (result != null) - return result; - if (dim > 2) { - Matrix m = new Matrix(dim - 1); - m.setParentScope(getParentScope()); - m.setPrototype(getPrototype()); - result = m; - } else { - Context cx = Context.getCurrentContext(); - Scriptable scope = ScriptableObject.getTopLevelScope(start); - result = cx.newArray(scope, 0); - } - list.set(index, result); - return result; - } - - /** - * Set a named property. - * - * We do nothing here, so all properties are effectively read-only. - */ - public void put(String name, Scriptable start, Object value) { - } - - /** - * Set an indexed property. - * - * We do nothing here, so all properties are effectively read-only. - */ - public void put(int index, Scriptable start, Object value) { - } - - /** - * Remove a named property. - * - * This method shouldn't even be called since we define all properties as - * PERMANENT. - */ - public void delete(String id) { - } - - /** - * Remove an indexed property. - * - * This method shouldn't even be called since we define all properties as - * PERMANENT. - */ - public void delete(int index) { - } - - /** - * Get prototype. - */ - public Scriptable getPrototype() { - return prototype; - } - - /** - * Set prototype. - */ - public void setPrototype(Scriptable prototype) { - this.prototype = prototype; - } - - /** - * Get parent. - */ - public Scriptable getParentScope() { - return parent; - } - - /** - * Set parent. - */ - public void setParentScope(Scriptable parent) { - this.parent = parent; - } - - /** - * Get properties. - * - * We return an empty array since we define all properties to be DONTENUM. - */ - public Object[] getIds() { - return new Object[0]; - } - - /** - * Default value. - * - * Use the convenience method from Context that takes care of calling - * toString, etc. - */ - public Object getDefaultValue(Class typeHint) { - return "[object Matrix]"; - } - - /** - * instanceof operator. - * - * We mimick the normal JavaScript instanceof semantics, returning true if - * this appears in value's prototype chain. - */ - public boolean hasInstance(Scriptable value) { - Scriptable proto = value.getPrototype(); - while (proto != null) { - if (proto.equals(this)) - return true; - proto = proto.getPrototype(); - } - - return false; - } - - /** - * Some private data for this class. - */ - private int dim; - private List list; - private Scriptable prototype, parent; -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/RhinoTests.java b/src/main/java/cf/study/java8/javax/script/javascript/rhino/RhinoTests.java deleted file mode 100644 index 2f2e327..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/RhinoTests.java +++ /dev/null @@ -1,320 +0,0 @@ -package cf.study.java8.javax.script.javascript.rhino; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.mozilla.javascript.Context; -import org.mozilla.javascript.ContextFactory; -import org.mozilla.javascript.Function; -import org.mozilla.javascript.Script; -import org.mozilla.javascript.Scriptable; -import org.mozilla.javascript.ScriptableObject; -import org.mozilla.javascript.WrapFactory; -import org.mozilla.javascript.annotations.JSConstructor; -import org.mozilla.javascript.annotations.JSFunction; -import org.mozilla.javascript.annotations.JSGetter; - -public class RhinoTests { - - public static Logger log = Logger.getLogger(RhinoTests.class.getSimpleName()); - - public static String getScript(final String fileName) { - try { - return IOUtils.toString(RhinoTests.class.getResourceAsStream(fileName)); - } catch (IOException e) { - log.log(Level.SEVERE, e.getMessage(), e); - } - return StringUtils.EMPTY; - } - - public static Object runScript(final String scriptStr) throws Exception { - Context cx = Context.enter(); - cx.setLanguageVersion(Context.VERSION_1_2); - try { - ScriptableObject sharedScope = cx.initStandardObjects(); - final Script script = cx.compileString(scriptStr, "", 1, null); - return script.exec(cx, sharedScope); - } finally { - Context.exit(); - } - } - - @Test - public void control() throws Exception { - Context cx = Context.enter(); - - //Set version to Javascript1.2 so that we get object-literal style - // printing instead of "[object Object]" - cx.setLanguageVersion(Context.VERSION_1_2); - - //Initialize the standard objects (Object, Function, etc.) - //This must be done before scripts can be executed. - Scriptable scope = cx.initStandardObjects(); - - //Now we can evaluate a script. Let's create a new Object - //using the object literal notation - Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", "MySource", 1, null); - - Scriptable obj = (Scriptable) scope.get("obj", scope); - - // Should print "obj == result" (Since the result of an assignment - // expression is the value that was assigned - System.out.println(String.format("obj %s result", obj == result ? "==" : "!=")); - - // Should print "obj.a == 1" - System.out.println("obj.a == " + obj.get("a", obj)); - - Scriptable b = (Scriptable) obj.get("b", obj); - - //Should print "obj.b[0] == x" - System.out.println("obj.b[0] == " + b.get(0, b)); - - //Should print "obj.b[1] == y" - System.out.println("obj.b[1] == " + b.get(1, b)); - - // Should print {a:1, b:["x", "y"]} - Function fn = (Function) ScriptableObject.getProperty(obj, "toString"); - System.out.println(fn.call(cx, scope, obj, new Object[0])); - - Context.exit(); - } - - public static class Counter extends ScriptableObject { - private static final long serialVersionUID = 1L; - - @Override - public String getClassName() { - return Counter.class.getSimpleName(); - } - - // The zero-argument constructor used by Rhino runtimes to create instances - public Counter() {} - - //@JSConstructor annotation defines the JavaScript constructor - @JSConstructor - public Counter(int a) { count = a;} - - // The method getCount defines the count property - @JSGetter - public int getCount() { - return count++; - } - - // Methods can be defined the @JSFunction annotation. - // Here we define resetCount for JavaScript - @JSFunction - public void resetCount() { count = 0; } - - private int count; - } - - /** - * An example illustrating how to create a JavaScript object and retrieve - * properties and call methods. - *

- * Output should be: - *

-	 * count = 0
-	 * count = 1
-	 * resetCount
-	 * count = 0
-	 * 
- */ - @Test - public void counter() throws Exception { - Context cx = Context.enter(); - try { - Scriptable scope = cx.initStandardObjects(); - ScriptableObject.defineClass(scope, Counter.class); - - Scriptable testCounter = cx.newObject(scope, "Counter"); - - Object count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - - count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - - ScriptableObject.callMethod(testCounter, "resetCount", new Object[0]); - System.out.println("resetCount"); - - count = ScriptableObject.getProperty(testCounter, "count"); - System.out.println("count = " + count); - } finally { - Context.exit(); - } - } - - public static class MyFactory extends ContextFactory { - public static boolean useDynamicScope; - protected boolean hasFeature(Context cx, int featureIndex) { - if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) { - return useDynamicScope; - } - return super.hasFeature(cx, featureIndex); - } - - static { - ContextFactory.initGlobal(new MyFactory()); - } - - public static void runScripts(Context cx, Script script) { - //Initialize the standard objects (Object, Function, etc.) - //This must be done before scripts can be executed. The call - //returns a new scope that we will share. - ScriptableObject sharedScope = cx.initStandardObjects(null, true); - - //Now we can execute the precompiled script against the scope - //to define x variable and f function in the shared scope - script.exec(cx, sharedScope); - - // Now we spawn some threads that execute a script that calls the - // function 'f'. The scope chain looks like this: - //
-	        //            ------------------                ------------------
-	        //           | per-thread scope | -prototype-> |   shared scope   |
-	        //            ------------------                ------------------
-	        //                    ^
-	        //                    |
-	        //               parentScope
-	        //                    |
-	        //            ------------------
-	        //           | f's activation   |
-	        //            ------------------
-	        // 
- // Both the shared scope and the per-thread scope have variables 'x' - // defined in them. If 'f' is compiled with dynamic scope enabled, - // the 'x' from the per-thread scope will be used. Otherwise, the 'x' - // from the shared scope will be used. The 'x' defined in 'g' (which - // calls 'f') should not be seen by 'f'. - final int threadCount = 3; - Thread[] t = new Thread[threadCount]; - String scriptStr = getScript("thread_scope.js"); - for (int i = 0; i < threadCount; i++) { - t[i] = new Thread(new PerThread(sharedScope, scriptStr, "thread" + i)); - } - - for (Thread _t : t) { - _t.start(); - } - - //Don't return in this thread until all the spawned threads have - //completed. - for (Thread _t : t) { - try { - _t.join(); - } catch (InterruptedException e) { - } - } - } - } - - /** - * Main entry point. - * - * Set up the shared scope and then spawn new threads that execute - * relative to that shared scope. Try to run functions with and - * without dynamic scope to see the effect. - * - * The expected output is - *
-    * sharedScope
-    * nested:sharedScope
-    * sharedScope
-    * nested:sharedScope
-    * sharedScope
-    * nested:sharedScope
-    * thread0
-    * nested:thread0
-    * thread1
-    * nested:thread1
-    * thread2
-    * nested:thread2
-    * 
- * The final three lines may be permuted in any order depending on - * thread scheduling. - */ - @Test - public void testDynamicScope() throws Exception { - Context cx = Context.enter(); - try { - //Precompile souce only once - String source = getScript("dynamic.js"); - Script script = cx.compileString(source, "sharedScript", 1, null); - - MyFactory.useDynamicScope = false; - MyFactory.runScripts(cx, script); - MyFactory.useDynamicScope = true; - MyFactory.runScripts(cx, script); - } finally { - Context.exit(); - } - } - - private static class PerThread implements Runnable { - - @Override - public void run() { - //We need a new Context for this thread. - Context cx = Context.enter(); - try { - //We can share the scope. - Scriptable threadScope = cx.newObject(sharedScope); - threadScope.setPrototype(sharedScope); - - // We want "threadScope" to be a new top-level - // scope, so set its parent scope to null. This means - // that any variables created by assignments - // will be properties of "threadScope" - threadScope.setParentScope(null); - - //Create a Javascript property of the thread scope named - //'x' and save a value for it. - threadScope.put("x", threadScope, x); - cx.evaluateString(threadScope, source, "threadScript", 1, null); - - } finally { - Context.exit(); - } - } - - private Scriptable sharedScope; - private String source; - private String x; - public PerThread(Scriptable sharedScope, String source, String x) { - super(); - this.sharedScope = sharedScope; - this.source = source; - this.x = x; - } - } - - @Test - public void fooTest() throws Exception { - RhinoTests.runScript(getScript("foo.js")); - } - - @Test - public void wrapFactoryTest() throws Exception { -// RhinoTests.runScript(getScript("wrap_factory.js")); - String scriptStr = getScript("wrap_factory.js"); - - Context cx = Context.enter(); - cx.setLanguageVersion(Context.VERSION_1_2); - - final WrapFactory wf = Context.getCurrentContext().getWrapFactory(); - System.out.println(wf.isJavaPrimitiveWrap()); - - try { - ScriptableObject sharedScope = cx.initStandardObjects(); - final Script script = cx.compileString(scriptStr, "", 1, null); - script.exec(cx, sharedScope); - } finally { - Context.exit(); - } - } -} diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/dynamic.js b/src/main/java/cf/study/java8/javax/script/javascript/rhino/dynamic.js deleted file mode 100644 index d15a82f..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/dynamic.js +++ /dev/null @@ -1,11 +0,0 @@ -var x = 'sharedScope'; -function f() { - return x; -} - -// Dynamic scope works with nested function too -function initClosure(prefix) { - return function test() {return prefix + x;}; -} - -var closure = initClosure('nested: '); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/foo.js b/src/main/java/cf/study/java8/javax/script/javascript/rhino/foo.js deleted file mode 100644 index 053e625..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/foo.js +++ /dev/null @@ -1,32 +0,0 @@ -//importClass(Packages.java.lang); - -function print(obj) { - java.lang.System.out.println(obj); -} - -print(this); - -defineClass("Foo"); - -var foo = new Foo(); -print(foo); -print(foo.counter); -print(foo.counter); -print(foo.counter); -print(foo.counter); -foo.resetCounter(); -print(foo.counter); -print(foo.counter); - -var bar = new Foo(37); -print(bar.counter); - -print(foo.varargs(3, "hi")); - -foo[7] = 43; -print(foo[7]); - -foo.a = 23; -print(foo.a); - -print(foo.a + foo[7]); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/test.js b/src/main/java/cf/study/java8/javax/script/javascript/rhino/test.js deleted file mode 100644 index 0ad9abe..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/test.js +++ /dev/null @@ -1,7 +0,0 @@ -print("warp_factory.js"); - -importPackage(java.lang); - -var j_str = new java.lang.String(); - -print(JSON.stringify(j_str)); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/thread_scope.js b/src/main/java/cf/study/java8/javax/script/javascript/rhino/thread_scope.js deleted file mode 100644 index ebe1a7b..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/thread_scope.js +++ /dev/null @@ -1,13 +0,0 @@ -function g() { - var x = 'local'; - return f(); -} - -java.lang.System.out.println(g()); - -function g2() { - var x = 'local'; - return closure(); -} - -java.lang.System.out.println(g2()); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/javascript/rhino/wrap_factory.js b/src/main/java/cf/study/java8/javax/script/javascript/rhino/wrap_factory.js deleted file mode 100644 index 5d2f26e..0000000 --- a/src/main/java/cf/study/java8/javax/script/javascript/rhino/wrap_factory.js +++ /dev/null @@ -1,7 +0,0 @@ -//print("warp_factory.js"); -// -//importPackage(java.lang); - -//var j_str = new java.lang.String(); - -print(JSON.stringify(new java.lang.Long(1))); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/pref.js b/src/main/java/cf/study/java8/javax/script/pref.js deleted file mode 100644 index d4623a1..0000000 --- a/src/main/java/cf/study/java8/javax/script/pref.js +++ /dev/null @@ -1,3 +0,0 @@ -for (var i = 0; i < 1000; i++) { - var re = Math.sqrt(i); -} diff --git a/src/main/java/cf/study/java8/javax/script/pref_sqrt.js b/src/main/java/cf/study/java8/javax/script/pref_sqrt.js deleted file mode 100644 index bee3331..0000000 --- a/src/main/java/cf/study/java8/javax/script/pref_sqrt.js +++ /dev/null @@ -1,12 +0,0 @@ -var System = java.lang.System; - -var now = System.currentTimeMillis(); -var then = now; - -var result = 0.0; -for (var i = 0; i < 1000000; i++) { - result += Math.sqrt(i); -} - -now = System.currentTimeMillis(); -print("after " + (now - then) + " ms " + result); \ No newline at end of file diff --git a/src/main/java/cf/study/java8/javax/script/runnable.js b/src/main/java/cf/study/java8/javax/script/runnable.js deleted file mode 100644 index f37b993..0000000 --- a/src/main/java/cf/study/java8/javax/script/runnable.js +++ /dev/null @@ -1,6 +0,0 @@ - -function run() { - for (var i = 0; i < 1000; i++) { - var re = Math.sqrt(i); - } -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/lang/ArrayTests.java b/src/main/java/cf/study/java8/lang/ArrayTests.java deleted file mode 100644 index 194c414..0000000 --- a/src/main/java/cf/study/java8/lang/ArrayTests.java +++ /dev/null @@ -1,21 +0,0 @@ -package cf.study.java8.lang; - -import java.lang.reflect.Array; - -import junit.framework.Assert; - -import org.junit.Test; - -public class ArrayTests { - - @Test - public void testArrayType() { - int[] intArray = new int[0]; - -// Assert.assertTrue((intArray instanceof Array)); - System.out.println(intArray.getClass()); - System.out.println(intArray.getClass().isArray()); -// Assert.assertTrue(Array.class.isInstance(intArray)); - - } -} diff --git a/src/main/java/cf/study/java8/lang/GenericTests.java b/src/main/java/cf/study/java8/lang/GenericTests.java deleted file mode 100644 index f447d3f..0000000 --- a/src/main/java/cf/study/java8/lang/GenericTests.java +++ /dev/null @@ -1,15 +0,0 @@ -package cf.study.java8.lang; - -import org.junit.Test; - -public class GenericTests { - public static class Holder { - T t; - } - - @Test - public void testTypeParam() { - Holder strHolder = new Holder(); - System.out.println(strHolder.getClass().getGenericSuperclass()); - } -} diff --git a/src/main/java/cf/study/java8/lang/LambdaTests.java b/src/main/java/cf/study/java8/lang/LambdaTests.java deleted file mode 100644 index f9e81c2..0000000 --- a/src/main/java/cf/study/java8/lang/LambdaTests.java +++ /dev/null @@ -1,169 +0,0 @@ -package cf.study.java8.lang; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.IntPredicate; -import java.util.function.Predicate; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.IntStream; - -import org.junit.Assert; -import org.junit.Test; - -public class LambdaTests { - - public static final Logger log = Logger.getLogger(LambdaTests.class.getSimpleName()); - - @Test - public void lambda() { - { - Runnable r = new Runnable() { - @Override - public void run() { - log.log(Level.INFO, "My Runnable"); - } - }; - new Thread(r).start(); - } - - { - Runnable r = () -> log.info("My lambda Runnable"); - new Thread(r).start(); - } - } - - /* - interface IObj {boolean equals(Object obj);} - //Not functional because equals is already an implicit member (Object class) - - interface Comparator { - boolean equals(Object obj); - int compare(T o1, T o2); - } - //Functional because comparator has only one abstract non-Object method - - interface Clonable { - int m(); - Object clone(); - } - //Not functional because method Object.clone is not public - - interface X { Iterable m(Iterable arg); } - interface Y { Iterable m(Iterable arg); } - interface Z extends X, Y {} - //Functional: Y.m is a subsignature & return-type-substituable - - interface X1 { int m(Iterable arg); } - interface Y1 { int m(Iterable arg); } - interface Z1 extends X1, Y1{} //names clash - //Not functional: No method has subsignature of all abstract methods - - interface X2 { int m(Iterable arg, Class c);} - interface Y2 { int m(Iterable arg, Class c); } - interface Z2 extends X2, Y2 {} //names clash - //Not functional: No method has a subsignature of all abstract methods - - interface X3 { long m(); } - interface Y3 { int m(); } - interface Z3 extends X3, Y3 {} - //Compiler error: no method is return type substitutable - - interface Foo { void m(T arg); } - interface Bar { void m(T arg); } - interface FooBar extends Foo, Bar {} - // Compiler error: different signatures, same erasure - */ - - private static boolean isPrime(int number) { - if (number < 2) return false; - for (int i = 2, j = Double.valueOf(Math.ceil(Math.sqrt(number))).intValue(); i < j; i++) { - if (number % i == 0) return false; - } - return true; - } - - private static boolean isPrime_(int number) { - return number > 1 - && IntStream.range(2, Double.valueOf(Math.ceil(Math.sqrt(number))).intValue()).noneMatch(i -> (number % i == 0)); - } - - @Test - public void testPrime() { - for (int i = 0; i < 100; i++) { - Assert.assertEquals(isPrime(i), isPrime_(i)); - } - - IntStream.range(1, 101).forEach((int i) -> {Assert.assertEquals(isPrime(i), isPrime_(i));}); - } - - @Test - public void testFactor() { - List i3s = new ArrayList(); - List i5s = new ArrayList(); - List i7s = new ArrayList(); - - IntStream.range(1, 101).forEach((int i) -> { - if (i % 3 == 0) { - i3s.add(i); - } else if (i % 5 == 0) { - i5s.add(i); - } else if (i % 7 == 0) { - i7s.add(i); - } - }); - - System.out.println("i % 3 == 0 " + i3s); - System.out.println("i % 5 == 0 " + i5s); - System.out.println("i % 7 == 0 " + i7s); - - List i3_5s = new ArrayList(); - - IntPredicate p3 = (int i) -> { - return i % 3 == 0; - }; - IntPredicate p3_5 = p3.and((int i) -> { - return i % 5 == 0; - }); - IntStream.range(1, 101).filter(p3_5).forEach((int i) -> i3_5s.add(i)); - - System.out.println("i % (5|3) == 0 " + i3_5s); - } - - public static int sumWithCond(List numbers, Predicate p) { - return numbers.parallelStream().filter(p).mapToInt(i -> i).sum(); - } - - @Test - public void testSumWithComd() { - List i100 = new ArrayList(); - IntStream.range(1, 101).forEach(i -> i100.add(i)); - - System.out.println(sumWithCond(i100, n -> true)); - System.out.println(sumWithCond(i100, n -> n % 2 == 0)); - System.out.println(sumWithCond(i100, n -> n > 5)); - } - - static class Opers { - public static boolean isOdd(int i) { - return i % 2 != 0; - } - public static boolean isGreaterThan3(int i) { - return i > 3; - } - public static boolean isLessThan11(int i) { - return i < 11; - } - } - - @Test - public void testStaticMethods() { - int sum = IntStream.range(1, 101) - .filter(Opers::isOdd) - .filter(Opers::isGreaterThan3) - .filter(Opers::isLessThan11) - .max() - .getAsInt(); - System.out.println(sum); - } -} diff --git a/src/main/java/cf/study/java8/lang/MathTests.java b/src/main/java/cf/study/java8/lang/MathTests.java deleted file mode 100644 index 0e22ec2..0000000 --- a/src/main/java/cf/study/java8/lang/MathTests.java +++ /dev/null @@ -1,11 +0,0 @@ -package cf.study.java8.lang; - -import org.junit.Test; - -public class MathTests { - @Test - public void testCeilAndFloor() { - System.out.println(Math.ceil(0.05)); - System.out.println(Math.floor(0.05)); - } -} diff --git a/src/main/java/cf/study/java8/lang/OperTests.java b/src/main/java/cf/study/java8/lang/OperTests.java deleted file mode 100644 index 7ea2f08..0000000 --- a/src/main/java/cf/study/java8/lang/OperTests.java +++ /dev/null @@ -1,55 +0,0 @@ -package cf.study.java8.lang; - -import org.junit.Assert; -import org.junit.Test; - -public class OperTests { - @Test - public void unary() { - int i = 5; - i = +5; - Assert.assertEquals(i, 5); - - i = +i; - Assert.assertEquals(i, 5); - - i = -i; - Assert.assertNotSame(i, 5); - } - - @Test - public void arithmetic() { -// int i = 1; -// System.out.println(i + i); -// System.out.println(i * i); -// System.out.println(i - i); -// System.out.println(i / i); -// -// System.out.println(i * (i + i)); -// System.out.println(i / (i + i)); -// System.out.println(i + (i + i)); -// System.out.println(i - (i + i)); -// -// System.out.println(i - +i); -// System.out.println(i + -i); -// System.out.println(i + ++ i); -// System.out.println(i + +(+ i)); - - int a = 0; - System.out.println(+a); - System.out.println(++a); - System.out.println(+ ++a); - } - - @Test - public void mod() { - System.out.println(6 % 4);//2 - System.out.println(-6 % 4);//-2 - System.out.println(6 % -4);//2 - System.out.println(-6 % -4);//-2 - System.out.println(0.6 % 0.4);//0.19999999999999996 - System.out.println(6 % 0.4);//0.3999999999999997 - System.out.println(0.4 % 0.6);//0.4 - } - -} diff --git a/src/main/java/cf/study/java8/lang/StringTests.java b/src/main/java/cf/study/java8/lang/StringTests.java deleted file mode 100644 index bdd4e71..0000000 --- a/src/main/java/cf/study/java8/lang/StringTests.java +++ /dev/null @@ -1,19 +0,0 @@ -package cf.study.java8.lang; - -import java.nio.charset.Charset; - -import org.junit.Test; - -public class StringTests { - - @Test - public void getAllCharsets() { - System.out.println(Charset.availableCharsets()); - } - - @Test - public void testEncoding() throws Exception { - String str = "abc"; - System.out.println(new String(str.getBytes(), "UTF-8")); - } -} diff --git a/src/main/java/cf/study/java8/lang/_enum/EnumTests.java b/src/main/java/cf/study/java8/lang/_enum/EnumTests.java deleted file mode 100644 index f84ad99..0000000 --- a/src/main/java/cf/study/java8/lang/_enum/EnumTests.java +++ /dev/null @@ -1,71 +0,0 @@ -package cf.study.java8.lang._enum; - -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import org.apache.commons.lang3.time.DateUtils; -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; - -public class EnumTests { - enum Direction { - south, north, east, west; - } - - @Test - public void testNotExistentEnum() { - System.out.println(Direction.valueOf("what")); - } - - @Test - public void testSwitchWithEnum() { - Direction d = Direction.south;// null; - switch (d) {//throw NullPointException for null value - case south: - System.out.println(Direction.south); - break; - case north: - System.out.println(Direction.north); - break; - case west: - System.out.println(Direction.west); - break; - case east: - System.out.println(Direction.east); - break; - default: - System.out.println(d); - break; - } - } - - public static interface IConverter { - T doConvert(S s, T t, Map ctx); - } - - public static interface IJsonParser extends IConverter { - String getName(); - } - - enum JsonDateParser implements IJsonParser { - YEAR { - public Date doConvert(JsonNode s, Date t, Map ctx) { - return DateUtils.setYears(t, s.get(getName()).asInt()); - } - }, - MONTH { - public Date doConvert(JsonNode s, Date t, Map ctx) { - return DateUtils.setMonths(t, s.get(getName()).asInt()); - } - }, - DATE { - public Date doConvert(JsonNode s, Date t, Map ctx) { - return DateUtils.setDays(t, s.get(getName()).asInt()); - } - }; - public String getName() {return this.name().toLowerCase();} - } - -} diff --git a/src/main/java/cf/study/java8/lang/annotation/AnnotationTests.java b/src/main/java/cf/study/java8/lang/annotation/AnnotationTests.java deleted file mode 100644 index cd251a4..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/AnnotationTests.java +++ /dev/null @@ -1,93 +0,0 @@ -package cf.study.java8.lang.annotation; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.Arrays; -import java.util.stream.Stream; - -import org.junit.Assert; -import org.junit.Test; - -import cf.study.java8.lang.annotation.test.Dummy; - - -public class AnnotationTests { - - @Test - public void inheiredAnnotation() { - Shape s = new Shape(); - { - final TypeAnnotation at = s.getClass().getAnnotation(TypeAnnotation.class); - System.out.println(at); - - final TypeAnnotation[] ats = s.getClass().getAnnotationsByType(TypeAnnotation.class); - System.out.println(Arrays.toString(ats)); - System.out.println(); - } - - - Shape r = new Rectangle(); - { - final TypeAnnotation at = r.getClass().getAnnotation(TypeAnnotation.class); - System.out.println(at); - - final TypeAnnotation[] ats = r.getClass().getAnnotationsByType(TypeAnnotation.class); - System.out.println(Arrays.toString(ats)); - System.out.println(); - } - - Shape p = new Point(); - { - final TypeAnnotation at = p.getClass().getAnnotation(TypeAnnotation.class); - System.out.println(at); - - final TypeAnnotation[] ats = p.getClass().getAnnotationsByType(TypeAnnotation.class); - System.out.println(Arrays.toString(ats)); - System.out.println(); - } - } - - /** - * Can't get LOCAL_VARIABLE annotation by reflection in runtime - */ - @Test - public void testLocalVariable() { - @Creator(id=5, who=TYPE_NAME) - Shape r = new Rectangle(); - - final Creator at = r.getClass().getAnnotation(Creator.class); - System.out.println(at); - } - - @Test - public void testMethodAnnotation() throws Exception { - final Method md = Rectangle.class.getMethod("draw"); - Assert.assertNotNull(md); - final MethodAt mdAt = md.getAnnotation(MethodAt.class); - System.out.println(mdAt); - } - - @Test - public void testFieldAnnotation() throws Exception { - final Field fd = Rectangle.class.getField("start"); - Assert.assertNotNull(fd); - final FieldAt fieldAt = fd.getAnnotation(FieldAt.class); - System.out.println(fieldAt); - } - - @Test - public void testParamAnnotation() throws Exception { - final Method md = Rectangle.class.getMethod("draw", IDrawable.class); - Assert.assertNotNull(md); - Stream.of(md.getParameters()).forEach((Parameter param)->{System.out.println(param.getAnnotation(ParamAt.class));}); - } - - @Test - public void testPackageAnnotation() { - final PackageAt at = Dummy.class.getAnnotation(PackageAt.class); - System.out.println(at); - } - - public static final String TYPE_NAME = "cf.study.java8.lang.annotation.AnnotationTests"; -} diff --git a/src/main/java/cf/study/java8/lang/annotation/PackageAt.java b/src/main/java/cf/study/java8/lang/annotation/PackageAt.java deleted file mode 100644 index e4c20f7..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/PackageAt.java +++ /dev/null @@ -1,12 +0,0 @@ -package cf.study.java8.lang.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.PACKAGE}) -public @interface PackageAt { - -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/lang/annotation/Shape.java b/src/main/java/cf/study/java8/lang/annotation/Shape.java deleted file mode 100644 index 8cbaf73..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/Shape.java +++ /dev/null @@ -1,70 +0,0 @@ -package cf.study.java8.lang.annotation; - -@TypeAnnotation(typeName = Shape.TYPE_NAME, id = 0) -class Shape { - public static final int TYPE_ID = Shape.class.hashCode(); - public static final String TYPE_NAME = "Shape"; - - @MethodAt(caller = TYPE_NAME) - public Shape draw() { - return this; - } -} - -class Rectangle extends Shape { - public static final String TYPE_NAME = "Rectangle"; - - @FieldAt(definedBy=TYPE_NAME) - public Point2D start; - - @MethodAt(caller = TYPE_NAME) - public Shape draw() { - return this; - } - - @MethodAt(caller = TYPE_NAME) - public Shape draw(@ParamAt(definedBy=TYPE_NAME) IDrawable canvas) { - canvas.doDraw(this); - return this; - } - - public Rectangle(Point2D start) { - super(); - this.start = start; - } - - public Rectangle() { - start = new Point2D(); - } -} - -interface IDrawable { - IDrawable doDraw(Shape shape); -} - -@TypeAnnotation(typeName = Point.TYPE_NAME, id = 1) -class Point extends Shape { - public static final int TYPE_ID = Point.class.hashCode(); - public static final String TYPE_NAME = "Point"; - - @MethodAt(caller = TYPE_NAME) - public Point draw() { - return this; - } - -} - -class Point2D extends Point { - public static final int TYPE_ID = Point2D.class.hashCode(); - public static final String TYPE_NAME = "Point2D"; - - public int x = 0, y = 0; - - public Point2D(int x, int y) { - super(); - this.x = x; - this.y = y; - } - - public Point2D() {} -} diff --git a/src/main/java/cf/study/java8/lang/annotation/TypeAnnotation.java b/src/main/java/cf/study/java8/lang/annotation/TypeAnnotation.java deleted file mode 100644 index ef7ba10..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/TypeAnnotation.java +++ /dev/null @@ -1,53 +0,0 @@ -package cf.study.java8.lang.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface TypeAnnotation { - int id() default -1;; - String typeName() default "invalid_type"; -} - - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.LOCAL_VARIABLE}) -@interface DefinedBy { - int id(); - String who(); -} - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.LOCAL_VARIABLE}) -@interface Creator { - int id(); - String who(); -} - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Inherited -@interface MethodAt { - String caller(); -} - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -@Inherited -@interface FieldAt { - String definedBy(); -} - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.PARAMETER}) -@Inherited -@interface ParamAt { - String definedBy(); -} - - diff --git a/src/main/java/cf/study/java8/lang/annotation/test/Dummy.java b/src/main/java/cf/study/java8/lang/annotation/test/Dummy.java deleted file mode 100644 index 0671a1a..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/test/Dummy.java +++ /dev/null @@ -1,5 +0,0 @@ -package cf.study.java8.lang.annotation.test; - -public class Dummy { - -} diff --git a/src/main/java/cf/study/java8/lang/annotation/test/package-info.java b/src/main/java/cf/study/java8/lang/annotation/test/package-info.java deleted file mode 100644 index 9d6f9f6..0000000 --- a/src/main/java/cf/study/java8/lang/annotation/test/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/* - * for something like ASM, or ByteCode motification - * */ -@cf.study.java8.lang.annotation.PackageAt -package cf.study.java8.lang.annotation.test; \ No newline at end of file diff --git a/src/main/java/cf/study/java8/lang/keywords/InstanceofTests.java b/src/main/java/cf/study/java8/lang/keywords/InstanceofTests.java deleted file mode 100644 index ff1376f..0000000 --- a/src/main/java/cf/study/java8/lang/keywords/InstanceofTests.java +++ /dev/null @@ -1,77 +0,0 @@ -package cf.study.java8.lang.keywords; - -import java.io.Serializable; - -import org.junit.Assert; -import org.junit.Test; - -public class InstanceofTests { - @Test - public void testInstanceof_1() { - final Integer _int = Integer.valueOf(1); - - Assert.assertTrue(_int instanceof Integer); - Assert.assertTrue(_int instanceof Number); - Assert.assertTrue(_int instanceof Object); - Assert.assertTrue(_int instanceof Serializable); - Assert.assertTrue(_int instanceof Comparable); -// Assert.assertTrue(1 instanceof Integer); // compile error - - Assert.assertTrue((Integer)1 instanceof Integer); - - Assert.assertFalse(null instanceof Integer); - } - - @Test - public void testInstanceof_2() { - Cls_1 obj_1 = new Cls_1(); - Cls_1 obj_null = null; - Inf_1 inf_1 = obj_1; - - Assert.assertTrue(obj_1 instanceof Cls_1); - Assert.assertTrue(obj_1 instanceof Inf_1); - - Assert.assertFalse(obj_null instanceof Cls_1); - Assert.assertFalse(obj_null instanceof Inf_1); - - Assert.assertTrue(inf_1 instanceof Cls_1); - Assert.assertTrue(inf_1 instanceof Inf_1); - - Cls_2 obj_2 = new Cls_2(); - Cls_2 obj_2_null = null; - Inf_2 inf_2 = obj_2; - - Assert.assertTrue(obj_2 instanceof Cls_2); - Assert.assertTrue(obj_2 instanceof Inf_2); - - Assert.assertFalse(obj_2_null instanceof Cls_2); - Assert.assertFalse(obj_2_null instanceof Inf_2); - - Assert.assertTrue(inf_2 instanceof Cls_2); - Assert.assertTrue(inf_2 instanceof Inf_2); - - Cls_1_2 obj_1_2 = new Cls_1_2(); - Assert.assertTrue(obj_1_2 instanceof Inf_1); - Assert.assertTrue(obj_1_2 instanceof Inf_2); - Assert.assertFalse(obj_1_2 instanceof Inf_12); - - Cls_12 obj_12 = new Cls_12(); - Assert.assertTrue(obj_12 instanceof Inf_1); - Assert.assertTrue(obj_12 instanceof Inf_2); - Assert.assertTrue(obj_12 instanceof Inf_12); - - } - - -} - -interface Inf_1 {} -interface Inf_2 {} - -interface Inf_12 extends Inf_1, Inf_2 {} - -class Cls_1 implements Inf_1 {} -class Cls_2 implements Inf_2 {} - -class Cls_1_2 implements Inf_1, Inf_2 {} -class Cls_12 implements Inf_12 {} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/lang/keywords/KeyWordTests.java b/src/main/java/cf/study/java8/lang/keywords/KeyWordTests.java deleted file mode 100644 index bd18299..0000000 --- a/src/main/java/cf/study/java8/lang/keywords/KeyWordTests.java +++ /dev/null @@ -1,497 +0,0 @@ -package cf.study.java8.lang.keywords; - -import org.junit.Test; - -public class KeyWordTests { - public static final String[] KEY_WORDS = { - "abstract", //checked - "assert", //checked - "boolean", - "break", //checked - "byte", - "case", //checked - "catch", - "char", - "class", - "const", //checked - "continue", - "default", //checked - "do", - "double", - "else", //checked - "enum", - "extends", - "final", - "finally", - "float", - "for", - "goto", - "if", //checked - "implements", - "import", //checked - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "package", //checked - "private", - "protected", - "public", - "return", - "short", - "static", - "strictfp", - "super", - "switch", //checked - "synchronized", - "this", - "throw", - "throws ", - "transient", - "try", - "void", - "volatile", - "while" - }; - - - - @Test - public void testIfAndElse() { - if (true) {System.out.println(true);} - if (false) {System.out.println(false);} - - if (true) - if (false) - System.out.println(false); - else if (true) - System.out.println(true); - else if (false); - else; - } - - @Test - public void testAssert() { - assert true; - System.out.println("assert true"); - assert false; // run java with "-ea", this throws AssertError - System.out.println("assert false"); - } - - @Test - public void testBreak() { -// break; break can't be used outside of loop or switch - for (int i = 0; i < 1; i++) {break;} - do {break;} while(true); - while(true) {break;} - - switch (1) { - case 1: - break; - default: - break; - } - - _outer: for (int i = 0; i < 3; i++) { - System.out.println("outer begins: " + i); - for (int j = 0; j < i; j++) { - System.out.println("\t" + j); - break _outer; //jump out of outer loop too - } - System.out.println("outer ends: " + i); - } - } - - @Test - public void testCaseAndSwitchAndDefaultAndBreakAndContinueAndLabel() { - // case; error - // case true; - switch (5) { - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - default: - System.out.println("default:"); - break; - } - -// testDefaultInSwitch(); - - System.out.println(); - { - int i = 5; - _1: switch (i) { - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - i = 1; - break _1; - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - i = 0; - default: - System.out.println("default: i = " + i); - break; - } - - System.out.println("i = " + i); - } - - System.out.println(); - { - int i = 5; - _1: switch (i) { - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - i = 1; -// continue _1; continue can't be used outside of loop -// for() {continue _1}; no statement between label and outer loop - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - i = 0; - default: - System.out.println("default: i = " + i); - break; - } - - System.out.println("i = " + i); - } - - System.out.println(); - { - int i = -1; - _1: switch (i) { - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - i = 1; -// break _1; -// continue _1; continue can't be used outside of loop -// for() {continue _1}; no statement between label and outer loop - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - i = 0; - default: - i = 2; - System.out.println("default: i = " + i); - break _1; - } - - System.out.println("i = " + i); - } - - } - - @Test - public void testDefaultInSwitch() { - System.out.println(); - switch (5) { - default: - System.out.println("default:"); -// break; - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - } - - System.out.println(); - switch (5) { -// break; - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - default: - System.out.println("default:"); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - } - - System.out.println(); - switch (-1) { - default: - System.out.println("default:"); -// break; - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - case 6: - System.out.println(6); - case 7: - System.out.println(7); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - } - - System.out.println(); - switch (-1) { -// break; - case 1: - System.out.println(1); - case 2: - System.out.println(2); - case 3: - System.out.println(3); - case 4: - System.out.println(4); - case 5: - System.out.println(5); - case 6: - System.out.println(6); - case 7: - System.out.println(7); - default: - System.out.println("default:"); - case 8: - System.out.println(8); - case 9: - System.out.println(9); - case 0: - System.out.println(10); - } - } - - @Test - public void testSwitchWithVariable() { - System.out.println(); - int i = 3; - switch (i) { -// break; - case 1: - System.out.println(1 + " var :" + i); - case 2: - System.out.println(2 + " var :" + i); - case 3: - System.out.println(3 + " var :" + i); - case 4: - System.out.println(4 + " var :" + i); - case 5: - System.out.println(5 + " var :" + i); - i = -1; //continue execution - case 6: - System.out.println(6 + " var :" + i); - case 7: - System.out.println(7 + " var :" + i); - case 8: - System.out.println(8 + " var :" + i); - case 9: - System.out.println(9 + " var :" + i); - case 0: - System.out.println(0 + " var :" + i); - default: - System.out.println("default:"); - } - } - - @Test - public void testSwitchWithStr() { - System.out.println(); - { - final String _str = "i"; //constant literal - final String _random = String.valueOf(System.currentTimeMillis()); //non constant expression - String str = "d"; - switch (str) { - case "a": - System.out.println("a"); - break; - case "b": - System.out.println("b"); - break; - case "c": - System.out.println("c"); - break; - case "d": - System.out.println("d"); - break; - case "e": - System.out.println("e"); - break; - case "f": - System.out.println("f"); - break; - case "g": - System.out.println("g"); - break; - case "h": - System.out.println("h"); - break; - case _str: //constant expression can be "case" - System.out.println(_str); - break; -// case _random: //constant expression can be "case" -// System.out.println(_random); -// break; - default: - System.out.println("default: str = " + str); - break; - } - } - } - - @Test - public void testSwitchWithNull() { - System.out.println(); - { - final String _str = "i"; //constant literal - final String _random = String.valueOf(System.currentTimeMillis()); //non constant expression - String str = "d"; //null; //switch will throw NullPointerException for null value -// switch (null) { can't take null literal - switch (str) { - case "a": - System.out.println("a"); - break; - case "b": - System.out.println("b"); - break; -// case null: doesn't accept null as case expression - case "c": - System.out.println("c"); - break; - case "d": - System.out.println("d"); - break; - case "e": - System.out.println("e"); - break; - case "f": - System.out.println("f"); - break; - case "g": - System.out.println("g"); - break; - case "h": - System.out.println("h"); - break; - case _str: //constant expression can be "case", except null - System.out.println(_str); - break; -// case _random: //constant expression can be "case" -// System.out.println(_random); -// break; - default: - System.out.println("default: str = " + str); - break; - } - } - } - - -// const String _str = "i"; no use of const -} -//abstract, class -abstract class Abstract { - abstract void method(); -// abstract Object obj; -} - -abstract interface AbstractInterface { - abstract void method(); - void foo(); -} \ No newline at end of file diff --git a/src/main/java/cf/study/java8/lang/number/NumberTests.java b/src/main/java/cf/study/java8/lang/number/NumberTests.java deleted file mode 100644 index 6fc7109..0000000 --- a/src/main/java/cf/study/java8/lang/number/NumberTests.java +++ /dev/null @@ -1,99 +0,0 @@ -package cf.study.java8.lang.number; - - -import static misc.MiscUtils.toBinStr; - -import org.junit.Test; - -public class NumberTests { - - @Test - public void testMod() { - System.out.println(-3 % 2); //-1 - System.out.println(3 % -2); //1 - } - - @Test - public void testNaN() { - System.out.println(Float.NaN); - System.out.println(0.0f / 0.0f); - Float v = 0.0f / 0.0f; - System.out.println(v == Float.NaN); - System.out.println(Float.isNaN(v)); - } - - @Test - public void testInfinitive() { - System.out.println(Float.POSITIVE_INFINITY); - } - - @Test - public void testMax() { - System.out.println(Integer.MAX_VALUE); - System.out.println(-Integer.MAX_VALUE); - System.out.println(Integer.MAX_VALUE + (-Integer.MAX_VALUE)); - - System.out.println(Long.MAX_VALUE); - System.out.println(-Long.MAX_VALUE); - System.out.println(Long.MAX_VALUE + (-Long.MAX_VALUE)); - } - - - @Test - public void testMaxAndMin() { - System.out.println(Integer.MAX_VALUE); - System.out.println(Integer.MIN_VALUE); - System.out.println(Integer.MAX_VALUE + Integer.MIN_VALUE); - - System.out.println(Long.MAX_VALUE); - System.out.println(Long.MIN_VALUE); - System.out.println(Long.MAX_VALUE + Long.MIN_VALUE); - } - - @Test - public void testBinary() { - byte _b = 1; - short _s = 1; - int _i = 1; - long _l = 1; - System.out.println(toBinStr(_b)); - System.out.println(toBinStr(_b >> 1)); - System.out.println(toBinStr((byte)_b >> 1)); - System.out.println(toBinStr((byte)(_b >> 1))); - - //every number operation between byte, short, integer, produces result in integer - System.out.println(); - System.out.println("every number operation between byte, short, integer, produces result in integer"); - System.out.println(toBinStr(_b + _b)); - System.out.println(toBinStr(_b + _s)); - System.out.println(toBinStr(_b + _i)); - System.out.println(toBinStr(_s + _i)); - System.out.println(toBinStr((byte)(_b + _b))); - - //every number operation between byte, short, integer, involving long, produces result in long - System.out.println(); - System.out.println("every number operation between byte, short, integer, produces result in long"); - System.out.println(toBinStr(_b + _l)); - System.out.println(toBinStr(_i + _l)); - System.out.println(toBinStr(_b + _l)); - System.out.println(toBinStr(_l + _l)); - System.out.println(toBinStr((byte)(_l + _l))); - - System.out.println(); - System.out.println("two's compelment"); - System.out.println(toBinStr((byte)-_b)); - System.out.println(toBinStr((byte)-(_b+_b))); - System.out.println(toBinStr(-_l)); -// System.out.println(toBinStr((byte)-_b)); - - System.out.println(); - System.out.println("bit order in java is big endian"); - System.out.println(toBinStr((byte)16)); - - System.out.println(); - System.out.println(Byte.MAX_VALUE + " = " + toBinStr(Byte.MAX_VALUE)); - System.out.println(Byte.MIN_VALUE + " = " + toBinStr(Byte.MIN_VALUE)); - System.out.println(((byte)-1)); - System.out.println(((byte)-1) & Byte.MAX_VALUE); - } -} diff --git a/src/main/java/cf/study/java8/lang/reflect/ClassLoaderTest.java b/src/main/java/cf/study/java8/lang/reflect/ClassLoaderTest.java deleted file mode 100644 index 214fcc4..0000000 --- a/src/main/java/cf/study/java8/lang/reflect/ClassLoaderTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package cf.study.java8.lang.reflect; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Stream; - - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Assert; -import org.junit.Test; - -public class ClassLoaderTest { - @Test - public void loadClassesFromRuntimeJar() throws Exception { - File _f = new File(String.format("%s/lib/rt.jar", SystemUtils.JAVA_HOME)); - - Assert.assertTrue(_f.exists()); - Assert.assertTrue(_f.isFile()); - - ClassLoader cl = ClassLoader.getSystemClassLoader(); - - List> clsList = new LinkedList>(); - try (JarFile jf = new JarFile(_f)) { - System.out.println(String.format("entries: %d", jf.size())); - - try (Stream entryStream = jf.stream()) { - entryStream.parallel().map((je) -> { - try { - return cl.loadClass(StringUtils.removeEnd(je.getName().replace('/', '.'), ".class")); - } catch (Exception e) { - System.err.println(e.getMessage()); - } - return null; - }).forEach((cls) -> { - if (cls != null) { - clsList.add(cls); - } - }); - - } - } - - System.out.println(clsList.size()); - } -} diff --git a/src/main/java/cf/study/java8/lang/reflect/Reflects.java b/src/main/java/cf/study/java8/lang/reflect/Reflects.java deleted file mode 100644 index cf2113e..0000000 --- a/src/main/java/cf/study/java8/lang/reflect/Reflects.java +++ /dev/null @@ -1,72 +0,0 @@ -package cf.study.java8.lang.reflect; - -import java.io.File; -import java.net.URL; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Stream; - -import junit.framework.Assert; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.SystemUtils; -import org.apache.xbean.classloader.JarFileClassLoader; -import org.junit.Test; - -public class Reflects { - - public static List> loadClzzFromJar(File jarFile, ClassLoader defaultLoader) throws Exception { - List> clsList = new LinkedList>(); - if (jarFile == null || !jarFile.exists() || !jarFile.isFile() || !jarFile.canRead()) { - return clsList; - } - - JarFileClassLoader cl = new JarFileClassLoader("jfcl", new URL[] { jarFile.toURI().toURL() }, defaultLoader); - - try { - try (JarFile jf = new JarFile(jarFile)) { - System.out.println(String.format("entries: %d", jf.size())); - - try (Stream entryStream = jf.stream()) { - entryStream.filter((je) -> { - return !je.isDirectory(); - }).map((je) -> { - String clsName = StringUtils.removeEnd(je.getName().replace('/', '.'), ".class"); - try { - return cl.loadClass(clsName); - } catch (Exception e) { - System.err.println(clsName + e.getMessage()); - } - return null; - }).forEach((cls) -> { - if (cls != null) { - clsList.add(cls); - } - }); - - } - } - } finally { - cl.close(); - } - - return clsList; - } - - @Test - public void test() throws Exception { - String[] classPaths = StringUtils.split(SystemUtils.JAVA_CLASS_PATH, ';'); - - Optional opt = Stream.of(classPaths).filter((String str) -> { - return str.contains("junit"); - }).findFirst(); - Assert.assertTrue(opt.isPresent()); - - List> re = loadClzzFromJar(new File(opt.get()), ClassLoader.getSystemClassLoader()); - System.out.println(StringUtils.join(re, '\n')); - System.out.println(re.size()); - } -} diff --git a/src/main/java/cf/study/java8/nio/PathsTest.java b/src/main/java/cf/study/java8/nio/PathsTest.java deleted file mode 100644 index e756777..0000000 --- a/src/main/java/cf/study/java8/nio/PathsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package cf.study.java8.nio; - -import java.net.URI; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Test; - -public class PathsTest { - - @Test - public void testPaths() { - Path p = Paths.get("folder1", "folder2"); - System.out.println(p); - - p = Paths.get("folder1/", "folder2"); - System.out.println(p); - - p = Paths.get("folder1", "/folder2"); - System.out.println(p); - - p = Paths.get("folder1/", "/folder2"); - System.out.println(p); - - URI uri = URI.create("folder1"); - System.out.println(uri); - } -} diff --git a/src/main/java/cf/study/java8/nio/WatchTest.java b/src/main/java/cf/study/java8/nio/WatchTest.java deleted file mode 100644 index f7f78d7..0000000 --- a/src/main/java/cf/study/java8/nio/WatchTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package cf.study.java8.nio; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import static java.nio.file.StandardWatchEventKinds.*; -import static java.nio.file.LinkOption.*; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -public class WatchTest { - - static WatchService ws = null; - static Map keys; - static final Path start = Paths.get("./test"); - - @BeforeClass - public static void setUp() throws Exception { - ws = FileSystems.getDefault().newWatchService(); - keys = new HashMap(); - - Path _start = start; - regAllForWatch(_start); - } - - private static void regAllForWatch(Path _start) throws IOException { - Files.walkFileTree(_start, new SimpleFileVisitor() { - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - regForWatch(dir); - return FileVisitResult.CONTINUE; - } - }); - } - - @AfterClass - public static void tearDown() throws Exception { - if (ws != null) { - ws.close(); - } - } - - @SuppressWarnings("unchecked") - static WatchEvent cast(WatchEvent event) { - return (WatchEvent)event; - } - - public static void processEvent() { - while (true) { - // wait for key to be signalled - WatchKey wk; - try { - wk = ws.take(); - System.out.println(wk); - } catch (InterruptedException x) { - return; - } - - Path dir = keys.get(wk); - if (dir == null) { - System.err.println("WatchKey not recognized! " + wk.watchable()); - continue; - } - - for (WatchEvent event : wk.pollEvents()) { - WatchEvent.Kind kind = event.kind(); - //TBD - provide example of how OVERFLOW event is handled - if (kind == OVERFLOW) { - continue; - } - - // Context for directory entry event is the file name of entry - WatchEvent ev = cast(event); - Path name = ev.context(); - Path child = dir.resolve(name); - - //print out event - System.out.format("%s: %s\n", event.kind().name(), child); - - if (kind == ENTRY_CREATE) { - try { - if (Files.isDirectory(child, NOFOLLOW_LINKS)) { - regAllForWatch(child); - } else { - regForWatch(child); - } - } catch (IOException x) { - // ignore to keep sample readbale - } - } - } - - if (wk.reset()) { - keys.remove(wk); - //all directories are inaccessible - if (keys.isEmpty()) { - return; - } - } - } - } - - private static void regForWatch(Path dir) throws IOException { - WatchKey regKey = dir.register(ws, StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_DELETE, - StandardWatchEventKinds.ENTRY_MODIFY); - - keys.put(regKey, dir); - } - - @Test - public void testWatchDir() throws Exception { - ExecutorService thread = Executors.newSingleThreadExecutor(); - thread.submit(WatchTest::processEvent); - - ScheduledExecutorService scheduledThread = Executors.newScheduledThreadPool(1); - scheduledThread.schedule(() -> { - try { - Path p = Paths.get("./test/test_file"); - p = Files.createFile(p); - Path _p = Paths.get("./test/test_file_renamed"); - Files.move(p, _p); - Files.delete(_p); - } catch (Exception e) { - e.printStackTrace(); - } - }, 5, TimeUnit.SECONDS); - - thread.shutdown(); - thread.awaitTermination(30, TimeUnit.SECONDS); - } -} diff --git a/src/main/java/cf/study/java8/text/SimpleDateFormatTests.java b/src/main/java/cf/study/java8/text/SimpleDateFormatTests.java deleted file mode 100644 index 1c004fa..0000000 --- a/src/main/java/cf/study/java8/text/SimpleDateFormatTests.java +++ /dev/null @@ -1,45 +0,0 @@ -package cf.study.java8.text; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -import org.apache.commons.lang3.time.DateFormatUtils; -import org.apache.log4j.Logger; -import org.junit.Test; - -public class SimpleDateFormatTests { - - @Test - public void testPatterns() { - Date now = new Date(); - - System.out.println(new SimpleDateFormat("S").format(now)); - - log.info(now); - } - - @Test - public void testYear() throws Exception { - SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd"); - Date d1 = s1.parse("2014-01-01"); - System.out.println(d1.getTime()); - - SimpleDateFormat s2 = new SimpleDateFormat("YYYY-MM-dd"); - Date d2 = s1.parse("2014-01-01"); - System.out.println(d2.getTime()); - - Calendar calendar = Calendar.getInstance(); - calendar.set(2014, Calendar.DECEMBER, 29); - System.out.println(DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd")); - System.out.println(s2.format(calendar.getTime())); - } - - private static final Logger log = Logger.getLogger(SimpleDateFormatTests.class); - - @Override - public String toString() { - return "SimpleDateFormatTests []"; - } - -} diff --git a/src/main/java/cf/study/java8/utils/OptionalTests.java b/src/main/java/cf/study/java8/utils/OptionalTests.java deleted file mode 100644 index adba1b7..0000000 --- a/src/main/java/cf/study/java8/utils/OptionalTests.java +++ /dev/null @@ -1,38 +0,0 @@ -package cf.study.java8.utils; - -import java.util.Arrays; -import java.util.Date; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.IntStream; - -import org.junit.Test; - -public class OptionalTests { - - @Test - public void testOptional() { - { - final Optional dateOpt = Optional.of(new Date()); - - final Predicate springPred = (_d) -> (IntStream.of(2, 3, 4).anyMatch((i) -> (i == _d.getMonth()))); - final Consumer springPrint = (_d) -> (System.out.println("spring")); - - final Predicate winterPred = (_d) -> (IntStream.of(10, 11, 12).anyMatch((i) -> (i == _d.getMonth()))); - final Consumer winterPrint = (_d) -> (System.out.println("winter")); - - dateOpt.filter(springPred).ifPresent(springPrint); - dateOpt.filter(winterPred).ifPresent(winterPrint); - } - - { - final Date d = new Date(); - if (Arrays.asList(1,2,3).contains(d.getMonth())) { - System.out.println("spring"); - } else if (Arrays.asList(10, 11, 12).contains(d.getMonth())) { - System.out.println("winter"); - } - } - } -} diff --git a/src/main/java/cf/study/java8/utils/concurrent/PrefTest.java b/src/main/java/cf/study/java8/utils/concurrent/PrefTest.java deleted file mode 100644 index 95f7897..0000000 --- a/src/main/java/cf/study/java8/utils/concurrent/PrefTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package cf.study.java8.utils.concurrent; -import java.nio.file.Paths; -import java.util.concurrent.atomic.AtomicLong; - -public class PrefTest implements Runnable { -// static volatile long counter = 0; - static AtomicLong counter = new AtomicLong(0); - - static void inc() { - try { - Paths.get("/").toFile().list(); - } catch (Exception e) { - e.printStackTrace(); - } -// counter++; - counter.incrementAndGet(); - } - - private int rounds = 1; - - public PrefTest(int num) { - this.rounds = num; - } - - @Override - public void run() { - for (long i = 0; i < rounds; i++) { - inc(); - } - } - - static final int THREAD_NUM = 8; - static final long EXPECTED_COUNTER = 1 << 16; //65536 - - public static void main(String[] args) { - System.out.printf("cpu core: %d \n", Runtime.getRuntime().availableProcessors()); - - System.out.printf("start\n"); - - for (int ci = 1; ci <= 256; ci = ci << 1) { - System.out.print(ci + " \t"); - for (int i = 0; i < 3; i++) { -// counter = 0; - counter.set(0); - System.out.print(doTest(ci) + " \t "); - } - System.out.print(counter + " \t "); - - System.out.println(); - } - } - - static long doTest(int testThreadNum) { - long start = System.currentTimeMillis(); - - Thread[] threads = new Thread[testThreadNum]; - for (int i = 0; i < testThreadNum; i++) { - threads[i] = new Thread(new PrefTest((int) (EXPECTED_COUNTER / testThreadNum))); - } - - for (Thread thread : threads) { - thread.start(); - } - - try { - for (Thread thread : threads) { - thread.join(); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - - return System.currentTimeMillis() - start; - } -} diff --git a/src/main/java/cf/study/java8/utils/concurrent/QueueTest.java b/src/main/java/cf/study/java8/utils/concurrent/QueueTest.java deleted file mode 100644 index c34987d..0000000 --- a/src/main/java/cf/study/java8/utils/concurrent/QueueTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package cf.study.java8.utils.concurrent; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -public class QueueTest { - public void testConcurrentLinkedQueue() { -// final Queue q = new LinkedBlockingQueue(); - final Queue q = new ConcurrentLinkedDeque(); - - final AtomicLong sum = new AtomicLong(0); - int supplierNum = 1; - int consumerNum = 32; - final int elementNum = 1 << 21; - - for (; supplierNum <= 32; supplierNum = supplierNum << 1) { - System.out.printf("producer: %d \t", supplierNum); - for (int i = 0; i < 4; i++) { - System.out.printf("%d ms \t", doQueueTest(q, sum, supplierNum, consumerNum, elementNum)); - System.out.printf("result %d \t\t", sum.get()); - } - System.out.println(); - } - } - - private long doQueueTest(final Queue q, final AtomicLong sum, final int supplierNum, int consumerNum, final int elementNum) { - sum.set(0); - ExecutorService executors = Executors.newFixedThreadPool(supplierNum + consumerNum); -// ExecutorService consumerExecutors = Executors.newFixedThreadPool(supplierNum); - - long start = System.currentTimeMillis(); - - Runnable supplier = new Runnable() { - public void run() { - for (int i = 0, j = elementNum / supplierNum; i < j; i++) { - q.offer(1); - } - } - }; - - for (int i = 0; i < supplierNum; i++) { - executors.submit(supplier); - } - - Runnable consumer = new Runnable() { - public void run() { - for (Integer i = null; sum.get() < elementNum; i = q.poll()) { - if (i == null) continue; - sum.addAndGet(i); - } - } - }; - for (int i = 0; i < consumerNum; i++) { - executors.submit(consumer); - } - - executors.shutdown(); -// consumerExecutors.shutdown(); - - try { -// while (!(supplyExecutors.isTerminated() && consumerExecutors.isTerminated())) { -// Thread.sleep(1); -// } - executors.awaitTermination(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - return System.currentTimeMillis() - start; - } - - public static void main(String[] args) { - QueueTest qt = new QueueTest(); - qt.testConcurrentLinkedQueue(); - } -} diff --git a/src/main/java/cf/study/java8/utils/jar/JarTest.java b/src/main/java/cf/study/java8/utils/jar/JarTest.java deleted file mode 100644 index 2c3adb7..0000000 --- a/src/main/java/cf/study/java8/utils/jar/JarTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package cf.study.java8.utils.jar; - -import java.io.File; -import java.io.InputStream; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Stream; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.SystemUtils; -import org.junit.Assert; -import org.junit.Test; - -public class JarTest { - - @Test - public void getClassPaths() { - System.out.println(SystemUtils.JAVA_CLASS_PATH.replace(';', '\n')); - System.out.println(SystemUtils.JAVA_LIBRARY_PATH.replace(';', '\n')); - System.out.println(SystemUtils.JAVA_HOME); - } - - @Test - public void loadRuntimeJar() throws Exception { - File _f = new File(String.format("%s/lib/rt.jar", SystemUtils.JAVA_HOME)); - - Assert.assertTrue(_f.exists()); - Assert.assertTrue(_f.isFile()); - - try (JarFile jf = new JarFile(_f)) { - System.out.println(String.format("entries: %d", jf.size())); - try (Stream entryStream = jf.stream()) { - entryStream.forEach((je) -> { - System.out.println(je); - }); - } - } - } - - @Test - public void readContentFromJar() throws Exception { - File _f = new File(String.format("%s/lib/rt.jar", SystemUtils.JAVA_HOME)); - - Assert.assertTrue(_f.exists()); - Assert.assertTrue(_f.isFile()); - - try (JarFile jf = new JarFile(_f)) { - JarEntry manifestEntry = jf.getJarEntry("META-INF/MANIFEST.MF"); - try (InputStream is = jf.getInputStream(manifestEntry)) { - System.out.println(IOUtils.toString(is)); - } - } - } -} diff --git a/src/main/java/cf/study/java8/utils/regex/RegexTests.java b/src/main/java/cf/study/java8/utils/regex/RegexTests.java deleted file mode 100644 index 6edad9d..0000000 --- a/src/main/java/cf/study/java8/utils/regex/RegexTests.java +++ /dev/null @@ -1,20 +0,0 @@ -package cf.study.java8.utils.regex; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Test; - -public class RegexTests { - - @Test - public void test() { - Pattern pattern = Pattern.compile("(ab|cd)"); - Matcher matcher = pattern.matcher("ababab"); - System.out.println(matcher.find()); - matcher = pattern.matcher("cdcdcd"); - System.out.println(matcher.find()); -// Assert.assertTrue(Pattern.matches("(a)", "aaa")); -// Assert.assertTrue(Pattern.matches("(b)", "bbb")); - } -} diff --git a/src/main/java/cf/study/java8/utils/stream/StreamTests.java b/src/main/java/cf/study/java8/utils/stream/StreamTests.java deleted file mode 100644 index 6738a11..0000000 --- a/src/main/java/cf/study/java8/utils/stream/StreamTests.java +++ /dev/null @@ -1,257 +0,0 @@ -package cf.study.java8.utils.stream; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.IntBinaryOperator; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import misc.MiscUtils; - -import org.junit.Assert; -import org.junit.Test; - -public class StreamTests { - @Test - public void example() { - - {//find out sum of all the integers greater than 5. - final List intList = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - //Collections.addAll(new ArrayList(), 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - - //Prior to Java 8, it could be: - int sum1 = 0; - for (final Integer iv : intList) { - if (iv > 5) sum1 += iv; - } - - int sum2 = intList.stream().filter(i -> (i > 5)).mapToInt(i -> i).sum(); - - Assert.assertEquals(sum1, sum2); - } - } - - @Test - public void createStream() { - { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - intStream.forEach(i -> (System.out.print(i + ", "))); - System.out.println(); - } - - { - Stream intStream = Stream.of(new Integer[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 }); - intStream.forEach(i -> (System.out.print(i + ", "))); - System.out.println(); - - { - Stream parallelIntStream = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5).parallelStream(); - parallelIntStream.forEach(i -> (System.out.print(i + ", "))); - System.out.println(); - } - } - - if (false) { - Stream strStream1 = Stream.generate(new Supplier() { - int i = 0; - public String get() { - i++; - if (i > 10) return null; - return "from a Supplier"; - } - }); - - strStream1.forEach(i -> (System.out.println(i))); - } - - { - String str = "abcdefg"; - str.chars().forEach(c -> {System.out.println((char)c);}); - } - - { - String str1 = "abcdefg"; - String str2 = "abcdefg"; - - IntStream stream1 = str1.chars(); - IntStream stream2 = str2.chars(); - - IntStream concated = IntStream.concat(stream1, stream2); - - concated.forEach(c -> {System.out.print((char)c + ", ");}); - } - } - - @Test - public void toCollectionAndArray() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - List intList = intStream.collect(Collectors.toList()); - System.out.println(intList); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - Map intAndChars = intStream.distinct().collect(Collectors.toMap(i -> i, i -> (char)(97 + i))); - System.out.println(intAndChars); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - Integer[] intArray = intStream.toArray(Integer[]::new); - System.out.println(Arrays.toString(intArray)); - } - - @Test - public void filter() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - int sum = intStream.filter(i -> (i % 2 == 0)).collect(Collectors.summingInt(i -> i)); - System.out.println(sum); - - sum = 0; - for (final int i : new int[] {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}) { - if (i % 2 == 0) sum += i; - } - System.out.println(sum); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - intStream.filter((i)->{System.out.println(i); return i == 1;}).findFirst(); - } - - @Test - public void map() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - intStream.map(i -> {return Math.abs(10 - i);}).forEach(i -> {System.out.print(i + ", ");}); - } - - @Test - public void sorted() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - List intList = intStream.sorted().collect(Collectors.toList()); - System.out.println(intList); - } - - @Test - public void flatMap() { - Stream> listStream = Stream.of( - Arrays.asList("html", "javascript", "css"), - Arrays.asList("servlet", "filter", "jsp"), - Arrays.asList("ejb", "jms", "jpa") - ); - - Stream flatStream = listStream.flatMap(strList -> strList.stream()); - flatStream.forEach(System.out::println); - } - - @Test - public void reduce() { - { - final IntBinaryOperator op = (_sum, i) -> (_sum += i); - System.out.println(IntStream.range(1, 10).reduce(op).getAsInt()); - } - - { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - Optional sum = intStream.reduce((_sum, i) -> (_sum += i)); - System.out.println(sum.get()); - } - - { - final List prices = Arrays.asList( - new BigDecimal("10"), new BigDecimal("30"), new BigDecimal("17"), - new BigDecimal("20"), new BigDecimal("15"), new BigDecimal("18"), - new BigDecimal("45"), new BigDecimal("12")); - - BigDecimal totalOfDiscountedPrices = prices.stream() - .filter(price -> price.compareTo(BigDecimal.valueOf(20)) > 0) - .map(price -> price.multiply(BigDecimal.valueOf(0.9))) - .reduce(BigDecimal.ZERO, BigDecimal::add); - System.out.println("Total of discounted prices: " + totalOfDiscountedPrices); - - totalOfDiscountedPrices = BigDecimal.ZERO; - for (BigDecimal price : prices) { - if (price.compareTo(BigDecimal.valueOf(20)) > 0) - totalOfDiscountedPrices = totalOfDiscountedPrices.add(price.multiply(BigDecimal.valueOf(0.9))); - } - System.out.println("Total of discounted prices: " + totalOfDiscountedPrices); - } - } - - @Test - public void count() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - System.out.println(intStream.count()); - } - - @Test - public void match() { - Stream intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - - System.out.println("even numbers: " + intStream.anyMatch(i -> (i % 2 == 0))); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - System.out.println("even numbers: " + intStream.allMatch(i -> (i % 2 == 0))); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - System.out.println("odd numbers: " + intStream.anyMatch(i -> (i % 2 == 1))); - - intStream = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); - System.out.println("odd numbers: " + intStream.noneMatch(i -> (i % 2 == 0))); - } - - - static class Record { - static int seq = 0; - Record(int _value) {value = _value;seq++;} - Record() { - seq++; - System.out.println(MiscUtils.stackInfo() + "\n"); - } - public int value; - @Override - public String toString() { - return super.toString() + "= {value: " + value + "}"; - } - } - - @Test - public void testInnerMechanism() { - { - final Record record1 = new Record(1); - final Record record2 = new Record(2); - final Record record3 = new Record(3); - - Stream records = Stream.of(record1, record2, record3); - final Optional reduced = records.reduce((_record, i) -> { - _record.value += i.value; - return _record; - }); - System.out.println(reduced.get().value); - System.out.println(Record.seq); - - System.out.println(record1); - System.out.println(record2); - System.out.println(record3); - } - - { - final Record record1 = new Record(1); - final Record record2 = new Record(2); - final Record record3 = new Record(3); - final Record recordSum = new Record(); - - Stream records = Stream.of(record1, record2, record3); - final Record reduced = records.reduce(recordSum, (_record, i) -> { - _record.value += i.value; - return _record; - }); - System.out.println(reduced.value); - System.out.println(Record.seq); - - System.out.println(record1); - System.out.println(record2); - System.out.println(record3); - System.out.println(recordSum); - } - } -} diff --git a/src/main/java/cf/study/java8/utils/zip/ZipTest.java b/src/main/java/cf/study/java8/utils/zip/ZipTest.java deleted file mode 100644 index 70c9bb6..0000000 --- a/src/main/java/cf/study/java8/utils/zip/ZipTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package cf.study.java8.utils.zip; - -public class ZipTest { - -} diff --git a/src/main/java/cf/study/search/lucene/LuceneTest.java b/src/main/java/cf/study/search/lucene/LuceneTest.java deleted file mode 100644 index cefa22d..0000000 --- a/src/main/java/cf/study/search/lucene/LuceneTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package cf.study.search.lucene; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -public class LuceneTest { - - @BeforeClass - public void setUp() throws Exception { - - } - - @AfterClass - public void tearDown() throws Exception { - - } -} diff --git a/src/main/java/misc/MiscUtils.java b/src/main/java/misc/MiscUtils.java deleted file mode 100644 index f1bc858..0000000 --- a/src/main/java/misc/MiscUtils.java +++ /dev/null @@ -1,214 +0,0 @@ -package misc; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.management.ManagementFactory; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.collections4.iterators.ObjectArrayIterator; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.apache.commons.lang3.math.NumberUtils; - -public class MiscUtils { - - public static String loadResAsString(final Class cls, final String fileName) { - if (cls == null || StringUtils.isBlank(fileName)) { - return StringUtils.EMPTY; - } - - try { - return IOUtils.toString(cls.getResourceAsStream(fileName)); - } catch (IOException e) { - e.printStackTrace(); - } - return StringUtils.EMPTY; - } - - public static class LoopingArrayIterator extends ObjectArrayIterator { - public LoopingArrayIterator(final E... array) { - super(array, 0, array.length); - } - - public LoopingArrayIterator(final E array[], final int start) { - super(array, start, array.length); - } - - public E loop() { - final E[] array = this.getArray(); - loopIdx.compareAndSet(array.length, 0); - return array[loopIdx.getAndIncrement() % array.length]; - } - - private AtomicInteger loopIdx = new AtomicInteger(); - } - - public static String toBinStr(final byte _b) { - final StringBuilder sb = new StringBuilder(); - for (byte i = 7; i >= 0; i--) { - sb.append((_b & (1 << i)) != 0 ? 1 : 0); - } - return sb.toString(); - } - - public static String toBinStr(final short _s) { - final StringBuilder sb = new StringBuilder(); - for (byte i = 16; i >= 0; i--) { - sb.append((_s & (1 << i)) != 0 ? 1 : 0); - } - return sb.toString(); - } - - public static String toBinStr(final int _i) { - final StringBuilder sb = new StringBuilder(); - for (byte i = 32; i >= 0; i--) { - sb.append((_i & (1 << i)) != 0 ? 1 : 0); - } - return sb.toString(); - } - - public static String toBinStr(long _l) { - final StringBuilder sb = new StringBuilder(); - for (byte i = 64; i >= 0; i--) { - sb.append((_l & (1 << i)) != 0 ? 1 : 0); - } - return sb.toString(); - } - - public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); - private static long HOST_HASH = System.currentTimeMillis(); - private static long IDX = 0; - - static { - try { - HOST_HASH = InetAddress.getLocalHost().getHostAddress().hashCode(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - } - - public static String invocationInfo() { - StackTraceElement[] ste = Thread.currentThread().getStackTrace(); - int i = 2; - return String.format("%s\t%s.%s", ste[i].getFileName(), ste[i].getClassName(), ste[i].getMethodName()); - } - - public static String invocInfo() { - StackTraceElement[] ste = Thread.currentThread().getStackTrace(); - int i = 2; - return String.format("%s\t%s.%s", ste[i].getFileName(), StringUtils.substringAfterLast(ste[i].getClassName(), ".") , ste[i].getMethodName()); - } - - public static String invocationInfo(final int i) { - StackTraceElement[] ste = Thread.currentThread().getStackTrace(); - return String.format("%s\t%s.%s", ste[i].getFileName(), ste[i].getClassName(), ste[i].getMethodName()); - } - - public static String stackInfo() { - final StringBuilder sb = new StringBuilder(); - final StackTraceElement[] stes = Thread.currentThread().getStackTrace(); - ArrayUtils.reverse(stes); - for (StackTraceElement ste : stes) { - sb.append(String.format("%s\t%s.%s\n", ste.getFileName(), ste.getClassName(), ste.getMethodName())); - } - return sb.toString(); - } - - public static String byteCountToDisplaySize(long size) { - String displaySize; - if (size / 1073741824L > 0L) { - displaySize = String.valueOf(size / 1073741824L) + " GB"; - } else { - if (size / 1048576L > 0L) { - displaySize = String.valueOf(size / 1048576L) + " MB"; - } else { - if (size / 1024L > 0L) - displaySize = String.valueOf(size / 1024L) + " KB"; - else - displaySize = String.valueOf(size) + " bytes"; - } - } - return displaySize; - } - - public static long getProcessId() { - // Note: may fail in some JVM implementations - // therefore fallback has to be provided - - // something like '@', at least in SUN / Oracle JVMs - final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); - final int index = jvmName.indexOf('@'); - String pidStr = jvmName.substring(0, index); - - if (index < 1 || !NumberUtils.isNumber(pidStr)) { - // part before '@' empty (index = 0) / '@' not found (index = -1) - return 0; - } - - return Long.parseLong(pidStr); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Map map(Object...keyAndVals) { - return MapUtils.putAll(new HashMap(), keyAndVals); - } - - public static String toXML(final Object bean) { - final StringWriter sw = new StringWriter(); - try { - JAXBContext jc = JAXBContext.newInstance(bean.getClass()); - - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FRAGMENT, true); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - // marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16"); - - m.marshal(bean, sw); - } catch (Exception e) { - e.printStackTrace(); - } - return sw.toString(); - } - - public static T toObj(final String xmlStr, final Class cls) { - if (StringUtils.isBlank(xmlStr) || cls == null) { - return null; - } - - try { - JAXBContext jc = JAXBContext.newInstance(cls); - Unmarshaller um = jc.createUnmarshaller(); - return um.unmarshal(new StreamSource(new StringReader(xmlStr)), cls).getValue(); - } catch (JAXBException e) { - e.printStackTrace(); - } - - return null; - } - - public static long uniqueLong() { - return Math.abs(UUID.randomUUID().hashCode()); - } - - public static ThreadFactory namedThreadFactory(final String name) { - return new BasicThreadFactory.Builder().namingPattern(name + "_%d").build(); - } - - -} diff --git a/src/main/resources/META-INF/beans.xml b/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 2196eb4..0000000 --- a/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/META-INF/persistence.xml b/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 458bc63..0000000 --- a/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml deleted file mode 100644 index 171216a..0000000 --- a/src/main/resources/log4j.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/study_java_8.iml b/study_java_8.iml deleted file mode 100644 index fe27d73..0000000 --- a/study_java_8.iml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/test.txt b/test/test.txt deleted file mode 100644 index f76415b..0000000 --- a/test/test.txt +++ /dev/null @@ -1 +0,0 @@ -hello work \ No newline at end of file diff --git a/testing-study/pom.xml b/testing-study/pom.xml new file mode 100644 index 0000000..31e5971 --- /dev/null +++ b/testing-study/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + java-study + testing-study + 0.0.1 + + + java-study + java-study + 0.1.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testing-study/src/test/java/study/junit/EnvTests.java b/testing-study/src/test/java/study/junit/EnvTests.java new file mode 100644 index 0000000..c9327b7 --- /dev/null +++ b/testing-study/src/test/java/study/junit/EnvTests.java @@ -0,0 +1,134 @@ +package study.junit; + + +import org.junit.jupiter.api.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.DynamicTest.dynamicTest; + +/** + * This class is meant to test logging settings + * as well as some new feature of JUnit5 + */ +public class EnvTests { + static final Logger log = LoggerFactory.getLogger(EnvTests.class); + + int testCount = 0; + + @TestFactory + Collection dynamicTestsFromCollection() { + return Arrays.asList( + dynamicTest("1st dynamic test", () -> assertTrue(true)), + dynamicTest("2nd dynamic test", () -> assertEquals(4, 2 * 2)) + ); + } + + /** + *
+     * Denotes that the annotated method should be executed before all
+     * @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class;
+     * analogous to JUnit 4’s @BeforeClass. Such methods are inherited (unless they are hidden or overridden)
+     * and must be static (unless the "per-class" test instance lifecycle is used).
+     * 
+ */ + @BeforeAll + public static void beforeAll() { + log.info("this is run before all test cases"); + } + + @BeforeEach + public void beforeEach() { + log.info("this is run before each test case: {}", testCount++); + } + + @AfterEach + public void afterEach() { + log.info("this is run after each test case: {}", testCount); + } + + /** + *
+     * Denotes that a method is a test method. Unlike JUnit 4’s @Test annotation,
+     * this annotation does not declare any attributes,
+     * since test extensions in JUnit Jupiter operate based on their own dedicated annotations.
+     * Such methods are inherited unless they are overridden.
+     * 
+ */ + @Test + public void testCase1() { + log.info("this is a test run for junit @Test"); + } + + @Test + public void testCase2() { + log.info("this is a test run for junit @Test"); + } + + @Test + @Disabled + public void testAbort() { + log.info("this test aborts the junit"); + System.exit(1); + } + + @RepeatedTest(3) + public void testRepeated() { + log.info("I am not sure how many times I am repeated"); + } + + @RepeatedTest(3) + public void testRepeated1(RepetitionInfo rpi) { + log.info("I am being repeated the {}-th time out of {} times", rpi.getCurrentRepetition(), rpi.getTotalRepetitions()); + } + + @RepeatedTest(value = 3) + public void testRepeated2(RepetitionInfo rpi) { + log.info("I am being repeated the {}-th time out of {} times", rpi.getCurrentRepetition(), rpi.getTotalRepetitions()); + if (rpi.getCurrentRepetition() == 2) { + throw new RuntimeException("enough! stop!"); + } + } + + @Test + public void testWhatInfo(TestInfo ti) { + log.info("what is in the TestInfo:\n\t{}", ti); + } + + @ParameterizedTest + @ValueSource(ints = {5, 1, 2, 3, 4}) + public void testParamsFromValueSrc(int arg) { + log.info("what parameter is it? \n\t{}", arg); + } + + @ParameterizedTest + @ValueSource(strings = {"I", "lv", "Tao"}) + public void testParamsFromValueSrc1(String arg) { + log.info("what parameter is it? \n\t{}", arg); + } + +// @ParameterizedTest +// @ValueSource(ints = {1, 2, 3, 4}) +// public void testParamsFromValueSrcExt(int arg, ParameterContext aa) { +// log.info("what parameter is it? \n\t{}\n\t among {}", arg, aa); +// } + + @AfterAll + public static void afterAll() { + log.info("this is run after all test cases"); + } + + @Test + public void testJUnit5(TestInfo ti, TestReporter tr) { + log.info("TestInfo:\t{}", ti); + log.info("TestReporter:\t{}", tr); + tr.publishEntry("testJUnit5", "what the fuck?"); + } +} diff --git a/testing-study/src/test/java/study/junit/ParallelTests.java b/testing-study/src/test/java/study/junit/ParallelTests.java new file mode 100644 index 0000000..aebb37a --- /dev/null +++ b/testing-study/src/test/java/study/junit/ParallelTests.java @@ -0,0 +1,30 @@ +package study.junit; + +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@ExtendWith({RandomParamExt.class, TimingExt.class}) +public class ParallelTests { + static final Logger log = LoggerFactory.getLogger(ParallelTests.class); + + static { + // not working +// String enableKey = "junit.jupiter.execution.parallel.enabled"; +// log.info(System.getProperty(enableKey)); +// System.setProperty(enableKey, Boolean.TRUE.toString()); +// System.setProperty("junit.jupiter.execution.parallel.mode.default", "concurrent"); + } + + @Test + @RepeatedTest(10) + @Execution(ExecutionMode.CONCURRENT) + public void testConcurrentMode(@RandomParamExt.RandParam long ms) throws InterruptedException { + Thread.sleep(ms % 1000); + log.info("finished"); + } +} diff --git a/testing-study/src/test/java/study/junit/RandomParamExt.java b/testing-study/src/test/java/study/junit/RandomParamExt.java new file mode 100644 index 0000000..20fd495 --- /dev/null +++ b/testing-study/src/test/java/study/junit/RandomParamExt.java @@ -0,0 +1,121 @@ +package study.junit; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.*; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Parameter; +import java.util.stream.Stream; + +import static java.lang.String.format; + +public class RandomParamExt implements ParameterResolver {//, TestTemplateInvocationContextProvider { + +// @Override +// public boolean supportsTestTemplate(ExtensionContext extCtx) { +// if (!extCtx.getTestMethod().isPresent()) { +// return false; +// } +// +// return true; +// } +// +// @Override +// public Stream provideTestTemplateInvocationContexts(ExtensionContext extCtx) { +// return null; +// } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.PARAMETER) + public @interface RandParam { + double start() default Double.NaN; + + double end() default Double.NaN; + } + + @Override + public boolean supportsParameter(ParameterContext paramCtx, ExtensionContext extCtx) throws ParameterResolutionException { + return paramCtx.isAnnotated(RandParam.class); + } + + @Override + public Object resolveParameter(ParameterContext paramCtx, ExtensionContext extCtx) throws ParameterResolutionException { + Parameter param = paramCtx.getParameter(); + Class paramCls = param.getType(); + + RandParam randAnno = param.getAnnotation(RandParam.class); + double d_start = randAnno.start(); + double d_end = randAnno.end(); + + Object randVal = genRandVal(paramCls, d_start, d_end); + extCtx.publishReportEntry(param.getName(), String.valueOf(randVal)); + return randVal; + } + + private static Object genRandVal(Class paramCls, double d_start, double d_end) { + if (int.class.equals(paramCls) || Integer.class.equals(paramCls)) { + long start = Double.isNaN(d_start) ? 0 : (long) d_start; + long end = Double.isNaN(d_end) ? Long.MAX_VALUE : (long) d_end; + return (int) (RandomUtils.nextLong(start, end) % Integer.MAX_VALUE); + } + if (boolean.class.equals(paramCls) || Boolean.class.equals(paramCls)) { + return RandomUtils.nextBoolean(); + } + if (short.class.equals(paramCls) || Short.class.equals(paramCls)) { + long start = Double.isNaN(d_start) ? 0 : (long) d_start; + long end = Double.isNaN(d_end) ? Long.MAX_VALUE : (long) d_end; + return (short) (RandomUtils.nextLong(start, end) % Short.MAX_VALUE); + } + if (byte.class.equals(paramCls) || Byte.class.equals(paramCls)) { + long start = Double.isNaN(d_start) ? 0 : (long) d_start; + long end = Double.isNaN(d_end) ? Long.MAX_VALUE : (long) d_end; + return (byte) (RandomUtils.nextLong(start, end) % Byte.MAX_VALUE); + } + if (long.class.equals(paramCls) || Long.class.equals(paramCls)) { + long start = Double.isNaN(d_start) ? 0 : (long) d_start; + long end = Double.isNaN(d_end) ? Long.MAX_VALUE : (long) d_end; + return RandomUtils.nextLong(start, end); + } + if (float.class.equals(paramCls) || Float.class.equals(paramCls)) { + float start = Double.isNaN(d_start) ? 0 : (float) d_start; + float end = Double.isNaN(d_end) ? Float.MAX_VALUE : (float) d_end; + return RandomUtils.nextFloat(start, end); + } + if (double.class.equals(paramCls) || Double.class.equals(paramCls)) { + return RandomUtils.nextDouble(d_start, d_end); + } + if (String.class.equals(paramCls)) { + long start = Double.isNaN(d_start) ? 0 : (long) d_start; + long end = Double.isNaN(d_end) ? Long.MAX_VALUE : (long) d_end; + return RandomStringUtils.randomAscii((int) (RandomUtils.nextLong(start, end) % Integer.MAX_VALUE)); + } + + return null; + } + + @ExtendWith({RandomParamExt.class}) + public static class SelfTests { + + @Test + @RepeatedTest(10000) + public void testSelfInt(@RandParam(start = 100, end = 200) int _int) { + Assertions.assertTrue(_int >= 100 && _int < 200, format("_int is %d", _int)); + } + + @Test + @RepeatedTest(1) + public void testSelfString(@RandParam(start = 100, end = 200) String str) { + int len = str.length(); + Assertions.assertTrue(len >= 100 && len < 200, format("str.length() is %d", len)); +// System.out.println(format("str is %d", str)); + System.out.println(str); + } + } +} diff --git a/testing-study/src/test/java/study/junit/TimingExt.java b/testing-study/src/test/java/study/junit/TimingExt.java new file mode 100644 index 0000000..018b49c --- /dev/null +++ b/testing-study/src/test/java/study/junit/TimingExt.java @@ -0,0 +1,48 @@ +package study.junit; + +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.AfterTestExecutionCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Method; + +public class TimingExt implements BeforeTestExecutionCallback, AfterTestExecutionCallback { + + static final Logger log = LoggerFactory.getLogger(TimingExt.class); + + private static final String START_TIME = "start time"; + + @Override + public void beforeTestExecution(ExtensionContext context) throws Exception { + getStore(context).put(START_TIME, System.currentTimeMillis()); + } + + @Override + public void afterTestExecution(ExtensionContext context) throws Exception { + Method testMethod = context.getRequiredTestMethod(); + long startTime = getStore(context).remove(START_TIME, long.class); + long duration = System.currentTimeMillis() - startTime; + log.info("Method [{}] took {} ms.\n", testMethod.getName(), duration); + } + + private Store getStore(ExtensionContext context) { + return context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod())); + } + + @ExtendWith(value = {TimingExt.class, RandomParamExt.class}) + public static class Tests { + + @Test + @RepeatedTest(5) + public void testThreadSleep(@RandomParamExt.RandParam long milliSec) throws InterruptedException { + Thread.sleep(milliSec % 2000); + } + } +} \ No newline at end of file diff --git a/testing-study/src/test/resources/junit-platform.properties b/testing-study/src/test/resources/junit-platform.properties new file mode 100644 index 0000000..32dd6db --- /dev/null +++ b/testing-study/src/test/resources/junit-platform.properties @@ -0,0 +1,2 @@ +junit.jupiter.execution.parallel.enabled=true +junit.jupiter.execution.parallel.config.strategy=dynamic \ No newline at end of file diff --git a/testing-study/src/test/resources/log4j2.xml b/testing-study/src/test/resources/log4j2.xml new file mode 100644 index 0000000..739f19f --- /dev/null +++ b/testing-study/src/test/resources/log4j2.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + \ No newline at end of file