目前分類:java (42)

瀏覽方式: 標題列表 簡短摘要

合併多個相同物件內的List物件 物件設定

@Data
public class TestTOB {
  private List type;

  public static class Sel {
    private String key;
    private String val;

    /**
     * @param a
     * @param b
     */
    public Sel(String key, String val) {

      super();
      this.key = key;
      this.val = val;
    }

    @Override
    public String toString() {

      StringBuilder builder = new StringBuilder();
      builder.append("Sel [key=").append(key).append(", val=").append(val).append("]");
      return builder.toString();
    }

  }
}

用flatMap將TestTOB內的List轉換成個別扁平流,再透過collect結合

  @Test
  public void flatMapTest() throws Exception {
    List a= new ArrayList<>();
    
    TestTOB qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("a","1")));
    a.add(qq);
    
    qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("b","2")));
    a.add(qq);
    
    qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("c","3")));
    a.add(qq);
    
    List c = a.stream()
        .flatMap(o -> o.getType().stream())
        .collect(Collectors.toList());
    
    c.stream().forEach(o->System.out.println(o.toString()));

  }
  
//Sel [key=a, val=1]
//Sel [key=b, val=2]
//Sel [key=c, val=3]

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()


使用ThreadPoolTaskScheduler.schedule會因為任務執行的時間超過觸發器間隔,而延後後序排程時間。

以下程式RUN出來會發現

 

public String scheduleTask() {

    Runnable task = () -> {

      System.out.println(Thread.currentThread().getName() + "-Scheduled task started at: " + new Date());

      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println(Thread.currentThread().getName() + "-Scheduled task resumed at: " + new Date());
    };

    taskScheduler.schedule(task, new CronTrigger("0/5 * * * * *"));

    return "Schedule task triggered successfully!";
  }
  
  
//    Task-Scheduled-1-Scheduled task started at: Wed Jul 12 15:30:10 CST 2023
//    Task-Scheduled-1-Scheduled task resumed at: Wed Jul 12 15:30:20 CST 2023
//    Task-Scheduled-2-Scheduled task started at: Wed Jul 12 15:30:25 CST 2023
//    Task-Scheduled-2-Scheduled task resumed at: Wed Jul 12 15:30:35 CST 2023
//    Task-Scheduled-1-Scheduled task started at: Wed Jul 12 15:30:40 CST 2023
//    Task-Scheduled-1-Scheduled task resumed at: Wed Jul 12 15:30:50 CST 2023

如果不希望等待前一個排程作業結束,希望時間到就執行可以加入CompletableFuture.runAsync

public String scheduleTask2() {

    Runnable task = () -> {
      
      CompletableFuture.runAsync(() -> {

        System.out.println(Thread.currentThread().getName() + "-Scheduled task started at: " + new Date());

        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "-Scheduled task resumed at: " + new Date());
      });

    };

    taskScheduler.schedule(task, new CronTrigger("0/5 * * * * *"));
    
//    ForkJoinPool.commonPool-worker-1-Scheduled task started at: Wed Jul 12 15:33:15 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task started at: Wed Jul 12 15:33:20 CST 2023
//    ForkJoinPool.commonPool-worker-3-Scheduled task started at: Wed Jul 12 15:33:25 CST 2023
//    ForkJoinPool.commonPool-worker-1-Scheduled task resumed at: Wed Jul 12 15:33:25 CST 2023
//    ForkJoinPool.commonPool-worker-1-Scheduled task started at: Wed Jul 12 15:33:30 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task resumed at: Wed Jul 12 15:33:30 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task started at: Wed Jul 12 15:33:35 CST 2023
//    ForkJoinPool.commonPool-worker-3-Scheduled task resumed at: Wed Jul 12 15:33:35 CST 2023

    return "Schedule task triggered successfully!";
  }
 

 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

資料寫入檔案

  /**
   * 產檔
   * @param filePathLocal 路徑
   * @param fileName 檔名
   * @param str內容
   * @throws IOException
   */
  public void mkFile(String filePathLocal, String fileName, String str) throws IOException {

    File file = new File(filePathLocal);
    if (!file.isDirectory()) {
      file.mkdirs();
     //資料夾權限
      file.setReadable(true, false);
      file.setExecutable(true, false);
      file.setWritable(true, false);
    }

    Path localFile = Paths.get(filePathLocal, fileName);
    BufferedWriter writer = Files.newBufferedWriter(localFile, StandardCharsets.UTF_8);
    writer.write(xml);
    writer.close();
  }

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

將多個檔案壓縮到一個檔

  /**
   * 壓縮檔案
   * @param filePathList 檔案列表
   * @param zipDest 壓縮檔資料夾
   * @return 壓縮檔路徑
   * @throws IOException
   */
public String batchDownLoadFile(List<String> filePathList, String zipDest) throws IOException {

    File zipFile = new File(zipDest, System.nanoTime() + ".zip");

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);
    FileInputStream fis = null;
    
    Set<String> filePathSet = new HashSet<>(filePathList);
    
    try {
      for(String filePath: filePathSet) {
        fis = new FileInputStream(filePath);
        File file = new File(filePath);
        
        zos.putNextEntry(new ZipEntry(file.getName()));
      
        int tmp = 0;
        while((tmp = fis.read()) != -1) {
          zos.write(tmp);
        }
        zos.flush();
        fis.close();
        zos.closeEntry();
      } 
    }finally {
      zos.close();
      fos.close();
    }

    return zipFile.getPath();
  }

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

Q: 使用Image getInstance(final URL url)報錯 java.io.IOException: XXXXXXXX is not a recognized imageformat.

A: 確認圖檔是否為可使用格式:gif jpeg png

    /**
     * Gets an instance of an Image.
     *
     * @param filename
     *            a filename

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

 @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

 public void batchUpdate(List<User> list) {

    if(CollectionUtils.isNotEmpty(list)) {
          String sql = "INSERT INTO USER (NAME, TEL, ADDR) VALUES( :name, :tel, :addr)";
      SqlParameterSource[] batchArgs = SqlParameterSourceUtils.createBatch(list.toArray());
      nameJdbcTemplateOracle.batchUpdate(sql, batchArgs);   
    }
    
  }



@lombok.Data
public class SupStoreInfo{
  private String name;
    
  private String tel;

  private String addr;
}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

XML過濾非法符號

String xml = "<?xml  version="1.0" encoding="big5"?><doc><PickFileID>123456</PickFileID></doc>"
xml.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "")

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

換行使用:<br/>

  /**
   * 抓取zip檔
   * @param fileName 檔案名稱
   * @return 處理結果 
   * <br/>msg: 內容
   * <br/>dir: 資料夾
   * @throws Exception
   */
public Rst process(String fileName) throws Exception {}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

Java 8 的 Stream API是對集合(Collection)功能的增強,能進行各種便利、高效的聚合操作(aggregate operation),或者數據操作。

同時提供順序流和並行流兩模式進行匯聚操作:

  • 並行模式:把一個內容分成多個數據塊,並用不同的線程分別處理每個數據塊的流(Fork/Join),能夠充分利用多核處理器的優勢。使用 fork/join 並行方式拆分任務和加速處理過程。
  • 順序模式:一個一個執行
  • 順序流的操作是在單線程上執行,而並行流的操作是在多線程上併發。
  • 並不是所有的問題都適合使用並行模式,考量要點:數據量、任務是否獨立、資料是否有順序
  • stream() − 為集合創建串行流;parallelStream() − 為集合創建並行流。

 Stream建構方法 

//基本數值型,目前有三種對應的包裝類型 Stream:IntStream、LongStream、DoubleStream ,可以直接套用增加效能

//Individual values
Stream stream = Stream.of("a", "b", "c");

// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
Stream streamA = Stream.of(strArray);
Stream streamB = Arrays.stream(strArray);

IntStream.of(new int[]{1, 2, 3});
IntStream.range(1, 3);
IntStream.rangeClosed(1, 3);

// 3. Collections
List<String> list = Arrays.asList(strArray);
Stream stream = list.stream();

 Stream API操作類型 

  • intermediate operation( 中介操作 ):map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered。
    一個Stream後面可以跟隨0或多個操作,尚未真正開始Stream的遍歷,多個操作在 Terminal 操作的時候一次循環完成
  • terminal operations( 聚合操作 ):forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator,真正開始Stream的遍歷
  • Short-circuiting: anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit

 filter:過濾,符合條件的留下 

List<String> strList = Arrays.asList("A", "B", "AA", "C");
List<String> strListAfter = strList.stream()
 .filter(x -> x.contains("A"))
 .collect(Collectors.toList());

 map:把 input Stream 的每一個元素,映射成 output Stream 的另外一個元素 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

ftp client和ftp server進行文件上傳會建立2條連接(control connectionsdata connections )

control connections : client 對server所下的任何指令 ( tcp/21 )

data connections:資料傳輸 (tcp/20)

client-server連線後保持著control connections等待要求,當需要傳輸檔案時,建立data connections,資料傳送完畢後釋放

控制連接:ftp命令交互

import org.apache.commons.net.ftp.FTPClient;

    FTPClient client = new FTPClient();
    /**
     * client和server的連線逾時時間
     */
    client.setConnectTimeout(connectTimeout);
    /**
     * 非處理資料總時間,data connections中socket阻塞未收到檔案的時間
     */
    client.setDataTimeout(timeout);
    /**
     * control connections數據讀取超時的時間
     * SoTimeout def.-set before connect() 
     */
    client.setDefaultTimeout(timeout);
    /**
     * control connections建立後,重新設置數據讀取超時時間
     * -set after connect() 
     */
    client.setSoTimeout(timeout);

 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

String array change to IntegerList

String[] arr = {'1', '2', '3'}
List<Integer> numList = Arrays.stream(arr )
            .map(Integer::parseInt)
            .collect(Collectors.toList());

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

避免溢位計算

java.lang.Math;

Math.addExact(Long.MAX_VALUE-1L, 2L); //計算溢位

throw java.lang.ArithmeticException: long overflow




文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

error by

Servlet.service() for servlet [dispatcherServlet] in context with path [/testweb] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/mem/prof/view], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/mem/prof/view], template might not exist or might not be accessible by any of the configured Template Resolvers
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:869)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

java.time.LocalDateTime to java.util.Date

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.junit.Test;

public class LocalDateTimeTest {
        
        @Test   
        public void toDate(){

          LocalDateTime testLDT = LocalDateTime.now();
          Date testD = Date.from(testLDT.atZone(ZoneId.systemDefault()).toInstant());
          
          System.out.println(testD.toString());

          LocalDateTime testLDT2 = LocalDateTime.ofInstant(testD.toInstant(), ZoneId.systemDefault());
          System.out.println(testLDT2.toString());
        }

}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

try catch use:

if(e instanceof RestClientException && e.getCause() instanceof HttpMessageNotReadableException) {
        //TODO
 }

org.springframework.web.client.RestClientException: Error while extracting response for type [class com.test.res] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: (PushbackInputStream); line: 1, column: 2]

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

解壓縮的時候發現

net.lingala.zip4j.ZipFile.isEncrypted() throws net.lingala.zip4j.exception.ZipException: Expected central directory entry not found (#1)

一路追發現主要是出錯在 at net.lingala.zip4j.headers.HeaderReader.readCentralDirectory(HeaderReader.java:168)
主要為檔案有異常

然後看到「ZIP4j 压缩与解压」https://blog.csdn.net/u011165335/article/details/50496930
這篇有提到

在添加文件时,发现只能添加一次,再次添加报错:Expected central directory entry not found (#1),

 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

@JsonFormat

  • 物件<->JSON 格式化互轉
  • 格式前端到後端、格式後端到前端
  • 資料交換如果以JSON交換,用此就可以了

@DateTimeFormat

  • spring mvc 格式前端到後端資料
  • 適用在form mapping

 

JSON傳值

{"testTimeA": "2020/08/26 18:42:12"}

後台設定物件

@lombok.Data
@ApiModel
public class testReq {

  @ApiModelProperty
  @JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss", shape = JsonFormat.Shape.STRING, timezone = "GMT+8")
  private Date testTime;
}

==> 
back-end value:  testTime=Wed Aug 26 18:42:12 CST 2020

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

table 複合主鍵 同時使用 JAXB annotation設定

  • 主pojo set @Id@IdClass(xxx.class)、並設定@XmlElement
/**
 *主檔
 */
@Entity
@lombok.Data
@lombok.ToString
@Table(name="STORE_INFO")
@XmlAccessorType(XmlAccessType.FIELD)
@IdClass(StoreInfoPK.class)
public class StoreInfo implements Serializable {

  private static final long serialVersionUID = 1L;
  
  @Id
  @XmlElement(name = "StoreId")
  private String storeId;
  
  @Id
  @XmlElement(name = "CreateTime")
  private Date createTime;

  /**
   * 店鋪店名
   */
  @XmlElement(name = "StoreName")
  @Column(name = "STORE_NAME")
  private String storeName;

  public SupStoreInfo() {}

}

table 複合主鍵 並用 JAXB annotation設定

  • PK pojo set @Column
/**
 *PK
 */

@lombok.Data
@lombok.ToString
public class StoreInfoPK implements Serializable {

  private static final long serialVersionUID = 1L;

    @Column(name="STORE_ID")
    private String storeId;

    @Column(name="CREATE_TIME")
    @Temporal(TemporalType.DATE)
    private Date createTime;
    
    public StoreInfoPK() {
    }
}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

 @Test
 public void tryremove() throws Exception {
    List<String> list = new ArrayList<String>();
    list.add("9");list.add("888");list.add("846");list.add("654");list.add("844");
    System.out.println("list: " + StringUtils.join(list, ","));
    
    if(CollectionUtils.isNotEmpty(list)){
      Iterator<String> it = list.iterator();
      while(it.hasNext()){
        String temp = it.next();
        System.out.println(temp);
        
        if(temp.startsWith("84")) {
          it.remove();
        }
      }
      
      System.out.println("list: " + StringUtils.join(list, ","));
    }
  }

//console:
list: 9,888,846,654,844
9
888
846
654
844
list: 9,888,654

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

Returns an immutable collection containing only the specified object. The returned set is serializable.
/**
 * Set<T> java.util.Collections.singleton(T var0)
 * https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#singleton-T-
 */
Set<String> aa = Collections.singleton("AA");


/**
 * List<T> java.util.Collections.singletonList(T var0)
 * https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#singletonList-T-
 */
List<String> bb = Collections.singletonList("BB");


/**
 * Map<K, V> java.util.Collections.singletonMap(K var0, V var1)
 * https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#singletonMap-K-V-
 */
Map<String, String> cc = Collections.singletonMap("CCKey", "CCVal");

 

 

refer:

https://stackoverflow.com/questions/4801794/use-of-javas-collections-singletonlist
https://stackoverflow.com/questions/31599467/what-is-the-benefit-for-collections-singleton-to-return-a-set-instead-of-a-col
 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

1 23