顯示具有 java 標籤的文章。 顯示所有文章
顯示具有 java 標籤的文章。 顯示所有文章

2020年12月8日 星期二

Quarkus-RestEasy & HttpRequest/Client

ResteasyTest.java (ref: quarkus guide and HowToDoInJava )
跟RecursiveTask/RecursiveAction不合的樣子@@"
package org.acme.lifecycle;

import io.quarkus.runtime.annotations.QuarkusMain;

import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import io.quarkus.runtime.Quarkus;


@QuarkusMain
public class ResteasyTest
{
    private static void getExample_one().
    {   
        ResteasyClient client = new ResteasyClientBuilder().build(); //for resteasy-api version 3.x
        ResteasyWebTarget target = client.target("http://localhost:2020/Helloworld/All");
        Response response = target.request().get();
        String value = response.readEntity(String.class);
        System.out.println(value);
        response.close();
    }   
    public static void main(String ... args) {
        System.out.println("Hello World");
        getExample_one();
        Quarkus.run(args);
    }   
}


ResteasHttpRequestClient.java (ref: httpclient, Java 11 HttpClient Examples)
package org.acme.lifecycle;

import io.quarkus.runtime.annotations.QuarkusMain;

import javax.ws.rs.core.Response;

import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

import io.quarkus.runtime.Quarkus;


@QuarkusMain
public class ResteasyTest
{
    private static void getExample_one()
    {   
        ResteasyClient client = new ResteasyClientBuilder().build(); //for resteasy-api version 3.x
        ResteasyWebTarget target = client.target("http://localhost:2020/Helloworld/All");
        Response response = target.request().get();
        String value = response.readEntity(String.class);
        System.out.println(value);
        response.close();
                HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json; charset=UTF-8")
                .POST(BodyPublishers.ofString(reqBody))
                .build();
        HttpResponse<String> response = null;
		try 
		{
		    response = client.send(request, HttpResponse.BodyHandlers.ofString());
		} 
		catch (IOException e) 
		{
		    e.printStackTrace();
		} 
		catch (InterruptedException e) 
		{
		    e.printStackTrace();
		}
        return response.body();
    }
    
    private static String getExample_two()
    {
        //HttpClient client = HttpClient.newHttpClient();
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(tout))
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(tout))
                .header("Content-Type", "application/json; charset=UTF-8")
                .POST(BodyPublishers.ofString(reqBody))
                .build();

        try {
            return client.sendAsync(request, BodyHandlers.ofString())
                    .thenApply(HttpResponse::body).get().toString();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private static String getExample_three()
    {
        //HttpClient client = HttpClient.newHttpClient();
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(tout))
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(tout))
                .header("Content-Type", "application/json; charset=UTF-8")
                .GET()
                .build();
        CompletableFuture <HttpResponse<String>> response =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        String result = null;
        try {
            result = response.thenApply(HttpResponse::body).get();
        }
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        } 
        catch (ExecutionException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static void main(String ... args) {
        System.out.println("Hello World");
        getExample_one();
        //two跟three寫法其實相同
        getExample_two();
        getExample_three();
        Quarkus.run(args);
    }   
}

pom.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.acme</groupId>
  <artifactId>lifecycle-quickstart</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <properties>
    <surefire-plugin.version>2.22.1</surefire-plugin.version>
    <maven.compiler.target>11</maven.compiler.target>
    <quarkus.platform.version>1.10.3.Final</quarkus.platform.version>
    <maven.compiler.source>11</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.parameters>true</maven.compiler.parameters>
    <quarkus-plugin.version>1.10.3.Final</quarkus-plugin.version>
    <compiler-plugin.version>3.8.1</compiler-plugin.version>
    <quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>${quarkus.platform.group-id}</groupId>
        <artifactId>${quarkus.platform.artifact-id}</artifactId>
        <version>${quarkus.platform.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
     <!-- core library -->
    <dependency>
       <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
       <version>3.6.0.Final</version>
    </dependency>
    <!-- JAXB support -->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.6.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>jaxrs-api</artifactId>
        <version>3.0.12.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.6.0.Final</version>
    </dependency>

    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-arc</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus-plugin.version}</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <goals>
              <goal>build</goal>
              <goal>generate-code</goal>
              <goal>generate-code-tests</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${compiler-plugin.version}</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <systemPropertyVariables>
            <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
            <maven.home>${maven.home}</maven.home>
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>native</id>
      <activation>
        <property>
          <name>native</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${surefire-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <systemPropertyVariables>
                    <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                    <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
                    <maven.home>${maven.home}</maven.home>
                  </systemPropertyVariables>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <properties>
        <quarkus.package.type>native</quarkus.package.type>
      </properties>
    </profile>
  </profiles>
</project>

編譯時碰到的問題, 因為環境是 java 11的,
使用太新的 resteasy 版本,所以發生些錯誤,查一下 java 11大約是何時 release後
找那個時間點左右的版本就行了
Caused by: org.apache.maven.plugin.MojoExecutionException: Dev mode process did not complete successfully
...
...
[ERROR] Using javaTool: /opt/java/jdk-11.0.8/bin/java
...
...
[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.10.3.Final:dev (default-cli) on project lifecycle-quickstart: Failed to run: Dev mode process did not complete successfully -> [Help 1]

編譯:
./mvnw compile quarkus:dev -Ddebug=5006 -Dquarkus.log.file.enable=true -Dquarkus.log.file.rotation.max-file-size=10M -Dquarkus.log.file.rotation.max-backup-index=20

ref:
1. What's New in Maven
2. quarkus guide
3. HowToDoInJava 

2020年11月10日 星期二

Maven-Hello world/Unix Time

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.coveros.demo</groupId>
  <artifactId>helloworld</artifactId>
  <version>1.1</version>
  <packaging>jar</packaging>

  <name>Hello World</name>
  <description>The most basic of Java programs.</description>
  <url>https://www.coveros.com/</url>
  <inceptionYear>2018</inceptionYear>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <jdk.version>1.8</jdk.version>

    <maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


HelloWorld.java
package com.coveros.demo.helloworld;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloWorld {

    public static void main(final String[] args) 
    {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	//format.setTimeZone(java.util.TimeZone.getTimeZone("GMT-8")); 
    	Date date = null;
		try {
			date = format.parse("2020-11-10 12:34:56");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	long unixSeconds = date.getTime();
    	System.out.println("timestamp="+unixSeconds);
    	
    	// convert seconds to milliseconds
    	date = new java.util.Date(unixSeconds); 
    	format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    	//format.setTimeZone(java.util.TimeZone.getTimeZone("GMT-8")); 
    	String formattedDate = format.format(date);
    	System.out.println(formattedDate);
    }
}


build: $ mvn clean package
run: $ java -cp target/helloworld-1.0.jar com.coveros.demo.helloworld.HelloWorld


Folder Tree
$ tree
.
├── pom.xml
├── src
│   └── main
│       └── java
│           └── com
│               └── coveros
│                   └── demo
│                       └── helloworld
│                           └── HelloWorld.java


Unix Time on line tool

2020年10月5日 星期一

反應式 (-the-term-reactive)

Maven Tools (mvn)

 

Running Maven Tools (mvn)

Maven Phases

Although hardly a comprehensive list, these are the most common default lifecycle phases executed.

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

There are two other Maven lifecycles of note beyond the default list above. They are

  • clean: cleans up artifacts created by prior builds
  • site: generates site documentation for this project



JVM Mode
$ mvn package

$ java -jar target/xxx-SNAPSHOT-runner.jar 
Native Mode
$ mvn package -P native

$ ./target/xxx-1.0-SNAPSHOT-runner
Maven Wrapper plugin (for Quarkus)
Create:
$ mvn -N io.takari:maven:wrapper

Usage:
$ ./mvnw compile quarkus:dev -Dquarkus.log.file.enable=true -Dquarkus.log.file.rotation.max-file-size=10M -Dquarkus.log.file.rotation.max-backup-index=20

2020年8月27日 星期四

SequenceGenerator

Copy it form PostgreSQL 建立資料庫時名稱大小混用,使用自動編號時要注意的地方
以前在 MS SQL 中設定 Primary key 可以設定 Identity Increment 選項讓他自動編號, 
Ho YA,幸福嗎? 很美滿!!!
但是到了 PostgreSQL 中建立Table 的介面上面找半天也找不到那個選項,
原來PosrgreSQL的自動編號叫做 SEQUENCE,要用她之前要先去新增SEQUENCE


Quarkus example:
@Id
@SequenceGenerator(name = "fruitsSequence", sequenceName = "known_fruits_id_seq", 
allocationSize = 1, initialValue = 10)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "fruitsSequence")
private Integer id;
這應該是用在PostgreSQL
MySQL應該用這就行了
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;


ref: 理解JPA注解@GeneratedValue的使用方法

2016年7月22日 星期五

打包jar檔

網路上有很多文章教人打包jar檔,試了一下,
過程都沒什麼問題,但是最後放到 android studio 都不能用 @@
後來只有用 studio 來包,
studio提供包成 Android library 和 Java library,
用 Java library 後,過程很順,但最後要試用,還是有問題。
所以目前用 Android library 來包 jar

在某個專案下:
File -> New -> New Module -> Android library
會產生類似一個新專案的結構,
可以把 MainActivity.java 給 delete
然後建立一個新的 java,寫完compile後,
會在 module_name/build/intermediates/bundles/debug/ 產生一個 classes.jar
這個 classes.jar 就能拿去給其它專案使用了
(會多個 BuildConfig,暫時找不到方法不讓它一起產生)

將 *.so 也打包成 *.jar:
将所有需要使用的.so文件压缩为.zip文件
zip中的文件目录结构为: lib/armeabi/*.so, ( $ zip -r zipFile.zip dirFile/ )
注意,一定要是这样的路径,lib不要写成libs啊!
然后将这个.zip文件重命名为xxx.jar文件,将该jar包添加到项目的libs文件下。
^---|armeabi.jar  
        ^---|lib 
              ^---|armeabi 
                     ^---|xxx.so 
build.gradle設定

ref :  Here

2016年7月20日 星期三

Sign Key for Jar

試了一下, jar檔可以用 keytool 來 sign key
keytool -genkey -keyalg RSA -alias myFirstKey -keystore myKeystore -validity 360
jarsigner -keystore myKeystore -verbose jarfiller-example.jar myKey
Sign好後,可以用
jarsigner -verify signed.jar
How to Create a (Self-)Signed Jar

2015年12月14日 星期一

Read file As String

public class ReadFile {

    private static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);//.append("\n");
        }
        reader.close();
        return sb.toString();
    }

    public static String getStringFromFile (String filePath) throws Exception {
        File fl = new File(filePath);
        FileInputStream fin = new FileInputStream(fl);
        String ret = convertStreamToString(fin);
        if (DEBUG) Log.i("nice", "retttttt=" + ret);
        //Make sure you close all streams.
        fin.close();
        return ret;
    }
}

ref : stackoverflow

Zip and Unzip on Java

zip file是用這個
/*
*  String[] files : pathFile1, pathFiles2, ...
*  zipFile : pathName.zip 
*/  
public static void zip(String[] files, String zipFile) throws IOException {
    BufferedInputStream origin = null;
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    try { 
        byte data[] = new byte[BUFFER_SIZE];

        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(files[i]);    
            origin = new BufferedInputStream(fi, BUFFER_SIZE);
            try {
                ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }
            }
            finally {
                origin.close();
            }
        }
    }
    finally {
        out.close();
    }
}
ref : stackoverflow

目前解壓zip是用這個...
private boolean unpackZip(String path, String zipname)
{       
     InputStream is;
     ZipInputStream zis;
     try 
     {
         is = new FileInputStream(path + zipname);
         zis = new ZipInputStream(new BufferedInputStream(is));          
         ZipEntry ze;

         while((ze = zis.getNextEntry()) != null) 
         {
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             byte[] buffer = new byte[1024];
             int count;

             String filename = ze.getName();
             FileOutputStream fout = new FileOutputStream(path + filename);

             // reading and writing
             while((count = zis.read(buffer)) != -1) 
             {
                 baos.write(buffer, 0, count);
                 byte[] bytes = baos.toByteArray();
                 fout.write(bytes);             
                 baos.reset();
             }

             fout.close();               
             zis.closeEntry();
         }

         zis.close();
     } 
     catch(IOException e)
     {
         e.printStackTrace();
         return false;
     }
    return true;
}
ref : stackoverflow

2015年11月26日 星期四

threadpool

public int abc()
    {
        ExecutorService executor = Executors.newFixedThreadPool(1);
        readCmdGpio rCmdGpio = new readCmdGpio();
        Future future = executor.submit(rCmdGpio);

    }

    private class readCmdGpio implements Callable
    {
        @Override
        public Integer call() throws Exception {

            return 0;
        }
    }
http://stackoverflow.com/questions/3141158/how-can-a-thread-return-a-value-after-finishing-its-job

http://www.journaldev.com/1069/java-thread-pool-example-using-executors-and-threadpoolexecutor

2015年8月17日 星期一

Java提供四种线程池

Java通过Executors提供四种线程池,分别为:

。newCachedThreadPool
。newFixedThreadPool
。newScheduledThreadPool
。newSingleThreadExecutor
   
ref : Java(Android)线程池


2015年1月14日 星期三

Java - 函數指標

用利用abstract作到類似函數指標的功能

abstract class Base {
    public abstract void printValue();
}

class printA extends Base {
    @Override
    public void printValue(){
            System.out.println("printA");
        }
}

class printB extends Base {
    @Override
    public void printValue(){
            System.out.println("printB");
        }
}

class printC extends Base {
    @Override
    public void printValue(){
            System.out.println("printC");
        }
}

public class TestJavaFnPT {

    public static void main(String[] argv){
            Base[] pv3 = new Base[2];
            pv3 [0] = new printA();
            pv3 [1] = new printB();
            pv3 [2] = new printC();
            for( int i=0 ; i<3 i++)
                pv3 [i].printValue();
            }
    }
}       

RUN....

printA
printB
printC

ref : Young's Blog

2014年10月5日 星期日

介面與多重繼承

介面與多重繼承

2014年9月10日 星期三

隨手筆記

Thread & Runnable
啟動Thread,指定Runable給它執行。執行完後就不再動作。

HandlerThread & Handler
有一種Thread,他的性質比較不一樣,不管有沒有事情做也要待機在那裡。
會有一個 HandlerThread 負責管理他要執行的事。

2014年8月25日 星期一

AsyncTask

注意事項:
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

ref: 老灰鴨的筆記本
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
{
    // 對照前面提到的 3 個傳入的參數
    // URL 指 Params 參數的類別
    // Integer 指 Progress 參數的類別
    // Long 指 Result 參數的類別
    protected Long doInBackground(URL... urls)
    {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++)
        {
            totalSize += Downloader.downloadFile(urls[i]);
            // 呼叫 publishProgress() 以更新 UI 畫面,
            // 可藉由此方式更新畫面上的進度表
            publishProgress((int) ((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled())
                break;
        }
        // 將 totalSize 傳給 onPostExecute()
        return totalSize;
    }
 
    protected void onProgressUpdate(Integer... progress)
    {
        // 這裡接收傳入的 progress 值, 並更新進度表畫面
        // 參數為 Integer 型態的陣列
        // 但因為在 doInBackground() 只傳一個參數
        // 所以以 progress[0] 取得傳入參數
        setProgressPercent(progress[0]);
    }
 
    protected void onPostExecute(Long result)
    {
        showDialog("Downloaded " + result + " bytes");
    }
}

ref: 老灰鴨的筆記本
       AsyncTask

2014年8月21日 星期四

入門 1

@Override
    public void onClick(View arg0) {
     MyClientTask myClientTask = new MyClientTask(
       editTextAddress.getText().toString(),
       Integer.parseInt(editTextPort.getText().toString()));
     myClientTask.execute();
    }};
先這樣記:建立(MyClientTask)一個物件(myClientTask),並給初始值(new MyClientTask()) keyword: inner class
public class MyClientTask extends AsyncTask {
  
  String dstAddress;
  int dstPort;
  String response = "";

  MyClientTask(String addr, int port)  /*建構子,會先執行初使化*/
  { 
   dstAddress = addr;
   dstPort = port;
  }
  ...
  ...
  ...

ref : Android Server/Client example - client side using Socket
/*nice*/