スパゲッティなコード忘備録
あずにゃん「スパゲッティのように絡まったコードには皆さん激おこですが、私が男の子に絡まれても同じように怒ってくれますか?」
寮に暮らしていた時にゴミ捨てアナウンス用に作成したプログラムをぽいっと。その時の環境の制約が割とあって、少し複雑な作りになっているんだが、パーツパーツとしては、利用する機会があるかな(限りなく無さそう)っていう感じで、とりあえず置いておくことにしようといったそんなモチベーションでたらたらチラ裏。
全体の動作概要は、一週間のゴミ捨ての内容を、WEBページから取得して、gmail経由で送信をしようっていう内容。
コーディングルールの本を読む前に書いた可読性0の古いソースコードのため、書き方に関しては勘弁。
下記ソースは、gmailでメールを送信するための処理となる。
jsse.jarと、mail.jarが必要なため、ビルドパスに通しておく必要あり。
import java.io.IOException; import java.security.Security; import java.util.Calendar; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.net.ssl.internal.ssl.Provider; public class Gmail { public static void sendMessage( String host, int port, String from, String to, String title, String text) throws IOException { try { Security.addProvider(new Provider()); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", port); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //gmailのアカウントを右の例のように書くこと("username","pass") return new PasswordAuthentication("gmailaccountを記入", "gmailパスワードを記入"); } }; Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] addresses = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, addresses); msg.setSubject(title, "iso-2022-jp"); msg.setSentDate(Calendar.getInstance().getTime()); msg.setText(text, "utf-8"); Transport.send(msg); } catch (Throwable e) { e.printStackTrace(); try { System.in.read(); } catch (IOException e1) { e1.printStackTrace(); } } } }
下記ソースは、http://www.city.aizuwakamatsu.fukushima.jp/index_php/gomical/index_i.php?typ=p
このページから、1週間のスケジュールを抜き出してくるための処理を行う。
Gomi.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Gomi { public static void main(String[] args) throws IOException { String sendmessage = ""; String smtp = "smtp.gmail.com"; //gmail int port = 587; //gmailのport番号 String sender = "@gmail.com"; //送信者 String to = "@gmail.com"; //宛先 String title = "hoge"; //メールタイトル try { Gmail.sendMessage(smtp,port,sender, to, title,SendMessage()); } catch (IOException e) { e.printStackTrace(); } } /** * URLからゴミの捨ての日の情報を抜き出す * */ private static String SendMessage() { String orgDatas = ""; String sendmessage = ""; String Ja_mes=""; String Eng_mes=""; try { URL url = new URL("http://www.city.aizuwakamatsu.fukushima.jp/index_php/gomical/index_i.php?typ=p"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); String data = "m=000800&d=1&send=send_pass"; // html form parameter wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader( new InputStreamReader(conn.getInputStream(),"utf-8")); String line; while ((line = rd.readLine()) != null) { orgDatas += line; } wr.close(); rd.close(); } catch (Exception e) { } //日付のリストday ArrayList<String> day = new ArrayList<String>(); //内容のリストobj Ja_mes = "今週のゴミ出しは以下の通りです。\r\n当日の朝6時から朝8時30分までに出すようお願いします。それ以外の時間帯は回収されません。\r\n"; Eng_mes = "\r\nThis week's schedule for garbage disposal is below.\r\nPlease take them to garbage yard between 6 to 8:30 a.m. In else time, nothing is collected by the operators.\r\n"; ArrayList<String> obj = new ArrayList<String>(); Pattern pattern = Pattern.compile("<li class=\"tri1\"><h3>([^<]*)</h3>([^<]*)</li>"); Matcher matcher = pattern.matcher(orgDatas); //日本語用処理 int count=0; for(int i = 0;i < 10;i++){ try{ matcher.find(); day.add(matcher.group(1)); obj.add(matcher.group(2)); Ja_mes = Ja_mes + day.get(i)+" "+obj.get(i)+"\r\n"; count++; }catch(Exception e){ } } //英語用処理 for(int i = 0;i < count;i++){ //曜日を英語に置換する処理 day.set(i, day.get(i).replaceAll("日", "Sun.")); day.set(i, day.get(i).replaceAll("月", "Mon.")); day.set(i, day.get(i).replaceAll("火", "Tue.")); day.set(i, day.get(i).replaceAll("水", "Wed.")); day.set(i, day.get(i).replaceAll("木", "Thu.")); day.set(i, day.get(i).replaceAll("金", "Fri.")); day.set(i, day.get(i).replaceAll("土", "Sat.")); //System.out.println(day.get(i)); //ゴミの内容を英語に置換する処理 obj.set(i,obj.get(i).replaceAll("なし","nothing")); obj.set(i,obj.get(i).replaceAll("燃やせるごみ","burnable garbage")); obj.set(i,obj.get(i).replaceAll("かん類","cans")); obj.set(i,obj.get(i).replaceAll("ペットボトル","Plastic bottle")); obj.set(i,obj.get(i).replaceAll("プラスチック製容器包装","plastic containers and packing")); obj.set(i,obj.get(i).replaceAll("古紙類","used papers")); obj.set(i,obj.get(i).replaceAll("燃やせないごみ","non-burnable garbage")); obj.set(i,obj.get(i).replaceAll("粗大ごみ(リサイクル品を含む)","balk garbage(including recyclables)")); obj.set(i,obj.get(i).replaceAll("びん類","been")); Eng_mes = Eng_mes + day.get(i)+" "+obj.get(i)+"\r\n"; } sendmessage = Ja_mes + Eng_mes; System.out.println(sendmessage); return sendmessage; } }
上記の実行結果
今週のゴミ出しは以下の通りです。 当日の朝6時から朝8時30分までに出すようお願いします。それ以外の時間帯は回収されません。 07/18(金) 燃やせるごみ 07/19(土) なし 07/20(日) なし 07/21(月) びん類・プラスチック製容器包装・古紙類・粗大ごみ(リサイクル品を含む) 07/22(火) 燃やせるごみ 07/23(水) なし This week's schedule for garbage disposal is below. Please take them to garbage yard between 6 to 8:30 a.m. In else time, nothing is collected by the operators. 07/18(Fri.) burnable garbage 07/19(Sat.) nothing 07/20(Sun.) nothing 07/21(Mon.) been・plastic containers and packing・used papers・balk garbage(including recyclables) 07/22(Tue.) burnable garbage 07/23(Wed.) nothing
あとは、cron使って、1週間に一回自動でプログラムを回すよう、登録しておけばおしまい。
これにしか使えないので、汎用性がないのがあれだけど、まあパーツがいつか輝くと信じて。