Java GZIP圧縮(単体のファイルを扱う場合には使いやすい)

はじめに

事前に準備する外部ライブラリ等はありません。 JavaSEに含まれるjava.util.zip.GZIPOutputStreamクラスを使用します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 *
 * @author tool-taro.com
 */
public class GZIPTest {

    public static void main(String[] args) throws IOException {

        //圧縮対象のデータ(今回は文字列)
        String source = "これはテストです。\n以上。";
        //圧縮後のファイルの保存場所
        String outputFilePath = "output.txt.gz";
        //圧縮前にバイト配列に置き換える際のエンコーディング
        String encoding = "UTF-8";

        GZIPOutputStream gout = null;

        try {
            gout = new GZIPOutputStream(new FileOutputStream(outputFilePath));
            gout.write(source.getBytes(encoding));
        }
        finally {
            if (gout != null) {
                try {
                    gout.close();
                }
                catch (Exception e) {
                }
            }
        }
    }
}

動作確認

$ javac GZIPTest.java
$ java GZIPTest

生成されたファイルの解凍結果と、 無題.png 解凍後のテキスト内容です。 無題2.png

環境

Webツールも公開しています。 Web便利ツール@ツールタロウ

Java SMTPSで認証・暗号化してメール送信(本文+添付ファイル)

はじめに

SMTPSでメールアカウントを認証してから暗号化してメール送信します。 ついでに本文と添付ファイルの構成例とします。

事前に以下のライブラリを用意します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
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;
import javax.mail.util.ByteArrayDataSource;

/**
 *
 * @author tool-taro.com
 */
public class SMTPSTest {

    public static void main(String[] args) throws MessagingException, UnsupportedEncodingException, IOException {

        String from = "差出人メールアドレス";
        String fromName = "差出人名を指定します";
        String subject = "件名を指定します";
        String to = "宛先メールアドレス";
        String toName = "宛名を指定します";
        String body = "これは本文です。\n\n\n\n\n\n\n\n\n\n以上。";
        String attachmentFileName = "添付ファイル名.txt";
        String attachmentFileType = "text/plain; charset=UTF-8";
        byte[] attachmentFileBody = "これは添付ファイルです。\n\n\n\n\n\n\n\n\n\n以上。".getBytes("UTF-8");

        String host = "メール送信サーバホスト";
        String user = "メール送信アカウント";
        String password = "メール送信アカウントパスワード";

        Properties properties;
        Session session;
        Store store = null;
        Transport transport = null;
        MimeMessage mimeMessage;
        MimeBodyPart messageBody;
        MimeMultipart multipart;
        InternetAddress[] address;

        try {
            properties = System.getProperties();
            properties.setProperty("mail.transport.protocol", "smtps");
            properties.setProperty("mail.smtp.port", "465");
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.starttls.enable", "true");
            properties.setProperty("mail.smtp.starttls.required", "true");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.fallback", "true");

            session = Session.getInstance(properties);

            mimeMessage = new MimeMessage(session);
            //件名は(一応)JISで
            mimeMessage.setSubject(MimeUtility.encodeText(subject, "iso-2022-jp", "B"), "iso-2022-jp");
            mimeMessage.setSentDate(new Date());

            address = new InternetAddress[1];
            address[0] = new InternetAddress(from);
            //差出人名は設定しなくても問題ない
            if (fromName != null) {
                //差出人名は(一応)JISで
                address[0].setPersonal(MimeUtility.encodeText(fromName, "iso-2022-jp", "B"));
            }
            mimeMessage.setFrom(address[0]);

            address[0] = new InternetAddress(to);
            //宛名は設定しなくても問題ない
            if (toName != null) {
                //宛名は(一応)JISで
                address[0].setPersonal(MimeUtility.encodeText(toName, "iso-2022-jp", "B"));
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, address);

            /*
                マルチパートのメッセージを作成する
                構造
                    パート1: 本文
                    パート2: 添付ファイル
             */
            multipart = new MimeMultipart();
            mimeMessage.setContent(multipart);

            //パート1: 本文
            messageBody = new MimeBodyPart();
            //本文のテキストは(一応)JISで
            messageBody.setText(body, "iso-2022-jp");
            messageBody.setHeader("Content-Transfer-Encoding", "7bit");
            multipart.addBodyPart(messageBody);

            //パート2: 添付ファイル
            messageBody = new MimeBodyPart();
            //添付ファイル名は(一応)JISで
            messageBody.setFileName(MimeUtility.encodeText(attachmentFileName, "iso-2022-jp", "B"));
            messageBody.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(attachmentFileBody), attachmentFileType)));
            multipart.addBodyPart(messageBody);

            transport = session.getTransport();
            transport.connect(host, user, password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        }
        finally {
            if (store != null) {
                try {
                    store.close();
                }
                catch (Exception e) {
                }
            }
            if (transport != null) {
                try {
                    transport.close();
                }
                catch (Exception e) {
                }
            }
        }
    }
}

動作確認

$ javac SMTPSTest.java
$ java SMTPSTest

送られてきたメールを見てみます。 無題.png 指定した通りの

  • 差出人名
  • 宛名
  • 件名
  • 本文
  • 添付ファイル名

が表示されています。

添付ファイルを開いてみます。 無題2.png

環境

Webツールも公開しています。 Web便利ツール@ツールタロウ

Java Runtimeでdigする

はじめに

Runtimeで外部アプリを叩いているだけじゃないか、というご指摘はごもっともです。

事前に準備する外部ライブラリ等はありません。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。 結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author tool-taro.com
 */
public class Dig {

    public static void main(String[] args) throws IOException, InterruptedException {

        //検索したいドメイン
        String source = "tool-taro.com";
        //nslookupのパス
        String nslookupPath = "/usr/bin/dig";

        //nslookup処理
        String[] commandArray = new String[3];
        commandArray[0] = nslookupPath;
        commandArray[1] = source;
        commandArray[2] = "ANY";
        final String encoding = "UTF-8";

        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        StringBuilder logBuilder = new StringBuilder();
        StringBuilder errorBuilder = new StringBuilder();
        int status = 0;

        try {
            process = runtime.exec(commandArray);
            final InputStream in = process.getInputStream();
            final InputStream ein = process.getErrorStream();

            Runnable inputStreamThread = () -> {
                BufferedReader reader = null;
                String line;
                try {
                    reader = new BufferedReader(new InputStreamReader(in, encoding));
                    while (true) {
                        line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        logBuilder.append(line).append("\n");
                    }
                }
                catch (Exception e) {
                }
                finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        }
                        catch (Exception e) {
                        }
                    }
                }
            };
            Runnable errorStreamThread = () -> {
                BufferedReader reader = null;
                String line;
                try {
                    reader = new BufferedReader(new InputStreamReader(ein, encoding));
                    while (true) {
                        line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        errorBuilder.append(line).append("\n");
                    }
                }
                catch (Exception e) {
                }
                finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        }
                        catch (Exception e) {
                        }
                    }
                }
            };

            Thread inThread = new Thread(inputStreamThread);
            Thread errorThread = new Thread(errorStreamThread);

            inThread.start();
            errorThread.start();

            status = process.waitFor();
            inThread.join();
            errorThread.join();
        }
        finally {
            if (process != null) {
                try {
                    process.destroy();
                }
                catch (Exception e) {
                }
            }
        }
        //標準出力
        System.out.format("検索結果=%1$s", logBuilder.toString());
    }
}

動作確認

$ javac Dig.java
$ java Dig
$ 検索結果=; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.2 <<>> tool-taro.com ANY
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 36600
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1
...(省略)

環境

上記の実装をベースにWebツールも公開しています。 dig(ドメインサーチ)|Web便利ツール@ツールタロウ

Java Cookieのセット・取得、Secure属性

はじめに

事前に準備する外部ライブラリ等はありません。

実装例

Cookieを管理するクラスを定義します。

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tool-taro.com
 */
public class CookieTest {

    public static String getCookie(HttpServletRequest request, String name) {
        String result = null;

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    result = cookie.getValue();
                    break;
                }
            }
        }

        return result;
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String path, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        //httpsで稼働している環境であればCookieが暗号化されるようSecure属性をつける
        if ("https".equals(request.getScheme())) {
            cookie.setSecure(true);
        }
        response.addCookie(cookie);
    }
}

Cookie管理機構の準備が終わりました。 サンプルでは、動作確認しやすいようにjspで実装しています。

<%-- 
    Author     : tool-taro.com
--%>

<%@page import="CookieTest"%>
<%@page contentType="text/html" pageEncoding="UTF-8" session="false" %>
<%
        //Cookieから"test_cookie_name"というKeyで登録された値(文字列)を取り出す
        String value = CookieTest.getCookie(request, "test_cookie_name");

        //valueがnullの場合のみCookieをセットする(期限は5分)
        if (value == null) {
                CookieTest.setCookie(request, response, "/", "test_cookie_name", "test_cookie_value", 5 * 60);
        }
%>
<!DOCTYPE html>
<html>
    <head>
        <title>tool-taro.com</title>
    </head>
    <body>
        取得した値="<%= value%>"<br>
    </body>
</html>

動作確認

cookie_test.jspの実行結果を見てみましょう。

取得した値="null"

想定通りの結果を得られました。 2回目のアクセスでは次のような結果となります。

取得した値="test_cookie_value"

想定通りの結果を得られました。

ブラウザでCookieが管理されている状況を確認します。 パスや有効期限が指定通り管理されています。 また、httpsでアクセスされた場合に限り"Secure"属性を指定していますので、 クライアント(ブラウザ)からのCookie送信の扱いについて違いが出ます。

http 無題.png

https 無題.png

環境

Webツールも公開しています。 Web便利ツール@ツールタロウ

Java Runtimeでnslookupする

はじめに

Runtimeで外部アプリを叩いているだけじゃないか、というご指摘はごもっともです。

事前に準備する外部ライブラリ等はありません。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。 結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author tool-taro.com
 */
public class NsLookup {

    public static void main(String[] args) throws IOException, InterruptedException {

        //検索したいドメイン・IPアドレス
        String source = "tool-taro.com";
        //nslookupのパス
        String nslookupPath = "/usr/bin/nslookup";

        //nslookup処理
        String[] commandArray = new String[2];
        commandArray[0] = nslookupPath;
        commandArray[1] = source;
        final String encoding = "UTF-8";

        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        StringBuilder logBuilder = new StringBuilder();
        StringBuilder errorBuilder = new StringBuilder();
        int status = 0;

        try {
            process = runtime.exec(commandArray);
            final InputStream in = process.getInputStream();
            final InputStream ein = process.getErrorStream();

            Runnable inputStreamThread = () -> {
                BufferedReader reader = null;
                String line;
                try {
                    reader = new BufferedReader(new InputStreamReader(in, encoding));
                    while (true) {
                        line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        logBuilder.append(line).append("\n");
                    }
                }
                catch (Exception e) {
                }
                finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        }
                        catch (Exception e) {
                        }
                    }
                }
            };
            Runnable errorStreamThread = () -> {
                BufferedReader reader = null;
                String line;
                try {
                    reader = new BufferedReader(new InputStreamReader(ein, encoding));
                    while (true) {
                        line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        errorBuilder.append(line).append("\n");
                    }
                }
                catch (Exception e) {
                }
                finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        }
                        catch (Exception e) {
                        }
                    }
                }
            };

            Thread inThread = new Thread(inputStreamThread);
            Thread errorThread = new Thread(errorStreamThread);

            inThread.start();
            errorThread.start();

            status = process.waitFor();
            inThread.join();
            errorThread.join();
        }
        finally {
            if (process != null) {
                try {
                    process.destroy();
                }
                catch (Exception e) {
                }
            }
        }
        //標準出力
        System.out.format("検索結果=%1$s", logBuilder.toString());
    }
}

動作確認

> javac NsLookup.java
> java NsLookup
> 検索結果=Server:         XXX.XXX.XXX.XXX
Address:        XXX.XXX.XXX.XXX#XX

Non-authoritative answer:
Name:   tool-taro.com
Address: XXX.XXX.XXX.XXX

環境

上記の実装をベースにWebツールも公開しています。 Nslookup(ドメイン/IPアドレスサーチ)|Web便利ツール@ツールタロウ

Java UUDecode(UUEncodeのデコード)

はじめに

事前に以下のライブラリを用意します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。 結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

/**
 *
 * @author tool-taro.com
 */
public class UUDecoder {

    public static void main(String[] args) throws MessagingException, IOException {

        //デコードしたい文字列
        String source = "begin 644 encoder.buf\n"
                + ")XX*_XX.MXX*F\n"
                + " \n"
                + "end";
        //デコード後に文字列に置き換える際のエンコーディング
        String encoding = "UTF-8";

        //デコード処理
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        InputStream in = null;

        try {
            in = MimeUtility.decode(new ByteArrayInputStream(source.getBytes(encoding)), "uuencode");
            byte[] buf = new byte[1024];
            int length;
            while (true) {
                length = in.read(buf);
                if (length == -1) {
                    break;
                }
                bout.write(buf, 0, length);
            }
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                }
                catch (Exception e) {
                }
            }
        }

        String result = new String(bout.toByteArray(), encoding);
        //標準出力
        System.out.format("デコード結果=%1$s", result);
    }
}

動作確認

$ javac UUDecoder.java
$ java UUDecoder
$ デコード結果=タロウ

環境

上記の実装をベースにWebツールも公開しています。 UUDecode|Web便利ツール@ツールタロウ

Java UUEncode

はじめに

事前に以下のライブラリを用意します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。 結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

/**
 *
 * @author tool-taro.com
 */
public class UUEncoder {

    public static void main(String[] args) throws MessagingException, IOException {

        //エンコードしたい文字列
        String source = "タロウ";
        //エンコード前にバイト配列に置き換える際のエンコーディング
        String encoding = "UTF-8";

        //エンコード処理
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        OutputStream out = null;
        try {
            out = MimeUtility.encode(bout, "uuencode");
            out.write(source.getBytes(encoding));
        }
        finally {
            if (out != null) {
                try {
                    out.close();
                }
                catch (Exception e) {
                }
            }
        }

        String result = new String(bout.toByteArray(), encoding);
        //標準出力
        System.out.format("エンコード結果=%1$s", result);
    }
}

動作確認

$ javac UUEncoder.java
$ java UUEncoder
$ エンコード結果=begin 644 encoder.buf
)XX*_XX.MXX*F
 
end

環境

上記の実装をベースにWebツールも公開しています。 UUEncode|Web便利ツール@ツールタロウ