runnable()

run();
オブジェクトが実装するインタフェース Runnable を使ってスレッドを作成し、そのスレッドを開始すると、独立して実行されるスレッド内で、オブジェクトの run メソッドが呼び出される。

class Playground {
private static class Thread {
@Override
public void run(){
for (int i = 0; i < 20; i++){ System.out.println(i + ":" + this.hashCode()); } } } public static void main(String[ ] args) { Thread t1 = new MyThread(); Thread t2 = new MyThread(); t1.start(); t2.start(); } } [/java]

rfc5322 3.4.1. Addr-Spec Specification

メールアドレスの仕様
https://tools.ietf.org/html/rfc5322#page-17

以下抜粋
—-
An addr-spec is a specific Internet identifier that contains a
locally interpreted string followed by the at-sign character (“@”,
ASCII value 64) followed by an Internet domain. The locally
interpreted string is either a quoted-string or a dot-atom. If the
string can be represented as a dot-atom (that is, it contains no
characters other than atext characters or “.” surrounded by atext
characters), then the dot-atom form SHOULD be used and the quoted-
string form SHOULD NOT be used. Comments and folding white space
SHOULD NOT be used around the “@” in the addr-spec.

addr-spec = local-part “@” domain

local-part = dot-atom / quoted-string / obs-local-part

domain = dot-atom / domain-literal / obs-domain

domain-literal = [CFWS] “[” *([FWS] dtext) [FWS] “]” [CFWS]

dtext = %d33-90 / ; Printable US-ASCII
%d94-126 / ; characters not including
obs-dtext ; “[“, “]”, or “\”
——-
使えるのは、半角英数字か、「!#$%&’*+-/=?^_`{|}~」
で、正規表現で書くと、

^[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+(\.[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+)*@[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+(\.[\w!#%&'/=~`\*\+\?\{\}\^\$\-\|]+)*$

実際に試してみる。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Playground {
    public static void main(String[ ] args) {
        
        String str = "hogehogehoge.jp";
        
        Pattern p = Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$");
        Matcher m = p.matcher(str);
        
        if(m.find() == true){
            System.out.println("OK");
        } else{
            System.out.println("NG");
        }
        
    }
}

NGとなる。

メールアドレスの判定をする。

public void getScore(View view){


        // edittextを取得
        EditText fEditText = (EditText) findViewById(R.id.firstnEditText);
        EditText lEditText = (EditText) findViewById(R.id.lastnEditText);
        EditText pEditText = (EditText) findViewById(R.id.phoneEditText);
        EditText mEditText = (EditText) findViewById(R.id.mailEditText);
        // edittextの中身を取得
        String firstName = fEditText.getText().toString().trim();
        String lastName = lEditText.getText().toString().trim();
        String myPhone = pEditText.getText().toString().trim();
        String myMail = mEditText.getText().toString().trim();

        Pattern p = Pattern.compile("^[0-9\\-]+");
        Matcher m = p.matcher(myPhone);

        Pattern mp = Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\\\.[a-zA-Z0-9-]+)*$");
        Matcher mm = mp.matcher(myMail);

        // 中身を観て条件分岐
       if (firstName.equals("")){
             fEditText.setError("Please enter your first name!");
        } else if(lastName.equals("")){
           lEditText.setError("Please enter your last name!");
        } else if(myPhone.equals("") || m.find() == false){
           pEditText.setError("Please enter your phone number!");
        }else if(myMail.equals("") || mm.find() == false){
           mEditText.setError("Please enter your valid email");
        } else {
            Intent intent = new Intent(this, MyResult.class);
            intent.putExtra(EXTRA_MYNAME, firstName);
            startActivity(intent);
        }
    }

郵便番号の正規表現

String str = "333-5555";
Pattern p = Pattern.compile("^[0-9]{3}-[0-9]{4}$");

ハイフンがない固定電話の電話番号なら、

Pattern p = Pattern.compile("^[0-9]{10}$");

携帯と固定電話の混入ならワイルドカード

Pattern p = Pattern.compile("^[0-9]*$");

ハイフンと数字なら、ハイフンをエスケープする

Pattern p = Pattern.compile("^[0-9\\-]+");

これをMainActivity.javaに入れてEditTextの判定したい。

java正規表現2

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Playground {
    public static void main(String[ ] args) {
        
        String str = "123A5";
        
        Pattern p = Pattern.compile("^[0-9]*$");
        Matcher m = p.matcher(str);
        
        System.out.println(m.find());
    }
}

falseになります。
Pattern p = Pattern.compile(“^[0-9]”); とすればtrue
123の次にAが入っているので、Pattern p = Pattern.compile(“^[0-9a-zA-Z]*$”);とすれば、trueに変わります。

if else文で書きます。

public static void main(String[ ] args) {
        
        String str = "123A5";
        
        Pattern p = Pattern.compile("^[0-9a-zA-Z]*$");
        Matcher m = p.matcher(str);
        
        if(m.find() == true){
            System.out.println("OK");
        } else{
            System.out.println("NG");
        }
        
    }

javaの正規表現


class Playground {
    public static void main(String[ ] args) {
        
        String str = "東京都千代田区 123-4567";
        System.out.println(str.matches(".*[0-9]{3}-[0-9]{4}.*"));
        
    }
}

何故だ?
..\Playground\:7: error: unmappable character for encoding Cp1252
String str = “µ?▒Σ║¼Θâ╜σ?âΣ╗úτö░σî║ 123-4567”;
^
..\Playground\:7: error: unmappable character for encoding Cp1252
String str = “µ?▒Σ║¼Θâ╜σ?âΣ╗úτö░σî║ 123-4567”;
^
2 errors

ArrayListへの配列の追加

javaでarraylistに配列に追加していく。

ArrayList<String> items = new ArrayList<>();
          items.add("マネックスグループ");
          items.add("オウケイウェブ");
          items.add("アカツキ");
          items.add("ジーエヌアイグループ");
          items.add("そーせいグループ");
          items.add("KLab");
          items.add("ブライトパスバイオ");
          items.add("リミックスポイント");
          items.add("ラクオリア創薬");
          items.add("楽天");

Java API sample

package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;

import java.io.File;
import java.util.Calender;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Activity;
import com.google.api.services.youtube.model.ActivityContentDetails;
import com.google.api.services.youtube.model.ActivitySnippet;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.ResourceId;
import com.google.common.collect.Lists;


public class ChannelBulletin {
	private static final HttpTrarnsport HTTP_TRANSPORT = new NetHttpTransport();
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();
	private static YouTube youtube;

	private static String VIDEO_ID = "xxxx"

	private static Credential authorize(List<String> scopes) throws Exception {

		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
			JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));

			if (clientSecrets.getDetails().getClientId().startsWith("Enter")
				|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")){
				System.out.println(
					"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
					+ "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
					Sytem.exit(1);
			}

			FileCredentialStore credentialStore = new FileCredentialStore(
				new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
				JSON_FACTORY);

			GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
				HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
				.build();

			LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

			return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
	}

	public static void main(String[] args){

		List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

		try {
			Credential credential = authorize(scopes);

			youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
				"youtube-cmdline-channelbulletin-sample").build();

			YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
			channelRequest.setMine("true");

			channelRequest.setFields("items/contentDetails");
			ChannelListResponse channelResult = channelRequest.execute();

			List<Channel> channelList = channelResult.getItems();

			if (channelList != null){
				String channelId = channelsList.get(0).getId();

				ActivitySnippet snippet = new ActivitySnippet();
				sunippet.setChannelId(channelId);
				Calendar cal = Calendar.getInstance();
				snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());

				ResourceId resource = new ResourceId();
				resource.setKind("youtube#bideo");
				resource.setVideoId(VIDEO_ID);

				Bulletin bulletin = new Bulletin();
				bulletin.setResourceId(resource);

				ActivityContentDetails contentDetails = new ActivityContentDetails();
				contentDetails.setBulletin(bulletin);

				Activity activity = new Activity();
				activity.setSnippet(snippet);
				activity.setContentDetails(contentDetails);

				YouTube.Activities.Insert insertActivities =
					youtube.activities().insert("contentDetails.snippet", activity);
				Activity newActivityInserted = insertActivities.execute();

				if (newActivityInserted != null){
					System.out.println(
						"New Activity inserted of type " + newActivityInserted.getSnippet().getType());
					System.out.println(" - Video id "
						+ newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
					System.out.println(
						" - Description; " + newActivityInserted.getSnippet().getPublishedAt());
					else {
					System.out.println("Activity failed.");
					}
				} else {
					System.out.println("No channels are assigned to this user.");
				}
			} catch (GoogleJsonResponseException  e) {
				e.printStackTrace();
				System.err.println("There was a service error: " + e.getDetails().getCode + " : "
				+ e.getDetails().getMessage());

			} catch (Throwable t){
				t.printStackTrace();
			}
		}
	}

}

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");
	}

}