Quantcast
Channel: プログラム の個人的なメモ
Viewing all 860 articles
Browse latest View live

【SQL】 SQL アンチパターン ~ 目次 ~

$
0
0

SQL アンチパターン

【1】データベース論理設計のアンチパターン
[01] Jaywalking(信号無視)
[02] Naive Trees(素朴な木)
[03] ID Required(とりあえずID)
[04] Keyless Entry(外部キー嫌い)
[05] Entity-Attribute-Value(EAV エンティティ・アトリビュート・バリュー)
[06] Polymorphic Associations(ポリモーフィック関連)
[07] Multicolumn Attributes(複数列属性)
[08] Metadata Tribbles(メタデータ大増殖)

【2】データベース物理設計のアンチパターン
[09] Rounding Errors(丸め誤差)
[10] 31 Flavors(31のフレーバー)
[11] Phantom Files(幻のファイル)
[12] Index Shotgun(闇雲インデックス)
[13] Fear of the Unknown(恐怖のunknown)

【3】クエリのアンチパターン
[14] Ambiguous Groups(曖昧なグループ)
[15] Random Selection(ランダムセレクション)
[16] Poor Man’s Search Engine(貧者のサーチエンジン)
[17] Spaghetti Query(スパゲッティクエリ)
[18] Implicit Columns(暗黙の列)

【4】アプリケーション開発のアンチパターン
[19] Readable Passwords(読み取り可能パスワード)
[20] SQL Injection(SQLインジェクション)
[21] Pseudokey Neat-Freak(疑似キー潔癖症)
[22] See No Evil(臭いものに蓋)
[23] Diplomatic Immunity(外交特権)
[24] Magic Beans(魔法の豆)
[25] Sandcastle(砂の城)

関連記事

【1】データベース論理設計のアンチパターン

[02] Naive Trees(素朴な木)
http://blogs.yahoo.co.jp/dk521123/36192208.html

【4】アプリケーション開発のアンチパターン

[19] Readable Passwords(読み取り可能パスワード)
 * 【セキュリティ】 パスワード について
  => ソルトについて、記載
http://blogs.yahoo.co.jp/dk521123/36151596.html
[20] SQL Injection(SQLインジェクション)
 * SQLインジェクション(SQL Injection)
http://blogs.yahoo.co.jp/dk521123/35715532.html




【SQL】 SQL アンチパターン ~ 31 Flavors(31のフレーバー) ~

$
0
0

問題点

 * テーブルの列の値を特定したい場合、Check制約などで限定する
  => 変更した場合、変更 / 移植が困難。

使用してもいい場合

 * 変更する事がない場合(ON/OFF, 有効/無効, 男性/女性など)

解決策

 * 特定の値を別テーブルで定義する

# んー。特定の値が多ければやる価値あると思うけど、、、


関連記事

SQL アンチパターン ~ 目次 ~

http://blogs.yahoo.co.jp/dk521123/36194309.html

【SQL】 SQL アンチパターン ~ Metadata Tribbles(メタデータ大増殖) ~

$
0
0

問題点

 * 例えば、日々データが追加されるテーブル(例えば、「売上 Sales」「発注 Orders」「支払 Payments」)
   があったとする。そのデータがすごく増えた場合、検索スピードが落ちる訳で...
  => その対策として、「年ごとにテーブル分割する」をとったら、これが、アンチパターンっと。

解決策

 * 水平・垂直パーティショニング を使用する

※ パーティショニング とは?
 => データを複数に分割して格納すること

# 「テーブル設計」でデータを分割するんじゃなくて、
# 「DBの機能・パーティショニング」で分割するって話。

サンプル

ダメな例

-- テーブル

-- ・・・

CREATE TABLE payment_2016
(
id char(4) NOT NULL PRIMARY KEY COMMENT '支払ID',
salary_date date NOT NULL COMMENT '支払日',
employee_id bigint NOT NULL COMMENT '従業員ID',
salary int(11) NOT NULL COMMENT '給与',
FOREIGN KEY (employee_id) REFERENCES employee(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='2016年度 支払';

CREATE TABLE payment_2015
(
id char(4) NOT NULL PRIMARY KEY COMMENT '支払ID',
salary_date date NOT NULL COMMENT '支払日',
employee_id bigint NOT NULL COMMENT '従業員ID',
salary int(11) NOT NULL COMMENT '給与',
FOREIGN KEY (employee_id) REFERENCES employee(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='2015年度 支払';

-- ・・・

-- 年度ごとにテーブルを作成するって話。


関連記事

SQL アンチパターン ~ 目次 ~

http://blogs.yahoo.co.jp/dk521123/36194309.html

【MySQL】 外部ファイルからSQL文を一括で実行するには...

$
0
0

構文

* 注意: -pの直後に続けてパスワードを指定する
mysql -u <ユーザ名> -p<パスワード> -h <ホスト名> <データベース名> < <SQLファイル>

サンプル

 * バッチファイルとして作成してみる

事前準備

 * 環境変数 Path に対して、パスを通しておく
  (デフォルトだったら「C:\Program Files\MySQL\MySQL Server X.X\bin」(X.X:Version)を指定)

sample_sql.bat

REM Use UTF-8
chcp 65001

REM mysql -u <UserName> -p<password> -h <host> <db name> < <SQL file>
mysql -u root -ppassword -h localhost sampledb < create_delete.sql
mysql -u root -ppassword -h localhost sampledb < input.sql

REM Use Shift_JIS
chcp 932

create_delete.sql

-- Dumping structure for テーブル sampledb.employee
CREATE TABLE IF NOT EXISTS `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `birth_date` date NOT NULL,
  `section_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='従業員';

DELETE FROM employee;

ALTER TABLE employee AUTO_INCREMENT = 1;

input.sql

INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Mike', '1982-11-22', 1);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Tom', '1973-01-02', 2);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Smith', '1939-04-15', 3);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Chris', '1949-12-31', 3);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('John', '1976-09-19', 4);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Alan', '1899-12-22', 1);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Cindy', '1961-08-01', 2);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Ken', '1945-10-21', 3);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Cassie', '1933-11-11', 3);
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('Brian', '1976-09-19', 4);

トラブルシューティング

日本語を使うと文字化けする

 * バッチで、以下のように、日本語を使うと文字化けする。

【例】
INSERT INTO `employee` (`name`, `birth_date`, `section_id`) VALUES ('あい', '1976-09-19', 4);

【原因】
 * コマンドプロンプトのデフォルトの文字コードが「Shift-JIS」に対して、
   SQLファイルの文字コードが「UTF-8」だった場合に文字化けを起こす

【解決策】
 * コマンドプロンプトの文字コードをUTF-8にするために「chcp 65001」を実行する


関連記事

【PostgreSQL】ファイルからSQL文を一括で実行するには ~pdqlコマンドの利用~

http://blogs.yahoo.co.jp/dk521123/33982442.html

【トラブル】【MySQL】 MySQL に関するトラブルシューティング

$
0
0

エラー「Access denied for user ****@**** (using password: YES) 」が表示

権限について

■ 権限を付与
GRANT 与える権限 ON データベース名.テーブル名 TO ユーザー名;

# GRANT ALL ON *.* TO test;

# GRANT ALL ON sampledb.* to 'user001'@'%';

■ 登録されているユーザを確認

SELECT user, host FROM user;

■ 権限を表示
SHOW GRANTS for 'ユーザ名'@'ホスト名';

# SHOW GRANTS for 'user'@'localhost';

参考文献

http://www.goofoo.jp/2011/11/1457
http://www.aipacommander.com/entry/2014/05/26/152247
http://b.l0g.jp/mysql/user-at-localhost/
http://blog.codebook-10000.com/entry/20130806/1375794910
権限について
http://qiita.com/pinohara/items/481c95dc4c8c2568bf8d
http://qiita.com/shuntaro_tamura/items/2fb114b8c5d1384648aa
http://takuya-1st.hatenablog.jp/entry/2015/03/22/120618

【MySQL】 権限に関するあれこれ

$
0
0

権限を付与

GRANT 与える権限 ON データベース名.テーブル名 TO ユーザー名 IDENTIFIED BY 'ユーザー名に対するパスワード';

サンプル

GRANT ALL ON *.* TO test IDENTIFIED BY 'password';

GRANT ALL ON sampledb.* to 'user001'@'%' IDENTIFIED BY 'password';

登録されているユーザを確認

SELECT user, host FROM mysql.user;

権限を表示

SHOW GRANTS for 'ユーザ名'@'ホスト名';

サンプル

SHOW GRANTS for 'user'@'localhost';

関連記事

MySQL に関するトラブルシューティング

http://blogs.yahoo.co.jp/dk521123/36200427.html

【Java FX】 Java FX ~ 入門編 ~

$
0
0

Java FX

 * Java のGUIライブラリ(Swing の後継)

補足

 * CSSが使えるらしい
 * ダイアログはないらしい(自作する必要がある)

開発環境構築

環境

 * OS      : Windows10
 * Java    : Java 1.8
 * Eclipse : Mars.2 Release (4.5.2)

インストール手順

http://blogs.osdn.jp/2016/04/02/JavaFX.html
が参考になる。

[1] Eclipse を立ち上げて、[Help]-[Install New Software...]を選択
[2] Work with欄に以下のURLを入力し、Enterキー押下
http://download.eclipse.org/releases/mars
[3] [General Purpose Tools]-[e(fx)clipse - IDE]でチェックを入れる

後は成り行きでできる

プロジェクト作成手順

* 上記の「インストール手順」をしておく
http://krr.blog.shinobi.jp/javafx/eclipse%E3%81%A7javafx%E5%85%A5%E9%96%80
が参考になる。

[1] Eclipse を立ち上げて、[File]-[New]-[Project...]-[Java Fx]-[Java Fx Project]を選択

後は成り行きでできる

サンプル

Main.java

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;

public class Main extends Application {
  @Override
  public void start(Stage primaryStage) {
    try {
      Label label = new Label("Hello World!"); // ★追加★
      BorderPane root = new BorderPane();
      root.setCenter(label); // ★追加★
      Scene scene = new Scene(root, 400, 400);
      scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
      primaryStage.setScene(scene);
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    launch(args);
  }
}

参考文献

サンプルがシンプルで分かりやすい
http://libro.tuyano.com/index3?id=12466003&page=4

今後に役立ちそうなサイト

http://javafx-trick.appspot.com/

【SQL】 表の変更 / 制約 について ~ ALTER TABLE ~

$
0
0

■PRIMARY KEY制約

表にプライマリーキーを追加する
ALTER TABLE 【テーブル名】 ADD CONSTRAINT 【CONSTRAINT名】 
	PRIMARY KEY (【PKにしたいカラム名1】, 【PKにしたいカラム名2】);

■UNIQUE制約

表に一意制約を追加する
ALTER TABLE 【テーブル名】 ADD 
	UNIQUE (【PKにしたいカラム名1】, 【PKにしたいカラム名2】);

参考文献

http://tilfin.hatenablog.com/entry/20080209/1202544867

■Not null制約

表にNot Nullを追加する
ALTER TABLE 【テーブル名】 MODIFY (【Not Nullにしたいカラム名1】 NOT NULL);

■制約の削除

 *  「ALTER TABLE ~ DROP CONSTRAINT ~」を使用

構文

ALTER TABLE テーブル名
DROP CONSTRAINT 制約名;

ALTER TABLE tblName
DROP CONSTRAINT fkKey;

参考資料

http://www4.plala.or.jp/tamo/sql/sqlddl/sqlddl.html

関連記事

表の扱い

http://blogs.yahoo.co.jp/dk521123/16096597.html

表の変更について ~ ALTER TABLE ~

http://blogs.yahoo.co.jp/dk521123/36153996.html

【SQL】【MySQL】 データあればUPDATE、なければINSERT ~ DUPLICATE KEY ~

$
0
0

データあればUPDATE、なければINSERT

 * MySQLでは、「INSERT INTO ~ ON DUPLICATE KEY UPDATE ~」で行う

サンプル

CREATE TABLE文

CREATE TABLE `item` (
	`id` CHAR(8) NOT NULL,
	`name` VARCHAR(100) NULL DEFAULT NULL,
	`price` INT(11) NULL DEFAULT NULL,
	`releasedate` DATETIME NULL DEFAULT NULL,
	`createdate` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
	`updatedate` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

SQL

* ここからが本番
INSERT INTO item
(
  id,
  name,
  price,
  releasedate
) VALUES (
  'X0000',
  'Orange',
  120,
  '2016-07-14'
) ON DUPLICATE KEY UPDATE
  id = 'X0000',
  name = 'Orange',
  price = 121,
  releasedate = '2016-07-14'
;

実行結果

* 1回目
id	name	price	releasedate	createdate	updatedate
X0000	Orange	120	2016/7/14 0:00	2016/7/14 22:06	2016/7/14 22:06
* 2回目(price:121に変わってる)
id	name	price	releasedate	createdate	updatedate
X0000	Orange	121	2016/7/14 0:00	2016/7/14 22:06	2016/7/14 22:08


関連記事

データあればUPDATE、なければINSERT ~ @@ROWCOUNT ~

http://blogs.yahoo.co.jp/dk521123/30656970.html

データあればUPDATE、なければINSERT ~ MERGE文 (マージ文) ~

http://blogs.yahoo.co.jp/dk521123/30657481.html

【Java】 Java で、 Email を送るには... ~ JavaMail / テキストメール編 ~

$
0
0

Java で、 Email を送るには...

 * (色々あるらしいが)JavaMail を利用する

準備

JavaMailのダウンロード

 * 以下のサイトから「javax.mail.jar」(今回は「JavaMail v1.5.5」)をダウンロードし
   インポートしておく
https://java.net/projects/javamail/pages/Home

【任意の設定】Windowsローカル上でテストするには(開発用SMTPサーバーの設定)

(これまた色々あるらしいが)smtp4dev を利用する
 * 以下のサイトから「smtp4dev-X.X.X-binaries.zip」(今回は「smtp4dev-2.0.9-binaries.zip」)
  をダウンロードし、解凍し、smtp4dev.exeを起動するだけ(簡単)
http://smtp4dev.codeplex.com/

サンプル

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailHandler {
  private final static String DEFAULT_TIMEOUT = "10000";
  private final static String DEFAULT_HOST = "localhost";
  private String fromAddress;
  private List<String> toAddresses;
  private String mailSubject;
  private String mailBody;
  private String host;
  private String timeout;
  private boolean isOnDebugMode;

  /**
   * Default Contractor.
   */
  public EmailHandler() {
    this.fromAddress = null;
    this.toAddresses = new ArrayList<>();
    this.mailSubject = null;
    this.mailBody = null;
    this.host = DEFAULT_HOST;
    this.timeout = DEFAULT_TIMEOUT;
    this.isOnDebugMode = false;
  }

  public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
  }

  public void setToAddresses(List<String> toAddresses) {
    this.toAddresses = toAddresses;
  }

  public void addToAddress(String toAddress) {
    this.toAddresses.add(toAddress);
  }

  public void setMailSubject(String mailSubject) {
    this.mailSubject = mailSubject;
  }

  public void setMailBody(String mailBody) {
    this.mailBody = mailBody;
  }

  public void setHost(String host) {
    this.host = host;
  }

  public void setOnDebugMode(boolean isOnDebugMode) {
    this.isOnDebugMode = isOnDebugMode;
  }

  public void send() throws MessagingException {
    if (this.toAddresses == null || this.host == null) {
      throw new InvalidParameterException();
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", this.host);
    props.put("mail.debug", this.isOnDebugMode);
    props.put("mail.smtp.connectiontimeout", this.timeout);
    props.put("mail.smtp.timeout", this.timeout);

    
    Session session = Session.getInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(this.toInternetAddress(this.fromAddress));
    InternetAddress[] addresses = this.toInternetAddresses(this.toAddresses);
    mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
    mimeMessage.setSubject(this.mailSubject);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setText(this.mailBody);

    Transport.send(mimeMessage);
  }

  private InternetAddress[] toInternetAddresses(List<String> addresses) throws AddressException {
    InternetAddress[] returnValues = new InternetAddress[addresses.size()];

    int index = 0;
    for (String address : addresses) {
      returnValues[index] = this.toInternetAddress(address);
      index++;
    }

    return returnValues;
  }

  private InternetAddress toInternetAddress(String address) throws AddressException {
    return new InternetAddress(address);
  }

  /**
   * 【使用例】
   * 
   * @param args
   */
  public static void main(String[] args) {
    try {
      EmailHandler email = new EmailHandler();
      email.setFromAddress("sample@yahoo.com");
      email.addToAddress("sample@gmail.com");
      email.setMailSubject("タイトルです。");
      email.setMailBody("メール本文です。\r\n以上です。");
      email.setOnDebugMode(true);
      email.send();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}


関連記事

Java で、 Email を送るには... ~ JavaMail / 添付ファイル付きメール編 ~

http://blogs.yahoo.co.jp/dk521123/36230816.html

【Java】 Java で、 Email を送るには... ~ JavaMail / 添付ファイル付きメール編 ~

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/36230453.html
の続き。

今度は、添付ファイルを付けて送る。
ついでに、CCとBCCをつけてみた。

サンプル

import java.io.UnsupportedEncodingException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EmailHandler {
  private final static String DEFAULT_TIMEOUT = "10000";
  private final static String DEFAULT_HOST = "localhost";
  private String fromAddress;
  private List<String> toAddresses;
  private List<String> ccAddresses;
  private List<String> bccAddresses;
  private String mailSubject;
  private String mailBody;
  private String atachmentFilePath;
  private String host;
  private String timeout;
  private boolean isOnDebugMode;

  /**
   * Default Contractor.
   */
  public EmailHandler() {
    this.fromAddress = null;
    this.toAddresses = new ArrayList<>();
    this.ccAddresses = new ArrayList<>();
    this.bccAddresses = new ArrayList<>();
    this.mailSubject = null;
    this.mailBody = null;
    this.atachmentFilePath = null;
    this.host = DEFAULT_HOST;
    this.timeout = DEFAULT_TIMEOUT;
    this.isOnDebugMode = false;
  }

  public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
  }

  public void setToAddresses(List<String> toAddresses) {
    this.toAddresses = toAddresses;
  }

  public void addToAddress(String toAddress) {
    this.toAddresses.add(toAddress);
  }
  
  public void setCcAddresses(List<String> ccAddresses) {
    this.ccAddresses = ccAddresses;
  }

  public void addCcAddress(String ccAddress) {
    this.ccAddresses.add(ccAddress);
  }

  public void setBccAddresses(List<String> bccAddresses) {
    this.bccAddresses = bccAddresses;
  }

  public void addBccAddress(String bccAddress) {
    this.bccAddresses.add(bccAddress);
  }


  public void setMailSubject(String mailSubject) {
    this.mailSubject = mailSubject;
  }

  public void setMailBody(String mailBody) {
    this.mailBody = mailBody;
  }

  public void setAtachmentFilePath(String atachmentFilePath) {
    this.atachmentFilePath = atachmentFilePath;
  }
  
  public void setHost(String host) {
    this.host = host;
  }

  public void setOnDebugMode(boolean isOnDebugMode) {
    this.isOnDebugMode = isOnDebugMode;
  }

  public void send() throws MessagingException, UnsupportedEncodingException {
    if (this.toAddresses == null || this.host == null) {
      throw new InvalidParameterException();
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", this.host);
    props.put("mail.debug", this.isOnDebugMode);
    props.put("mail.smtp.connectiontimeout", this.timeout);
    props.put("mail.smtp.timeout", this.timeout);

    Session session = Session.getInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(this.toInternetAddress(this.fromAddress));
    
    InternetAddress[] toAddresses = this.toInternetAddresses(this.toAddresses);
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);
    
    InternetAddress[] ccAddresses = this.toInternetAddresses(this.ccAddresses);
    mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
    
    InternetAddress[] bccAddresses = this.toInternetAddresses(this.bccAddresses);
    mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses);
    
    mimeMessage.setSubject(this.mailSubject);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setText(this.mailBody);

    // ★添付ファイル処理★
    if (this.atachmentFilePath != null) {
      Multipart multipart = new MimeMultipart();
      MimeBodyPart mimeBodyPart = new MimeBodyPart();
      FileDataSource fileDataSource = new FileDataSource(this.atachmentFilePath);
      DataHandler dataHandler = new DataHandler(fileDataSource);
      mimeBodyPart.setDataHandler(dataHandler);
      mimeBodyPart.setFileName(MimeUtility.encodeWord(dataHandler.getName()));
      multipart.addBodyPart(mimeBodyPart);
      mimeMessage.setContent(multipart);
    }
    
    Transport.send(mimeMessage);
  }

  private InternetAddress[] toInternetAddresses(List<String> addresses) throws AddressException {
    InternetAddress[] returnValues = new InternetAddress[addresses.size()];

    int index = 0;
    for (String address : addresses) {
      returnValues[index] = this.toInternetAddress(address);
      index++;
    }

    return returnValues;
  }

  private InternetAddress toInternetAddress(String address) throws AddressException {
    return new InternetAddress(address);
  }

  /**
   * 【使用例】
   * 
   * @param args
   */
  public static void main(String[] args) {
    try {
      EmailHandler email = new EmailHandler();
      email.setFromAddress("sample@yahoo.com");
      email.addToAddress("to.sample@gmail.com");
      email.addCcAddress("cc.sample@gmail.com");
      email.addBccAddress("bcc.sample@gmail.com");
      email.setMailSubject("タイトルです。");
      email.setMailBody("メール本文です。\r\n以上です。");
      email.setOnDebugMode(true);
      email.setAtachmentFilePath("C:\\Users\\AdminUser\\Desktop\\Book1.xlsx");
      email.send();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}


関連記事

Java で、 Email を送るには... ~ JavaMail / テキストメール編 ~

http://blogs.yahoo.co.jp/dk521123/36230453.html

【Java】【JAX-WS】 Webサービス / Metro [5] ~応用編 / あれこれ ~

$
0
0

■ JAX-WS / Metro で、Webサービス終了時のイベントを拾いたい

解決案

 * @PreDestroy を付加したメソッドを実装

サンプル

import javax.annotation.PreDestroy;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;

@WebService(name = "SampleWebService")
public class SampleWebService {

  @PreDestroy
  protected void close() {
    // ★ここに処理を書く★
  }

ポイント

 * public ではなく、 protected の方がいい
  => 自動生成でコード生成する際に、Webサービスとして認識してしまうため

関連記事

Webサービス / Metro [1] ~入門編 / サーバサイドの構築 ~

http://blogs.yahoo.co.jp/dk521123/36139336.html

【トラブル】【Eclipse】【Tomcat】 Eclipseで、Tomcat8.5 を動かす

$
0
0

問題点

 * 現在最新のEclipseのVersion(Version: Neon Release (4.6.0))でも
   Tomcat8.0系とTomcat9.0系は対応しているようだが、Tomcat8.5系は
   以下のエラーで設定できない

エラー内容

The Apache Tomcat installation at this directory is version 8.5.3. A Tomcat 8.0 installation is expected

解決策

 * ${CATALINA_HOME}/lib/catalina.jarの中身である、org/apache/catalina/util/ServerInfo.propertiesを修正し
   catalina.jarを作り直す(方法は以下の【手順】を参照のこと。)

手順

* 邪道な方法かもしれないが
[1] ${CATALINA_HOME}/lib/catalina.jar をリネーム「catalina.zip」などしてzip解凍する

【フォルダ構成】
catalina
 + META-INF(中身は「MANIFEST.MF」など)
 + org
   + apache
      + catalina
         + util
            + ServerInfo.properties

[2] ServerInfo.propertiesをテキストエディタなどで開き、【修正後】を参考に修正し、上書き保存

【修正前】
server.info=Apache Tomcat/8.5.3
server.number=8.5.3.0
server.built=Jun 9 2016 11:16:29 UTC

【修正後】
server.info=Apache Tomcat/8.0.0
server.number=8.0.0.0
server.built=Jun 9 2016 11:16:29 UTC

[3] 解凍したcatalinaを再度、Zipで圧縮し、リネーム「catalina.jar」する
[4] [3]を${CATALINA_HOME}/lib/catalina.jar に再配置する

【トラブル】【Java】 CHAR(1)の項目を文字で更新すると、SQLException: Incorrect string value ... が 発生する

$
0
0

問題概要

 * 以下の環境下で、CHAR(1)データ項目を文字(例えば 'f')で更新処理を行ったところ、
   SQLException: Incorrect string value: 'xxx' for column 'yyy'が 発生した

環境

 * OS : Windows7/10
 * Java : Java1.8
 * DB : MySQL
 * dbutils-1.6

エラー内容

java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05sr...' for column 'sex' at row 1 Query: INSERT INTO person (id, name, sex) VALUES (?, ?, ?) Parameters: [Z0000001, Tommy, f]
	at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:392)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:491)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:404)
	at com.sample.db.SampleDbUtils.execute(SampleDbUtils.java:28)
	at com.sample.db.SampleDbUtils.main(SampleDbUtils.java:14)

サンプル

テーブル

CREATE TABLE `person` (
	`id` CHAR(8) NOT NULL,
	`name` VARCHAR(100) NULL DEFAULT NULL,
	`sex` CHAR(1) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

NG例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

public class SampleDbUtils {

  public static void main(String[] args) {
    SampleDbUtils sample = new SampleDbUtils();
    sample.execute();
  }

  Connection connection = null;
  QueryRunner queryRunner = new QueryRunner();

  public void execute() {
    try {
      // DB接続
      this.connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledb", "root", "password");

      // オートコミットを無効
      this.connection.setAutoCommit(false);
      // INSERTサンプル
      this.queryRunner.update(this.connection, "INSERT INTO person (id, name, sex) VALUES (?, ?, ?)", "Z0000001",
          "Tommy", 'f');
      // commit
      DbUtils.commitAndCloseQuietly(this.connection);
    } catch (SQLException ex) {
      DbUtils.rollbackAndCloseQuietly(this.connection);
      ex.printStackTrace();
    } finally {
      DbUtils.closeQuietly(this.connection);
    }
  }
}

原因

 * 文字 'f' を設定したこと

調査詳細

DbUtils内の[AbstractQueryRunner.java]のfillStatement()より
~~~
public void fillStatement(PreparedStatement stmt, Object... params)
  // 略

  if (params[i] != null) {
    stmt.setObject(i + 1, params[i]);
  } else {
~~~
params[i]が文字(例 'f')の場合、うまくいかない

試しに、DbUtilsを使わずに、以下のようにPreparedStatement を使っても同じエラーが発生する
~~~
PreparedStatement preparedStatement = 
      connection.prepareStatement("INSERT INTO person(id, name, sex) VALUES(?, ?, ?)");) {
preparedStatement.setString(1, "Z0000001");
preparedStatement.setString(2, "Tom");
preparedStatement.setObject(3, 'f');
result = preparedStatement.executeUpdate();
~~~

解決策

 * 文字 CHAR(1)の項目であっても、文字 'f' ではなく、文字列 "f" として設定する

~~~
this.queryRunner.update(this.connection, "INSERT INTO person (id, name, sex) VALUES (?, ?, ?)",
 "Z0000001", "Tommy", "f");

preparedStatement.setString(3, "f");
~~~

後日談

http://stackoverflow.com/questions/5686514/jdbc-how-to-set-char-in-a-prepared-statement
で同じようなこと相談してた。上記より一部抜粋。


JDBC Type              Java Type
-------------------------------------------
CHAR                   String
VARCHAR                String
LONGVARCHAR            String
NUMERIC                java.math.BigDecimal
DECIMAL                java.math.BigDecimal
BIT                    boolean
BOOLEAN                boolean
TINYINT                byte
SMALLINT               short

【Java】【非同期】 ThreadPoolExecutor ~スレッドプール ~ [1]

$
0
0

ThreadPoolExecutor

 * プールされているスレッドと処理すべきタスクのリストを管理
 * 以下の関連記事で扱ったWorker Thread パターン(別名スレッドプールパターン)を実装するのに使える
  * ThreadPoolExecutorが、ChannelとWorker を兼ね備えている
http://blogs.yahoo.co.jp/dk521123/32918314.html

スレッドプールの種類

[1] newFixedThreadPool
 => 指定したスレッド数を使いまわして、タスクを処理する。

[2] newCachedThreadPool
 => 複数スレッドでタスクを処理。

スレッドプールのインスタンス作成方法

[1] new ThreadPoolExecutor(引数)で作成
 => 以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/33942167.html
[2] ファクトリーメソッド(例「executor = Executors.newCachedThreadPool()」)で作成
 => 以下のサンプルを参照

サンプル

http://blogs.yahoo.co.jp/dk521123/32918314.html
とほぼ同じことをやってみる

IRequest.java

public interface IRequest extends Runnable {
  // 何もない
}

Request.java

import java.util.Random;

public class Request implements IRequest {
  // 依頼者
  private final String companyName;
  // リクエストの番号
  private final int requestNumber;

  public SampleRequest(String companyName, int requestNumber) {
    this.companyName = companyName;
    this.requestNumber = requestNumber;
  }

  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName() + " executes " + this);
    try {
      this.doHeavyJob();
    } catch (InterruptedException e) {
    }
  }

  public String toString() {
    return "[ Request from " + this.companyName + " No." + this.requestNumber + " ]";
  }

  private void doHeavyJob() throws InterruptedException {
    Random random = new Random();
    Thread.sleep(random.nextInt(1000));
  }
}

SampleWorkerThread.java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SampleWorkerThread {
  private ExecutorService executor;
  
  public SampleWorkerThread() {
    this.executor = Executors.newCachedThreadPool();
  }
  
  public void putRequest(IRequest request) {
    this.executor.execute(request);
  }
  
  public void quit() {
    this.executor.shutdown();
  }
}

Main.java

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

public class Main {

  public static void main(String[] args) throws InterruptedException {
    SampleWorkerThread sampleWorkerThread = new SampleWorkerThread();

    List<String> companyNames = new ArrayList<String>() {
      private static final long serialVersionUID = 1L;
      {
        add("Yahoo");
        add("Google");
        add("Oracle");
      }
    };

    for (int i = 0; i < 100; i++) {
      String companyName = companyNames.get(i % 3);
      sampleWorkerThread.putRequest(new Request(companyName, i));
      doHeavyJob();
    }

    sampleWorkerThread.quit();
  }

  private static void doHeavyJob() throws InterruptedException {
    Random random = new Random();
    Thread.sleep(random.nextInt(10000));
  }
}

出力結果

[Start] pool-1-thread-1 executes [ Request from Yahoo No.0 ]
[Start] pool-1-thread-2 executes [ Request from Google No.1 ]
[End] pool-1-thread-2 executes [ Request from Google No.1 ]
[Start] pool-1-thread-2 executes [ Request from Oracle No.2 ]
[Start] pool-1-thread-3 executes [ Request from Yahoo No.3 ]
[Start] pool-1-thread-4 executes [ Request from Google No.4 ]
[Start] pool-1-thread-5 executes [ Request from Oracle No.5 ]
[Start] pool-1-thread-6 executes [ Request from Yahoo No.6 ]
[Start] pool-1-thread-7 executes [ Request from Google No.7 ]
[End] pool-1-thread-3 executes [ Request from Yahoo No.3 ]
[Start] pool-1-thread-3 executes [ Request from Oracle No.8 ]
[Start] pool-1-thread-8 executes [ Request from Yahoo No.9 ]
[End] pool-1-thread-7 executes [ Request from Google No.7 ]
[Start] pool-1-thread-7 executes [ Request from Google No.10 ]
[End] pool-1-thread-6 executes [ Request from Yahoo No.6 ]
[Start] pool-1-thread-6 executes [ Request from Oracle No.11 ]
[End] pool-1-thread-6 executes [ Request from Oracle No.11 ]
[Start] pool-1-thread-6 executes [ Request from Yahoo No.12 ]
[Start] pool-1-thread-9 executes [ Request from Google No.13 ]
[End] pool-1-thread-1 executes [ Request from Yahoo No.0 ]
[Start] pool-1-thread-1 executes [ Request from Oracle No.14 ]
[Start] pool-1-thread-10 executes [ Request from Yahoo No.15 ]
[End] pool-1-thread-8 executes [ Request from Yahoo No.9 ]
[End] pool-1-thread-2 executes [ Request from Oracle No.2 ]
[Start] pool-1-thread-2 executes [ Request from Google No.16 ]
...


関連記事

【デザインパターン】【非同期】Worker Thread パターン

http://blogs.yahoo.co.jp/dk521123/32918314.html

ThreadPoolExecutor ~スレッドプール ~ [2]

http://blogs.yahoo.co.jp/dk521123/33942167.html

【Java】【Velocity】 Velocityを利用してメールテンプレート機能の実装を考える

$
0
0

はじめに

 * 以下の関連記事でメール送信することはできたが、本文が直書きなので、
  外出しファイルで実装したい
http://blogs.yahoo.co.jp/dk521123/36230453.html
http://blogs.yahoo.co.jp/dk521123/36230816.html
 * できれば、件名も外出ししたいが...
 * できれば、日本語だけでなく、国際化にも将来的に対応できるようにしたいが...

構成

もっとスマートな方法ないかな...
■ MailParameterCreator : メール・パラメータ作成クラス

 * 本文
  => 本文「Body」は、Velocityテンプレートを使う 
  => インターフェイスとしては、public String getBody(String templatePath, MailBean bean);

サンプル

TempMail.vm

 * Velocityを利用してメールテンプレート
メンテ中

MailParameterCreator .java

メンテ中

Main.java

呼び出し側
メンテ中


関連記事

Apache Velocity関連

Apache Velocity ~入門編~
http://blogs.yahoo.co.jp/dk521123/34456704.html
Apache Velocity ~VTL(Velocity Template Language)編~
http://blogs.yahoo.co.jp/dk521123/34463879.html
Velocity を Servlet で使用するには
http://blogs.yahoo.co.jp/dk521123/34460303.html

メール送信関連

Java で、 Email を送るには... ~ JavaMail / テキストメール編 ~
http://blogs.yahoo.co.jp/dk521123/36230453.html
Java で、 Email を送るには... ~ JavaMail / 添付ファイル付きメール編 ~
http://blogs.yahoo.co.jp/dk521123/36230816.html

【Java】【Velocity】 Velocityを利用してメールテンプレート機能の実装を考える [2]

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/36245554.html
の続き。上記で言ってた
~~~~
できれば、
 * 件名も外出ししたい
~~~~
を考える。

実装案

http://blogs.yahoo.co.jp/dk521123/34463879.html
を眺めていたら「##」がコメントアウトになるので、例えば、
・件名は、一行目のコメント文に書く
と決めておけば実現できそう。

サンプル

SampleTemplete.vm

$mailBean.userName 様
                                       $mailBean.date
 この度はお買い上げ頂き、誠にありがとうございます。

【商品】
#foreach ($productName in $mailBean.productNames)
商品名   : $productName
#end

以上

IMailBean.java / SampleMailBean.java

http://blogs.yahoo.co.jp/dk521123/36245554.html
と同じなので省略

EmailParamCreator.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class EmailParamCreator {
  private static final String DEFAULT_ENCODING = "UTF-8";

  public static String getMailBody(String templatePath, String templateFileName, IMailBean bean) throws IOException {

    try (StringWriter writer = new StringWriter();) {
      Velocity.setProperty("file.resource.loader.path", templatePath);
      Velocity.init();
      VelocityContext context = new VelocityContext();

      context.put("mailBean", bean);
      Template tmplate = Velocity.getTemplate(templateFileName, DEFAULT_ENCODING);
      tmplate.merge(context, writer);
      return writer.toString();
    }
  }

  // ★ここ★
  public static String getMailSubject(String templatePath, String templateFileName) throws IOException {
    Path path = Paths.get(templatePath, templateFileName);
    try (BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(new FileInputStream(new File(path.toString())), DEFAULT_ENCODING));) {
      String firstLine = bufferedReader.readLine();
      String firstLineWithoutComment = firstLine.replaceFirst("##", "");
      return firstLineWithoutComment.trim();
    }
  }

  // ★ここ★
  public static SimpleEntry<String, String> getMailSubjectAndBody(String templatePath, String templateFileName,
      IMailBean bean) throws IOException {
    String mailSubject = EmailParamCreator.getMailSubject(templatePath, templateFileName);
    String mailBody = EmailParamCreator.getMailBody(templatePath, templateFileName, bean);

    return new SimpleEntry<>(mailSubject, mailBody);

  }
}

Main.java

呼び出し側
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;

public class Main {

  public static void main(String[] args) {
    SampleMailBean bean = new SampleMailBean();
    bean.setUserName("○井");
    bean.setDate("2016-07-23");
    bean.addProductNames("C#  Program Book");
    bean.addProductNames("Java Program Book");
    bean.addProductNames("C++ Program Book");

    try {
      SimpleEntry<String, String> mailSubjectAndBody = EmailParamCreator.getMailSubjectAndBody("./conf",
          "SampleTemplete.vm", bean);
      System.out.println(mailSubjectAndBody.getKey());
      System.out.println();
      System.out.println(mailSubjectAndBody.getValue());
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

出力結果

【サンプルタイトル】お買い上げ、ありがとうございます。

○井 様
                                       2016-07-23
 この度はお買い上げ頂き、誠にありがとうございます。

【商品】
商品名   : C#  Program Book
商品名   : Java Program Book
商品名   : C++ Program Book

以上

関連記事

Velocityを利用してメールテンプレート機能の実装を考える [1]

http://blogs.yahoo.co.jp/dk521123/36245554.html

Apache Velocity関連

Apache Velocity ~入門編~
http://blogs.yahoo.co.jp/dk521123/34456704.html
Apache Velocity ~VTL(Velocity Template Language)編~
http://blogs.yahoo.co.jp/dk521123/34463879.html
Velocity を Servlet で使用するには
http://blogs.yahoo.co.jp/dk521123/34460303.html

メール送信関連

Java で、 Email を送るには... ~ JavaMail / テキストメール編 ~
http://blogs.yahoo.co.jp/dk521123/36230453.html
Java で、 Email を送るには... ~ JavaMail / 添付ファイル付きメール編 ~
http://blogs.yahoo.co.jp/dk521123/36230816.html

【Linux】 ダミーSMTPサーバ構築

$
0
0

はじめに

http://blogs.yahoo.co.jp/dk521123/36230453.html
で、Windows環境にて、ダミーSMTPサーバとして、smtp4dev を利用した。
今回は、Linux環境で、ダミーSMTPサーバを立てる

種類

[1] FakeSMTP(Java製)
[2] MailCatcher(Ruby製)

# 他にも、DebuggingServer(Python製)など色々あるらしいが...

[1] FakeSMTP

 * Java Ver1.6以上

設定手順

[1] 以下のサイトの「Download」からモジュール「fakeSMTP-latest.zip」を落としてくる
http://nilhcem.github.io/FakeSMTP/index.html
[2] [1]のモジュール「fakeSMTP-latest.zip」を解凍する
 => 解凍すると「fakeSMTP-2.0.jar」が出てくる
# Windowsの場合、JARファイルをダブルクリックするだけ
[3] コマンドで「java -jar fakeSMTP-2.0.jar 【オプション】」で起動する

[Options]
  -s : 自動立ち上げモード
  -b : GUIでの立ち上げをオフ
  -p : ポート番号の指定(-p xxxx) / デフォルトは、port 25
  -a : アドレス
  -o : 特定の場所にメールを格納(-o directory)
  -m : メモリモード(メールを保存しない場合に使用) 

 [例]
 java -jar fakeSMTP-2.0.jar -s -b -p 2525 -a 127.0.0.1

公式サイト

http://nilhcem.github.io/FakeSMTP/index.html

参考文献

http://www.moongift.jp/2013/05/20130507-3/
http://propg.ee-mall.info/it/%E3%83%A1%E3%83%BC%E3%83%AB%E9%80%81%E4%BF%A1%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%A0%E3%81%AE%E7%A2%BA%E8%AA%8D%E7%94%A8%E3%81%AB%EF%BC%81%EF%BC%81-%E3%80%8Cfakesmtp%E3%80%8D/

[2] MailCatcher

設定手順

[1] 以下のコマンドを入力

sudo yum update
sudo yum groupinstall "Development Tools"
sudo yum install ruby-devel ruby19-devel sqlite-devel openssl openssl-devel
sudo yum install rubygems

# インストール
gem install mailcatcher

# 起動
mailcatcher

[2] ブラウザで以下のURLにアクセスする
[[http://localhost:1080/]]

補足:mailcatcherのオプション

# ヘルプ
mailcatcher --help
# ポート変更
mailcatcher --smtp-port 20025 --http-port 20080
構文
Usage: mailcatcher [options]
        --ip IP                      Set the ip address of both servers
        --smtp-ip IP                 Set the ip address of the smtp server
        --smtp-port PORT             Set the port of the smtp server
        --http-ip IP                 Set the ip address of the http server
        --http-port PORT             Set the port address of the http server
        --no-quit                    Don't allow quitting the process
    -f, --foreground                 Run in the foreground
    -b, --browse                     Open web browser
    -v, --verbose                    Be more verbose
    -h, --help                       Display this help information

【任意設定】Apacheとの連携

 * なお、Apacheの設定は、以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/36072244.html
[1] /etc/httpd/conf.d 配下に、以下のMailCatcher.confを新規作成する
/etc/httpd/conf.d/MailCatcher.conf
ProxyPass /mailcatcher http://localhost:1080

【任意設定】Mailcatcherの自動起動

 * systemd を使って、Mailcatcherを自動起動させる

# systemd については、以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/36255225.html
 [1] /etc/systemd/system 配下に、以下のMailCatcher.service を新規作成
 [2] 以下のコマンドを入力し、サービスの自動起動ONにし、OS再起動。

 systemctl enable MailCatcher.service
 reboot
/etc/systemd/system/MailCatcher.service
[Unit]
 Description=Mailcatcher Service

[Service]
 Type=simple
 ExecStart=/usr/local/bin/mailcatcher --foreground --smtp-port 20025 --http-port 20080

[Install]
 WantedBy=multi-user.target


関連記事

Linux(仮想環境) を構築する ~CentOS編~

http://blogs.yahoo.co.jp/dk521123/36252928.html

Java で、 Email を送るには... ~ JavaMail / テキストメール編 ~

http://blogs.yahoo.co.jp/dk521123/36230453.html

CentOS7でのサービス(デーモン) ~ systemd ~

http://blogs.yahoo.co.jp/dk521123/36255225.html

【Linux】 CentOS7でのサービス(デーモン) ~ systemd ~

$
0
0

サービス起動・停止

systemctl コマンドを利用
[1-1] サービスの起動  systemctl start サービス名.service
[1-2] サービスの停止  systemctl stop サービス名.service
[1-3] サービスの再起動 systemctl restart サービス名.service

[2-1] サービスの自動起動設定 systemctl enable サービス名.service
[2-2] サービスの自動起動解除 systemctl disable サービス名.service

[3-1] サービスの確認   systemctl list-units --type=service


関連記事

Linux(仮想環境) を構築する ~CentOS編~

http://blogs.yahoo.co.jp/dk521123/36252928.html

ダミーSMTPサーバ構築

 * 「Mailcatcherの自動起動」で、サービスの自動起動を設定している
http://blogs.yahoo.co.jp/dk521123/36252946.html

【Linux】【コマンド】 ネットワーク系のコマンド

$
0
0

■ ポートを開け、反映させる

その1

# ポート 20025 Open
sudo firewall-cmd --add-port=20025/tcp --zone=public --permanent
sudo firewall-cmd --reload

その2

iptables -I INPUT -p tcp --dport [ポート番号] -j ACCESPT

■ 特定のポートをオープンしているプロセスを調べる

http://blogs.yahoo.co.jp/dk521123/34704299.html
より抜粋

# 特定のポートをオープンしているプロセスを調べる
lsof -i:【ポート番号】

■ IP情報を調べる

`意味
`コマンド
備考
ifconfigIP情報などの表示Windowsのipconfig。※1

注意

※1 ifconfigコマンドを実行すると、command not foundと言われる場合

解決案1:ip addrコマンドを実行
解決案2:「/sbin/ifconfig」コマンドを実行
http://www.tabimoba.net/entry/2014/07/12/100725#.VXriSvntlBc
http://d.hatena.ne.jp/srkzhr/20071004/1191461815

■ 有線/無線LANの有効無効

ifconfig [eth0/wlan0] up/down
# 有線/無線LANの有効無効
sudo ifconfig eth0 up
# 有線LANの無効
sudo ifconfig eth0 down

# 無線LANの有効
sudo ifconfig wlan0 up
# 無線LANの有効無効
sudo ifconfig wlan0 down
http://www.xmisao.com/2014/01/16/how-to-connect-wpa2-wireless-lan-using-wpa-supplicant.html

■ ホストのネットワーク状態などの表示

`意味
 * 以下の関連記事を参照のこと
`コマンド
備考
netstatホストのネットワーク状態などの表示
http://blogs.yahoo.co.jp/dk521123/34848875.html

使用ポートが動作しているかを調べる

netstat -anp | grep "LISTEN " | grep 【ポート番号】

■ ping / tracert(traceroute)

 * 以下の関連記事を参照のこと
http://blogs.yahoo.co.jp/dk521123/31982842.html

関連記事

【Linux】【シェル】コマンド覚書

http://blogs.yahoo.co.jp/dk521123/33694626.html

【Linux】【シェル】 プロセスを強制終了するには

http://blogs.yahoo.co.jp/dk521123/34704299.html

【Linux】 ダミーSMTPサーバ構築

* 以下の関連記事でポートを開けた
http://blogs.yahoo.co.jp/dk521123/36252946.html
Viewing all 860 articles
Browse latest View live