Java パラメーターの種類

@FormParam

<form>
    <input name = "email">
    <input name = "password">

    <input type = "submit">
</form>


emailpasswordの部分にあたるものがパラメーターとして送られてくる。



@QueryParam

ブラウザから送るURLにある?以降がパラメーターになる。
ex) http://xxxx.com/hoge?email=hoge@xxx.jp&password=“pass”



@PathParam

URLが下記の時、
ex) http://xxxx.com/hoge/1

APIの方で指定しているresource
/hoge/{ id }の部分と対応していて、パラメーターはid = 1になる。

.ymlにあるhttpClientとは

そもそもHTTPとは

WebクライアントとWebサーバーの送受信において使われる取り決めのこと。
リクエスト・レスポンスのルール。


Webアクセスの流れ
  1. ユーザーがURLを入力する

  2. HTTPリクエストが、サーバーに送られる

  3. サーバーがHTTPリクエストを読み取って要求内容を分析する

  4. 要求されたデータを返す(HTTPレスポンス)

  5. Webブラウザが、サーバーからのデータを解析して、WebページとしてPCに表示する



connectionTimeout

クライアントからサーバーへの接続が確立するまで待って諦めるまでの時間。
1000ms = 1秒



timeout

接続後のデータ取得をするために待って諦めるまでの時間。

dropwizard + Gradle

  • Eclipse Marketplaceでgradleをインストール

  • 新規プロジェクト作成の時に「Gradle(STS)」を選択して作成。

  • build.gradleを編集。

apply plugin: 'idea'
apply plugin: 'java'

def defaultEncoding = 'UTF-8'
def jdkVersion = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compile 'io.dropwizard:dropwizard-core:1.0.3'
    compile 'io.dropwizard:dropwizard-configuration:1.0.3'
}

compileJava {
    options.encoding = defaultEncoding
}
compileTestJava {
    options.encoding = defaultEncoding
}

idea {
    project {
        jdkName = jdkVersion
        languageLevel = jdkVersion
    }
}

jar {
    from (configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
        exclude 'META-INF/MANIFEST.MF'
        exclude 'META-INF/*.SF'
        exclude 'META-INF/*.DSA'
        exclude 'META-INF/*.RSA'
    }
    manifest {
        attributes('Main-Class': 'org.gradle.service.HelloWorldService')
    }
}
  • gradle jarを叩く。

  • プロジェクトを右クリックしてGradle(STS)> Refresh Dependenciesを選択。
    これでdependenciesが反映される。

  • クラスの内容を、Dropwizard入門 - Qiitaに従って書いていく。

  • java -jar build/libs/gtest.jar server hello-world.ymlで実行。




エラー

java -jar build/libs/gtest.jar server hello-world.ymlを実行すると

エラー: メイン・クラスorg.gradle.service.HelloWorldServiceが見つからなかったかロードできませんでした

と出てくる。

HelloWorldServiceクラスは存在するのにさあどうして。




解決

gradle build

からの

java -jar build/libs/gtest.jar server hello-world.yml

で再びエラー

hello-world.yml has an error:
  * Failed to parse configuration at: logging.appenders.[0]; Could not resolve type id 'console' into a subtype of [simple type, class io.dropwizard.logging.AppenderFactory<ch.qos.logback.classic.spi.ILoggingEvent>]: known type ids = [AppenderFactory]
 at [Source: N/A; line: -1, column: -1] (through reference chain: org.gradle.configuration.HelloWorldConfiguration["logging"]->io.dropwizard.logging.DefaultLoggingFactory["appenders"]->java.util.ArrayList[0])



hello-world.ymlのlogginappendersコメントアウト

hello-world.ymlファイル

template: "Hello, %s!"

# use the simple server factory if you only want to run on a single port

server:
  applicationConnectors:
    - type: http
      port: 28080
  adminConnectors:
    - type: http
      port: 28081

## logging settings.
#logging:
#
#  # the default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.
#  level: DEBUG
#
#  appenders:
#    - type: console
#      timeZone: JST

コマンドで再び

java -jar build/libs/gtest.jar server hello-world.yml

http://localhost:28080/hello?name=hogeにアクセスすると
{"message":"Hello, hoge!"}と無事表示されました。

503エラー

エラー内容

サーバーの過負荷状態で一時的にWebページが表示できないときに起こるエラー。 これ以上無理!というサーバーからの警告。




原因/対処法

  • サーバーの負荷チェック
  • 時間を置いて再度アクセス
  • サーバーの転送量を上げる
  • サーバーの負荷を無理に上げてしまうプログラムがないか確認する
  • サーバー管理者へ連絡する

Java AmazonAPIを使って検索したものをとってくる

したいこと

書籍のジャンルの中で、「ペン」と調べた時に出てくる書籍のタイトルを表示させる。




サンプルコード

ItemLookupSample.java

package test;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ItemLookupSample {

    private static final String AWS_ACCESS_KEY_ID = "アクセスキー";
    private static final String AWS_SECRET_KEY = "シークレットキー";
    private static final String ASSOCIATE_TAG = "";
    private static final String ENDPOINT = "ecs.amazonaws.jp";

    public static void main(String[] args) {
        /*
         * Set up the signed requests helper 
         */
        SignedRequestsHelper helper;
        try {
            helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, ASSOCIATE_TAG);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        
        String requestUrl = null;
        String title = null;

        System.out.println("Map form example:");
        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("Version", "2009-03-31");
        params.put("Operation", "ItemSearch");
        params.put("ResponseGroup", "Small");
        params.put("AssociateTag", ASSOCIATE_TAG);
        params.put("SearchIndex", "Books");
        params.put("Keywords", "ペン");

        requestUrl = helper.sign(params);
        System.out.println("Signed Request is \"" + requestUrl + "\"");

        title = fetchTitle(requestUrl);
        System.out.println("Signed Title is \"" + title + "\"");
        System.out.println();

    }

    
    private static String fetchTitle(String requestUrl) {
        String titles = null;
        
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(requestUrl);
            
                NodeList titleNodes = doc.getElementsByTagName("Title");
                int titleNum = titleNodes.getLength();
                
                for(int i=0; i < titleNum; i++) {
                    Node titleNode = titleNodes.item(i);
                    String title = titleNode.getTextContent();
                    System.out.println(title);
                }
                
                

            } catch (Exception e) {
            throw new RuntimeException(e);
            }
        return titles;
    }

}




結果

Pen(ペン) 2016年 11/15 号 [ハリー・ポッター完全読本。]
Pen(ペン) 2016年 11/1号 [ゴッホ、君は誰?]
ペン太のこと(8): イブニング
【音声ペン付き】ペンがおしゃべり!  英検に役立つ 小学えいご絵じてん800 改訂版
30日できれいな字が書けるペン字練習帳 (TJMOOK)
【音声ペン付き】ペンがおしゃべり! ベビー&キッズえいご絵じてん500 改訂版
ワンランク上の美文字が書ける!!  極める!  ペン字・筆文字練習帳 (COSMIC MOOK)
Pen(ペン) 2016年 12/1 号 [雑誌]
【音声ペン付き】ペンがおしゃべり!  えいご絵じてんプレミアムセット 改訂版
大人の筆ペン字練習帳 春夏秋冬、季節のおたより篇
Signed Title is "null"




注意点

リクエスト制限が1時間に3600回以下らしいので
設計に工夫が必要になるね〜