ラベル java の投稿を表示しています。 すべての投稿を表示
ラベル java の投稿を表示しています。 すべての投稿を表示

2022/02/20

mac java version

久しぶりにJavaを触った。

many many jdks ...so how to mange so many jdks


  • show jdks version on your mac pc
    /usr/libexec/java_home -V

  • env is a good idea. 
    • python->pyenv
    • node->nodenv
    • ruby->rbenv
    • golang->gvm
    • java->jenv

  • install jenv
      brew install jenv
     export JENV_ROOT="$HOME/.jenv"
    echo 'eval "$(jenv init -)"' >> ~/.bash_profile
    source ~/.bash_profile
    jenv doctor

  • add jdk path to jenv
    jenv add /Library/Java/JavaVirtualMachines/jdk-12.0.2.jdk/Contents/Home

  • use some version
    jenv local 11     

2022/02/16

Gradle The JavaExec.main property has been deprecated

deprecated gradle features were used in this build, making it incompatible with gradle 8.0.


 => add ↓ to gradle.properties

org.gradle.warning.mode=all


then 

he JavaExec.main property has been deprecated


change build.gradle


plugins {
id "application"
}
apply plugin : "java"
application {
mainClass = 'xxx.xxx'
}

then 

gradle run

2017/04/19

eclipse error

workspace\.metadata/.log

eclipse.exe -clean

治らない。。

marketplaceのおすすめがおるさい。。
general ->editer->関連付けられていないファイルのオープンを「text editor]にする

2016/01/21

HttpResponse Stream


あまり情報がないので、
 
★The respone entity is always not null and is stream,so the 
  releaseConnection method cant be invoked always.
  
  
   final HttpEntity entity = response.getEntity(); 
  if (entity == null || !entity.isStreaming()) { 
 
★ 

  1. Using EntityUtils and HttpEntity
    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
  2. Using BasicResponseHandler
    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
     
     
    基本なことね、恥ずかしい、全てのresponeはStreamみたいなので
    、また調べる 

2015/06/06

改行コード DB java client?

つまらないことですが、思う通り行かない困るね。。。
世の中そんなことが多いと思いますが、
そんなことに時間を取られて、結局つまらないね。。。

DBに下記をinsert
 "今日は土曜日。\n明日は日曜日"
改行したいです!!

javaでoutPutして見る
System.out.print(description);
==> "今日は土曜日。\n明日は日曜日"

値は\\nになっている。


じゃ。。。

DB  "今日は土曜日。rn明日は日曜日"
JAVA 
        product.setDescription(product.getDescription().replaceAll("rn", "\n"));
System.out.println(product.getDescription());
==>
OK!!

2015/05/29

時間 intergerで表示 java

    long now = System.currentTimeMillis();
==>1432909782064 13桁!

十桁で時間を表示する?
例: 1336383401 (2012-05-07 09:36:41Z)
UNIX時間 
10ケタの秒数で年月日時分秒すべて表現する

何が違う????

秒の表示とミリ秒の表示かな!!?
10            13

じゃ、13桁の方を1000で割り、で比較できるね!!!

2015/04/25

MultipartEntityBuilder and Charset

日本語化けになっている。。
 
 
entity.addTextBody("plain_text", plain_text);
will use the default ContentType.TEXT_PLAIN which look like this...
public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", Consts.ISO_8859_1);

while ContentType.APPLICATION_JSON is using UTF-8 as below
public static final ContentType APPLICATION_JSON = ContentType.create("application/json", Consts.UTF_8);

So what i did was create our own ContentType like this..
entity.addTextBody("plain_text", plain_text, ContentType.create("text/plain", MIME.UTF8_CHARSET));

MultipartEntityBuilder: Omit Content-Type and Content-Transfer

What I want (what my chrome browser does):
POST .../some.jsp HTTP/1.1
Host: ...
Connection: keep-alive
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6tcnkxC7txvqE5Xl


------WebKitFormBoundary6tcnkxC7txvqE5Xl
Content-Disposition: form-data; name="merkmal"

5
What I get from MultipartEntityBuilder
POST.../some.jsp HTTP/1.1
Host: ...
Content-Type: multipart/form-data; boundary=m9Zb2QD-QaH-j-HqgGQfI8KwDkToz17ULYkZ

--m9Zb2QD-QaH-j-HqgGQfI8KwDkToz17ULYkZ
Content-Disposition: form-data; name="merkmal"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit

===>
 lright - intense googeling finally produced an answer.

1) There are apparently some servers that do not get on well with the "Content-Transfer-Encoding" header.
2) There is a browser compatibility mode in HttpComponents that is used like this:
MultipartEntityBuilder uploadEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

2015/04/19

java Strings.format 特殊文字

書式 説明 例
% 指定を開始する。「%」自身を出力したい場合は「%%」とする。 printf("%%%n"); %
d 整数を十進数で出力する。(nullの時は「null」) printf("%d%n", 123); 123
o 整数を八進数で出力する。(nullの時は「null」) printf("%o%n", 123); 173
x 整数を十六進数で出力する。(nullの時は「null」) printf("%x%n", 123); 7b
c 文字を出力する。(nullの時は「null」) printf("%c%n", 'x'); x
s 文字列を出力する。(nullの時は「null」)
(toString()あるいはFormattableで文字列に変換される)
printf("%s%n", "xyz"); xyz
- 左詰で出力する(省略時は右詰)。 printf("[%-4d]%n", 123);
printf("[%-4s]%n", "xyz");
[123 ]
[xyz ]
0 足りない桁数を0埋めする。
数値系(%d,%o,%x)で使用可能。[2009-10-21]
他(例えば%s,%b,%h)では使用不可(例外が発生する)。
printf("%04d%n", 123);
printf("%04x%n", 123);
0123
007b
# 代替フォームで変換する。
すなわち、「%o」において頭に「0」を、「%x」において頭に「0x」を付けて出力する。
「%s」の場合はデフォルトでは特に何も無さそう。「%d」では例外が発生する。
printf("%#o%n", 123);
printf("%#x%n", 123);
printf("%#s%n", 123);
0173
0x7b
123
数 桁数(最小フィールド幅)を指定する。
最低限確保される桁数であり、この数値以上の桁の値は全部出力される。
→%s(文字列)の場合は、文字数である
printf("[%4d]%n", 123);
printf("[%4s]%n", "xyz");
printf("[%4s]%n", "xyzab");
printf("[%4s]%n", "あいう");
[ 123]
[ xyz]
[xyzab]
[ あいう]
.数 精度(最大表示幅)を指定する。
この桁数より大きい場合は切り捨てられ、出力されない。
→%s(文字列)の場合は、文字数である
printf("[%.4s]%n", "xyzab");
printf("[%5.4s]%n", "xyzab");
printf("[%-5.4s]%n", "xyzab");
printf("[%-5.4s]%n", "あいうえお");
[xyza]
[ xyza]
[xyza ]
[あいうえ ]
数$ 引数の番号を指定する(値の引数のうち、一番左が1)。
通常これは省略されており、その場合は引数の並び順に従って値が出力される。
→C言語とJavaの違い
printf("%d:%d:%d%n",11,22,33);
printf("%1$d:%2$d:%3$d%n",11,22,33);
printf("%3$d:%2$d:%1$d%n",11,22,33);
printf("%3$d:%1$d:%d%n",11,22,33);
11:22:33
11:22:33
33:22:11
33:11:11

2015/04/07

htmlClient EntityUtils.consume?? why

try {

    //... some code

    HttpEntity httpEntity = httpResponse.getEntity();
    BufferedReader br = new BufferedReader(new InputStreamReader(http.Entity.getContent()));
    String line;
    while ((line = br.readLine())!= null) {
        System.out.println(line);
    }
    EntityUtils.consume(httpEntity);
} catch (Exception e) {
    //code
} finally { 
    httpClient.getConnectionManager().shutdown();
}
 
 What EntityUtils.consume will do is release all resources held by the httpEntity,
 which essentially implies releasing any underlying Stream and giving 
the Connection object back to its pool (in the case your connection 
manager is a multithreaded one) or freeing the connection manager so 
that it can process the next request.


何かメモリを開放するみたいね

2015/04/05

java ssl charles

httpClientからhttpsを接続する時、firefox/iosのように証明書が必要....

$JAVA_HOME/jre/lib/security/cacerts, where JAVA_HOME is your java home directory for the JVM you’re using.

keytool -import -alias charles -file charles-proxy-ssl-proxying-certificate.crt -keystore JAVA_HOME/jre/lib/security/cacerts -storepass changeit

(changeit is the default password on the cacerts file)
Then try: keytool -list -keystore JAVA_HOME/jre/lib/security/cacerts -storepass changeit

2014/10/26

eclipse jdk os 32bit/64bit

I am confusing with that
I think if the os is 32bit ,then jdk,eclipse also 32bit 
64bit the same
but .....
there is a lot aborting ...
i am wrong? they are wrong?

eclipse-java-luna-SR1-win32-x86_64
window7 64bit
jdk-8u20-windows-x64


i think it will  be ok
but ....


oh ,this time it goes oK! I uninstall all the jdk,and reinstall them

2014/08/18

2014/07/03

JavaScript EventSource

・どこの仕様?Server-Sent Eventsで
var source = new EventSource("/chatFeed/");

# receive messages
$scope.chatFeed.addEventListener("message", $scope.addMsg, false);
/** handle incoming messages: add to messages array */
    $scope.addMsg = function (msg) {
        $scope.$apply(function () { $scope.msgs.push(JSON.parse(msg.data)); });
    };

・サーバー側は、必ず text/event-stream という MIME type で返さなければならない。
 /** Controller action serving activity based on room */
  def chatFeed(room: String) = Action { req =>
    println(req.remoteAddress + " - SSE connected")
    Ok.feed(chatOut
      &> filter(room)
      &> Concurrent.buffer(50)
      &> connDeathWatch(req.remoteAddress)
      &> EventSource()
    ).as("text/event-stream")
  }
 
==>
handle data streams reactively
I know, the method's name "&>" can make some of you go away. Please stay! This sign is like the pipe in bash. It is very easy to understand:
fileLineStream(file) &> lineParser
==>fileLineStream(file).through(lineParser)


Server-Send Events
When we want to send events in "real time" to the browser, what technologies are available?

    polling: the browser pools the server every x milliseconds to check if there is a new message. This method is not very efficient, because a lot of requests are necessary to give the illusion to update the application in real time.
    long-polling (or Comet): the browser opens a connection to the server (for example in a iframe), and the server keeps the connection opened. When the server wants to push data to the client, it sends this data with the opened connection. The client receives the data, and opens a connection again for further messages. With this method, the browser is always showing that it is waiting for data. This technology does not scale on threaded system, as each opened connection uses a thread. In JEE environment, we need an asynchronous servlet 3.1 not to make the server exploding.
    Server-Send Events (SSE) are quite similar to Comet. The main difference is that the browser manages this connection. For example, it opens the connection again if it falls.
    WebSockets provide a bi-directional, full-duplex communications channels. It is a different protocol than HTTP.

I choose to use Server-Send Events instead of WebSockets because of the following reasons:

    I've already played with WebSockets and wanted to try something new.
    WebSockets are great and can communicate in both directions. But this technology is a new protocol, sometimes difficult to integrate in an existing infrastructure (Proxy, Load-Balancer, Firewall...) Server-Send Events, on the other hand, use the HTTP protocol. The PaaS Heroku does not support WebSockets yet, but support SSE. When pushing data from the server to clients is all what you need, SSE can be what is the most appropriate and is well supported (except in IE for the moment)

2014/06/27

java Fork/Join

★The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.
===>それはいいね!!



★例:

package testfork;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class MaximumFinder extends RecursiveTask {

    private static final int SEQUENTIAL_THRESHOLD = 100;

    private final int[] data;
    private final int start;
    private final int end;

    public MaximumFinder(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    public MaximumFinder(int[] data) {
        this(data, 0, data.length);
    }

    private Integer computeDirectly() {
        System.out.println(Thread.currentThread() + " computing: " + start
                + " to " + end);
        int max = Integer.MIN_VALUE;
        for (int i = start; i < end; i++) {
            if (data[i] > max) {
                max = data[i];
            }
        }
        return max;
    }

    @Override
    protected Object compute() {
        final int length = end - start;
        if (length < SEQUENTIAL_THRESHOLD) {
            return computeDirectly();
        }
        final int split = length / 2;
        final MaximumFinder left = new MaximumFinder(data, start, start + split);
        left.fork();
        final MaximumFinder right = new MaximumFinder(data, start + split, end);
        return Math.max((Integer) right.compute(), (Integer) left.join());
    }

    public static void main(String[] args) {
        // create a random data set
        final int[] data = new int[100000];
        final Random random = new Random();

        for (int i = 0; i < data.length; i++) {
            data[i] = random.nextInt(100);
        }

        // submit the task to the pool
        final ForkJoinPool pool = new ForkJoinPool(4);
        final MaximumFinder finder = new MaximumFinder(data);
        System.out.println(pool.invoke(finder));
       
    }
}


★ForkJoinPoolに入れるタスクはForkJoinTask型であるが、実際にはRecursiveTaskかRecursiveActionのいずれかから派生するのが便利である。
RecursiveTaskは戻り値のあるタスク、RecursiveActionは戻り値が無いタスクを定義するのに使う。

★Callable, RunnableをForkJoinTaskに変換するためのForkJoinTask.adapt()メソッドを使うこともできる

★
ForkJoinPool pool = new ForkJoinPool(
 Runtime.getRuntime().availableProcessors(),
 ForkJoinPool.defaultForkJoinWorkerThreadFactory,
 null,
true); // タスクの積み上げにFIFOモードを使用する.(通常はSTACKモード)

Why reduce the size of the Java JVM thread stack

★あれ、threadStack is out of heap...

When Java creates a new thread, it pre-allocates a fixed-size block of memory for that thread's stack. By reducing the size of that memory block, you can avoid running out of memory, especially if you have lots of threads - the memory saving is the reduction in stack size times the number of threads.

The downside of doing this is that you increase the chance of a Stack Overflow error.

Note that the thread stacks are created outside of the JVM heap, so even if there's plenty of memory available in the heap, you can still fail to create a thread stack due to running out of memory (or running out of address space, as Tom Hawtin correctly points out).

2014/06/24

java オブジェクト指向 デメリット



所有使用Java的人都喜欢“用例”,所以让我们以一个用例开始吧:倒垃圾。就像这样:“Johnny,快去倒垃圾,他都快溢出来了!”
我们的生活也同时充斥着各种“名词”。我们吃“名词”(食物),我们从商店买“名词”(商品),我们坐在“名词”(凳子)上。 “名词”(石头)可能会忽 然砸到你头上,在你的“名词”(头)上弄一个“名词”(大包)。 名词即事物,想想没有了事物我们会怎样? 但他们仅仅只是事物,比如: 意味着结束或者 结束本身,或者一些贵重物品,或者我们周围经常看到的事物的名字。 这是一座建筑,那是一个石头。任何一个小孩子都能指出名词,仅此而已。 发生在名词身 上的 “变化”才是最有趣的事情。
变化需要动作。 动作是生活的调料。 动作甚至给了调料以调料! 毕竟除非你“吃”它,你是不会感到香这种味道的。 名词也许无处不在,但是生活一直在变并一直有趣的功劳还是在于动词、
当然,除了名词和动词,我们还有形容词,介词,代词,冠词,连词,语气词,和许许多多其他让我们构造有趣语言的词汇。 它们都在语言中扮演着自己的角色,而且每一个都很重要。 如果它们哪一个不存在了的话,那是挺遗憾的事情。
面向对象
StateManager.getConsiderationSetter(“Noun Oriented Thinking”, State.HARMFUL).run()
或者, 正如外面的世界所说,“面向名词的思考是有害的”
面向对象的编程把名词放到首位,但是我们为什么非得把名词捧上神坛以至于让语句变的如此啰嗦哪? 为什么一种语句成分的低位非得高于另外一种?这并不是好 像面向对象的编程突然使得动词的低位降低,正如我们认为的那样。 这是一种奇怪的认识的扭曲。 正如我的朋友 Jacob Gabrielso一次说到, 提倡面向对象的编程好比提倡面向裤子的穿衣方式。
类是Java中唯一提供的建模的工具。 所以当一个新的想法出现在你脑海的时候,你不得不重塑它,包装它,甚至弄碎它直到它变成一个名词, 即使它开始是一个动作,过程,或者任何其他不是“物”的概念。
我似乎回到了8,9年前一帮搞Perl的家伙对我说的:“伙计,并不是所有的东西都是对象的。”
很奇怪,Java似乎是主流面向对象语言中唯一一个完全以名词为中心的语言。 在Python或者Ruby中,你不会找到 AbstractProxyMediator,NotificationStrategyFactory或者其他类似的东西。 为什么在Java中它们满 地都是? 我敢打赌这是原因出在了动词的身上。 Python,Ruby,JavaScript,Perl当然,还有所有的函数式编程语言允许你声明并传 递函数而不用用类包装它。Java没有理由不简单地添加第一类函数并最终实现一个成熟的,没有扭曲的可以让人自由运用动词来实现他们想法的世界。 实际上,有一个基于JVM叫 做 The Nice programming language 的语言实现了一个非常类似Java的语法, 并包含了一个非常具有表现力的实现了使用 动词方式:独立函数。 而Java强制你用Callback,Ruunable或其他匿名接口来包装它为一个类以便于调用。

Sun
公司甚至没有打破他们一切函数都必须被类拥有的信条。 任何匿名的函数都会具有一个隐式的this指针指向定义它的类;问题解决了。