youtube data API(v3)

https://developers.google.com/youtube/v3/getting-started?hl=ja

Youtube apiを使うには、cloud consoleで、プロジェクトの登録が必要となります。
https://console.developers.google.com/projectcreate
新しいプロジェクトを作りましょう。

ここでは、nameは[youtube-app]とします。
そして、サービスからYouTube Data API(v3)を有効にします。

リソースの種類
activity, channel, channelBanner, playlist, playlistItem, search result, subscription, thumbnail, video, videoCategory

操作
list: リソースのリストをGET
insert: 新しいリソースをPOST
update: 既存のリソースをPUT
delete: リソースをDELETE

サポートされる操作
activity, caption, channel, channelBanner, channelSection, comment, commentThread, guideCategory, i18nLanguage, i18nRegion, playlist, playlistItem, search result, subscription, thumbnail, video, videoCategory, watermark

partパラメーター:リソースを取得する API リクエストまたはリソースを返す API リクエストに対して必須のパラメータ。API レスポンスに含める必要がある 1 つ以上の最上位レベルのリソース プロパティを指定。

fieldsパラメーター:fields パラメータは API レスポンスをフィルタリングし、part パラメータ値で指定されたリソース パーツだけが含まれるようにする。

youtubeのiframe

youtubeの動画埋め込みは、iframe。
iframeとは、HTML文書の中に別のHTML文書を埋め込むもので、ウェブサイト上にドキュメントを埋め込むようなもの。 つまり、iframeを使用すると、別のソースからのコンテンツをパーツとして挿入することができる。

<iframe width="560" height="315" src="https://www.youtube.com/embed/UF8uR6Z6KLc" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

ニコニコ動画の動画埋め込みも、iframeです。

<iframe width="312" height="176" src="https://ext.nicovideo.jp/thumb/sm32606159" scrolling="no" style="border:solid 1px #ccc;" frameborder="0"><a href="http://www.nicovideo.jp/watch/sm32606159">日経225先物デイトレードプラン 2018/1/19</a></iframe>

index.jsp

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>
	<head>
		<meta charset="utf-8">
		<title>Welcome</title>
	</head> 
	<body>
		<h1>Sample Page</h1>
		<pre>${mybean}</pre>
		<hr>
		<form action="sample" method="post">
			<input type="text" id="message" name="message">
			<input type="submit" value="add">
		</form>
	</body>
</html>

javax.servlet.annotation.WebServletをimport出来ないとき

STSで
The import import javax.servlet.annotation cannnot be resolved と表示された時。

import javax.servlet.annotation.WebServlet;

javax.servlet.annotation.WebServlet は Servlet 3.0以上でないと使えません。
pom.xmlのservlet.versionを確認ください。

		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>2.5</servlet.version>
		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>3.1.0</servlet.version>

サーブレット

package jp.spring.websample1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Servlet implementation class MySampleServlet
 */
@WebServlet("/sample")
public class MySampleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	ApplicationContext app;
	@Override
	public void init() throws ServletException {
		super.init();
		app = new ClassPathXmlApplicationContext("/spring/application-config.xml");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		MyBean mybean1 = (MyBean)app.getBean("mybean1");
		request.setAttribute("mybean", mybean1);
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String message = request.getParameter("message");
		MyBean mybean1 = (MyBean)app.getBean("mybean1");
		mybean1.addMessage(message);
		response.sendRedirect("sample");
	}

}

STSからwebサーバー

サーバーにプロジェクトを追加
Pivotal tc Server Developer Edition…
Add and Remove

スタートアイコンよりサーバーを起動
http://localhost:8080/MySampleWebApp1/

pom.xml

<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>org.springframework.samples.service.service</groupId>
  <artifactId>MySampleWebApp1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <properties>

		<!-- Generic properties -->
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		
		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>2.5</servlet.version>
		

		<!-- Spring -->
		<spring-framework.version>3.2.3.RELEASE</spring-framework.version>

		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>

		<!-- Test -->
		<junit.version>4.11</junit.version>

	</properties>
	
	<dependencies>
	
		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		
		<!-- Other Web dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>
	
		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>
		
		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>	
</project>

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>MySampleWebApp1</display-name>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
</web-app>
package jp.spring.websample1;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class MyBean {
	private List<String> messages = new ArrayList<String>();
	
	public MyBean() {
		super();
		messages.add("This is Bean sample.");
	}
	
	public void addMessage(String message) {
		messages.add(message);
	}
	
	public String getMessage(int n) {
		return messages.get(n);
	}
	
	public void setMessage(int n, String message) {
		messages.set(n, message);
	}
	
	public List<String> getMessage(){
		return messages;
	}
	
	public void setMessages(List<String> messages) {
		this.messages = messages;
	}
	
	@Override
	public String toString() {
		String result = "MyBean [\n";
		for(String message : messages) {
			result += "\t'" + message + "'\n"; 
		}
		result += "]";
		return result;
	}
}

Create Spring Bean Configuration File

bean.xmlを生成します。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>

beanを追加

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="mybean1" class="jp.spring.sample1.MyBean">
	<property name="message" value="this is sample bean!"></property>
</bean>
</beans>

app.javaを書き換えます

package jp.spring.sample1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

	private static ApplicationContext app;
	
	public static void main(String[] args) {
		app = new ClassPathXmlApplicationContext("bean.xml");
		MyBean bean = (MyBean)app.getBean("mybean1");
		System.out.println(bean);
	}
}

spring beanの利用

classを作ります。

package jp.spring.sample1;

import java.util.Calendar;
import java.util.Date;

public class MyBean {
	private Date date;
	private String message;
	
	public MyBean() {
		super();
		this.date = Calendar.getInstance().getTime();
	}
	public MyBean(String message) {
		this();
		this.message = message;
	}
	
	public Date getDate() {
		return date;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	@Override
	public String toString() {
		return "MyBean [message=" + message + ", date=" + date + "]";
	}

}

App.java

package jp.spring.sample1;

public class App {

	public static void main(String[] args) {
		MyBean bean = new MyBean("This is Bean Sample!");
		System.out.println(bean);
	}
}

console

MyBean [message=This is Bean Sample!, date=Thu Jan 18 14:03:34 JST 2018]

maven class

\MySampleApp1\src\main\java\jp\spring\sample1

package jp.spring.sample1;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

pom.xml

<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>jp.spring.sample1</groupId>
  <artifactId>MySampleApp1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MySampleApp1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Java Springのコア機能

Dependency Injection
あるクラスの処理が、他の特定のクラスに依存している状態を解消することがDIの目的です。

それでは、mavenでプロジェクトを作成していきます。
コマンドプロンプトでmvnコマンドを実行します。

>mvn archetype:generate

Define value for property 'groupId': jp.spring.sample1
Define value for property 'artifactId': MySampleApp1
Define value for property 'version' 1.0-SNAPSHOT: :
Define value for property 'package' jp.spring.sample1: :
Confirm properties configuration:
groupId: jp.spring.sample1
artifactId: MySampleApp1
version: 1.0-SNAPSHOT
package: jp.spring.sample1
 Y: :
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\***\Desktop
[INFO] Parameter: package, Value: jp.spring.sample1
[INFO] Parameter: groupId, Value: jp.spring.sample1
[INFO] Parameter: artifactId, Value: MySampleApp1
[INFO] Parameter: packageName, Value: jp.spring.sample1
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\***\Desktop\MySampleApp1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10:03 min
[INFO] Finished at: 2018-01-17T15:32:23+09:00
[INFO] Final Memory: 14M/75M
[INFO] ------------------------------------------------------------------------