2015年12月2日水曜日

MySQLでの実行コマンドの履歴を表示するには

MySQLのコマンドのログをチェックしたかったので調べたら、どうやらファイルが作成されているようだ。

cat ~/.mysql_history

http://stackoverflow.com/questions/7818031/sql-command-to-display-history-of-queries

SpringでUTF8エンコードで表示されない問題の解決方法

Spring MVCで文字エンコーディングがUTF8で表示されないので苦戦したが、どうやらエンコードで使っていたフィルターの順序が問題だったようなので、1番目に設定したらエンコード問題がなくなった。

 <filter>
     <filter-name>EncodingFilter</filter-name>
     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
     </init-param>
     <init-param>
         <param-name>forceEncoding</param-name>
         <param-value>true</param-value>
     </init-param>
 </filter>

http://stackoverflow.com/questions/16029269/utf-8-encoding-with-form-post-and-spring-controller

2015年9月13日日曜日

iPhotoの写真でビックリマークが出現した時の対処方法

MacのOSのバージョンアップを重ねたり、外付けハードが予期せぬ出来事でUSBから外れたりと、どういう状況で発生しているのか分かりませんが、iPhotoのアルバム内の写真がビックリマークの出現で表示できないという事態が起こる時があります。

こういう場合はiPhoto起動時にCommand+Optionを押すと、フォトライブラリFirst Aidを使う。データベースを修復というオプションで修復できない場合は、データベースの再構築で修復する。

参考:
https://discussions.apple.com/thread/3873468?start=0&tstart=0

2015年8月8日土曜日

Blocked loading mixed active contentが出た時に気をつけること

FirefoxのFirebugで"Blocked loading mixed active content..."というエラーが出てるので調べてみると、どうやらCDNを使ってHTMLページでインポートしてるJS/CSSファイルが読み込まれていない。

さらに掘り下げてみると、httpsで読み込んでるページからhttpでこれらのCDNからJS/CSSを読み込もうとするとエラーが出てるようだ。

What is Mixed Content?When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.
引用:
http://stackoverflow.com/questions/18251128/why-am-i-suddenly-getting-a-blocked-loading-mixed-active-content-issue-in-fire

要するに、HTTPSのページにHTTPリクエストで呼ばれているコンテンツがあると、それを”mixied(混在した)”コンテンツとみなし、MITM攻撃の被害になりえるのでやめて下さいとFirefoxが新しいバージョンではエラーとして表示してくれているようだ。

一般的な解決策は意外と簡単で、インポートしてるファイル(js/css)の構文をhttpからhttpsに変えてやればいい。もしくは//みたいな書き方でURLをブラウザが自動判別してくれるということ。

http://stackoverflow.com/questions/4831741/can-i-change-all-my-http-links-to-just

追加:

ただ、CDNによってはhttpからhttpsになぜかリクエストが変わってくれなかったので、そういうケースは泣く泣くCDNを使わずローカルにファイルを保存したりして回避した。

2015年8月5日水曜日

Tomcat6でjsessionidをURLから表示させないようにするには?

Tomcat6でjsessionidをURLから表示させないようにするには、context.xmlでContextの属性値をdisableURLRewriting="true"にしてやる。

<Context disableURLRewriting="true">
....
</Context>

http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

2015年8月1日土曜日

Antでビルドする時にサーバー環境によってweb.xmlの内容を書き換えたいのでcopyタスクのFilterChainsを使う

Antでビルドする時にサーバー環境によってweb.xmlの内容や他の設定ファイル類の内容を書き換えたいので調べてみたら、copyタスクにFilterChainsというタスクで指定した文字列を書き換える事ができると分かったのでやってみた。

やり方の流れ:


  1. 書き換えたいファイルのテンプレートとなるファイルを作る(web_template.xml)
  2. テンプレートで書き換わる文字列をプロパティとして設定したファイルを作る(server1.xml)
  3. ビルドファイルにテンプレートと変数を元に生成するファイル(web.xml)を作るルールを書く(build.xml)
1.web_template.xml

....
<context-param>
    <param-name>someparameter</param-name>
    <param-value>@somevariable@</param-value>
</context-param>
....

※@~@の@は分かり易くつけてるだけです。

2.server1.xml

<project>
    <property name="server.host" value="abc.com" />
</project>

3.build.xml

<target name="rewriteXmlFile" >

    <copy file="/template/web_template.xml"  tofile="/WEB-INF/web.xml" overwrite="true">
        <filterchain>
            <tokenfilter>
                <replacestring from="@somevariable@" to="${server.host}"/>        
            </tokenfilter>
        </filterchain>
    </copy>

</target>



http://stackoverflow.com/questions/5217501/ant-copy-filterset
http://ant.apache.org/manual/Tasks/copy.html
http://ant.apache.org/manual/Types/filterchain.html#replacestring


2015年7月30日木曜日

MySQLのSelect文で特定の文字列の場所を見つけると同時に分割する関数

MySQLのSelect文で特定の文字列の場所を見つけると同時に分割する関数でsubstring_indexというのが便利だったのでメモ。indexofとsubstringの両方が合わさったもの。

substring_index("www.google.com",".","2)

1つ目と2つ目の引数は明らかなので割愛。3つ目の引数がポイント。

正の数:分割された文字列の何番目かを左からから指す
負の数:分割された文字列の何番目かを右からから指す


http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php

2015年6月17日水曜日

MySQLについてくるautomysqlbackupの使い方

MySQLにはバックアップ専用にautomysqlbackupがついてくるので、ちょっと使い方についてメモ書き。


  1. sudo apt-get install automysqlbackup でインストール
  2. /var/lib/automysqlbackup にバックアップが毎日作られるが、スクリプト中で保存先は指定できる。
※ BACKUPDIRとDBNAMESぐらいかな、変更したのは。。




https://serverpilot.io/community/articles/how-to-back-up-mysql-databases-with-automysqlbackup.html

MySQL 5.1 をUbuntu 12.04にインストールする方法

MySQL5.1をUbuntu12.04にインストールしようと思ったら、apt-getでは5.5がインストールされてしまうので、ソースからMySQL5.1をインストールするのに以下を参考にした。

シェルスクリプトでもコマンドラインからでもOK。

#!/bin/bash

set -e

cd ~/
wget http://downloads.mysql.com/archives/mysql-5.1/mysql-5.1.65.tar.gz
tar -zxf mysql-5.1.65.tar.gz
cd mysql-5.1.65
./configure  '--prefix=/usr' '--exec-prefix=/usr' '--libexecdir=/usr/sbin' '--datadir=/usr/share' '--localstatedir=/var/lib/mysql' '--includedir=/usr/include' '--infodir=/usr/share/info' '--mandir=/usr/share/man' '--with-system-type=debian-linux-gnu' '--enable-shared' '--enable-static' '--enable-thread-safe-client' '--enable-assembler' '--enable-local-infile' '--with-fast-mutexes' '--with-big-tables' '--with-unix-socket-path=/var/run/mysqld/mysqld.sock' '--with-mysqld-user=mysql' '--with-libwrap' '--without-readline' '--with-ssl' '--without-docs' '--with-extra-charsets=all' '--with-plugins=max' '--with-embedded-server' '--with-embedded-privilege-control'
make
sudo make install


参考
http://askubuntu.com/questions/125686/failed-to-spawn-mysql-main-process-unable-to-execute-no-such-file-or-director

2015年5月15日金曜日

HTML5でログインフォームの書き方

HTML5でログインフォームの書き方

HTML

<section class="loginform cf">  
<form name="login" action="/path" method="POST" accept-charset="utf-8">
    <ul>  
        <li><label for="usermail">Login Name</label>
        <input type="text" name="loginName" placeholder="login name" required></li>
        <li><label for="password">Password</label>
       <input type="password" name="password" placeholder="password" required></li>
        <li><input type="submit" value="Login"></li>
    </ul>  
</form>  

</section> 

CSSは参考リンク参照

参考
http://www.hongkiat.com/blog/html5-loginpage/

JavaScriptでhtmlのDOMエレメントのクラス名を得るには?

JavaScriptでhtmlのDOMエレメントのクラス名を得るには?

document.getElementById('divId').className.split(/\s+/);

参考
http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery

MySQL5.5をUbuntuから完全に消去する方法

MySQL5.5をUbuntuからアンインストールしたかったので、やり方を調べてみた。

sudo deluser mysql
sudo delgroup mysql
sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.5
sudo apt-get purge mysql-client-core-5.5
参考
http://stackoverflow.com/questions/10853004/removing-mysql-5-5-completely
http://askubuntu.com/questions/125686/failed-to-spawn-mysql-main-process-unable-to-execute-no-such-file-or-director

Ubuntuで新規ユーザーにsudo権限を与える方法

Ubuntuで新規ユーザーにsudo権限を与える方法

1.% sudo adduser (username)
2.% sudo gpasswd -a (username) sudo
3.% logout

参考
https://ueponx.wordpress.com/2013/09/23/ubuntu%E3%81%AB%E3%81%A6%E6%96%B0%E8%A6%8F%E3%83%A6%E3%83%BC%E3%82%B6%E3%81%ABsudo%E3%81%AE%E6%A8%A9%E9%99%90%E3%82%92%E3%81%A4%E3%81%91%E3%82%8B/

JavaScriptでhtmlのページにパラメーターを追加して更新する方法

JavaScriptでhtmlのページをリフレッシュする方法

var url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
}else{
   url += '?param=1'
}
window.location.href = url;

参考
http://stackoverflow.com/questions/5997450/append-to-url-and-refresh-page

mysqldumpでエラーを無視して実行する方法

mysqldumpでエラーを無視して実行する方法

-f, --force         Continue even if we get an sql-error.

参考
http://serverfault.com/questions/302151/how-do-i-ignore-errors-with-mysqldump

jsessionidを表示しないようにTomcatを設定するには?

jsessionidをURLに表示しないようにTomcatを設定するには?

web.xml

<!-- Disable the URL based jsessionid. -->
<session-config>
  <tracking-mode>COOKIE</tracking-mode>

</session-config>

参考
http://stackoverflow.com/questions/11327631/remove-jsessionid-from-url

mysqldumpでダンプを圧縮して実行する方法

ダンプ
% mysqldump <mysqldump options> | gzip outputfile.sql.gz

リストア
% gunzip < outputfile.sql.gz | mysqldump <mysqldump options>


参考
http://www.ducea.com/2006/10/28/compressing-mysqldump-output/

Spring MVCでファイルアップロードのやり方

Spring MVCでファイルアップロードのやり方は、必要最低限以下の設定でできる。

1. POMにApache Commons FileUploadとIOを付け足す

 <!-- Apache Commons FileUpload --> 
 <dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
 </dependency>
 
 <!-- Apache Commons IO --> 
 <dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
 </dependency>
2.JSPのformタグ

<form method="POST" action="uploadFile" enctype="multipart/form-data">
  File to upload: <input type="file" name="file"><br /> 
  Name: <input type="text" name="name"><br /> <br /> 
  <input type="submit" value="Upload">
</form>
3.CommonsMultipartResolverをSpringの設定ファイルに付け足す

 <beans:bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- setting maximum upload size -->
  <beans:property name="maxUploadSize" value="100000" />

 </beans:bean>
4.コントローラーのインターフェース

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
 public @ResponseBody
 String uploadFileHandler(@RequestParam("name") String name,
   @RequestParam("file") MultipartFile file)


参考
http://www.journaldev.com/2573/spring-mvc-file-upload-example-tutorial-single-and-multiple-files

2015年3月31日火曜日

Javaでファイルの拡張子を簡単に得る方法

Javaでファイルの拡張子を簡単に得るには、FilenameUtilsを使う。


import org.apache.commons.io.FilenameUtils;


String ext = FilenameUtils.getExtension(fileName);

http://stackoverflow.com/questions/924394/how-to-get-file-name-without-the-extension

2015年3月24日火曜日

libapache2-mod-fastcgiがApacheのモジュールとしてロードされていない時の対処方法

Apacheでfastcgiを使っていて、Ubuntuのリリースアップグレードなどのきっかけで、FastCgiServerのシンタックスがiipsrv.confで使えませんというエラーが出た。

/etc/apache2/mods-enabled/iipsrv.conf

---> FastCgiServer .......    ------>ここがエラーになる。

1.fastcgiがApacheのモジュールとしてロードされていない事を確認

  %> sudo apache2ctl -M

2./etc/apt/source.listでfastcgiが含まれるmultiverseに編集
3.sudo apt-get udpate
4.sudo apt-get install libapache2-mod-fastcgi
5.sudo a2enmod fastcgi でfastcgiをApacheのモジュールとしてロード
6.sudo apachectl configtest で設定ファイルのシンタックスが正しいかチェック
7.sudo /etc/init.d/apache2 restart

これでfastcgi_module (shared)が出ればOK。

きっかけはUbuntuのリリース・アップグレードで起こったので、注意しないなと思いました。こういうところは気づきにくい。。。


参考
https://help.ubuntu.com/community/HelpOnInstalling/FastCgi
https://www.howtoforge.com/how-to-set-up-apache2-with-mod_fcgid-and-php5-on-ubuntu-10.04
http://serverfault.com/questions/599707/e-package-libapache2-mod-fastcgi-has-no-installation-candidate-debian-ser
http://serverfault.com/questions/395139/cant-install-fastcgi-ubuntu-server-package-libapache2-mod-fastcgi-is-not-availa
http://www.binarytides.com/install-apache-php-mod-fastcgi-ubuntu/
https://wiki.archlinux.org/index.php/Apache_and_FastCGI
http://superuser.com/questions/284898/how-to-check-which-apache-modules-are-enabled-installed
http://www.unixmen.com/install-apache2-fastcgi-ubuntu-server-14-0413-10/


2015年3月20日金曜日

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bagsが発生した場合の対処方法

Hibernateでorg.hibernate.loader.MultipleBagFetchException発生した場合、Listを使っているプロパティをSetに変えてやれば問題は解消される。

原因については未だ調査中。。。

http://stackoverflow.com/questions/24675340/org-hibernate-loader-multiplebagfetchexception-cannot-simultaneously-fetch-mult

Apache POIでエクセルファイルを読み込むサンプルコード


         ByteArrayInputStream bis = null;
            Workbook workbook = null;
            try {
                bis = new ByteArrayInputStream(file.getBytes());            
                
                if (file.getOriginalFilename().endsWith("xls")) {
                    workbook = new HSSFWorkbook(bis);
                } else if (file.getOriginalFilename().endsWith("xlsx")) {
                    workbook = new XSSFWorkbook(bis);
                } else {
                    throw new IllegalArgumentException("Received file does not "
                    + "have a standard excel extension.");
                }
                
                // Iterate rows
                for ( Row row : workbook.getSheetAt(0) ) {                

                }
                
                ....
                
              }


http://stackoverflow.com/questions/14740727/upload-excel-file-into-database-using-apache-poi-and-spring-framework

Spring MVC 3.1ではRedirectAttributesが便利

Spring MVC 3.1ではリダイレクト先のページに値を受け渡しするのにRedirectAttributesが使えるので便利。


redirectAttributes.addFlashAttribute("key", value);

そしてリダイレクトするには、


return "redirect:someView";

http://www.tikalk.com/redirectattributes-new-feature-spring-mvc-31/

Tomcatで8080から8443にフォワードするには?

web.xmlを

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Someapp</web-resource-name>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>

    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

server.xmlを

<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
          maxThreads="150" scheme="https" secure="true"
          clientAuth="false" sslProtocol="TLS" 
          keystoreFile="/somepath/.keystore"
          keystorePass="somepass"/>


JavaScriptでparseIntの戻り値がNaNの場合の対処方法

var s = '';

var num = parseInt(s) || 0;

http://stackoverflow.com/questions/6736476/javascript-parseint-return-nan-for-empty-string

jQueryで兄弟(同列)のDomエレメントにアクセスするには?

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li class="third-item">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

$( "li.third-item" ).siblings().css( "background-color", "red" );


http://api.jquery.com/siblings/

POIでエクセルのセルが空かどうか調べるには?

Cell c = row.getCell(3);
 if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
    // This cell is empty
 }

http://stackoverflow.com/questions/15764417/how-to-check-if-an-excel-cell-is-empty-using-poi

Spring Securityでベーシック認証をするには?

applicationContext.xmlに以下を書き込む。


<security:http auto-config='true'>
<security:intercept-url pattern="/somepath/*" access="ROLE_USER"/>
<security:intercept-url pattern="/somepath/**" access="ROLE_USER"/>
     <security:http-basic />
</security:http>

<security:authentication-manager>
   <security:authentication-provider>
        <security:user-service>
        <security:user name="someid" password="somepass" authorities="ROLE_USER" />
        </security:user-service>
    </security:authentication-provider>

</security:authentication-manager>

Javaでリモートからの画像ファイルをダウンロードするには?



    response.setHeader("Content-Disposition""filename=\""+ fileName + "\"");
    response.setContentType("image/jpeg");

    URL url = new URL(fileLink);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();


ヘッダーの設定をダウンロードするファイルによって設定する。IOUtilsでストリームをコピーするのは便利。

Ubuntuでシステムクロックを正常にするにはntpdateを使う

ntpdate ntp.ubuntu.com

https://help.ubuntu.com/10.04/serverguide/NTP.html

mysqldumpでデータのみをダンプする場合

$ mysqldump -uroot -p --no-create-info testdb > dump.sql

http://zetcode.com/databases/mysqltutorial/exportimport/

JavaでURLエンコードをする場合、特定の文字に注意する。

特定の文字を別途変換する必要がある。

String encodeStr = URLEncoder.encode("*-_", "UTF-8");
encodeStr = encodeStr.replace("*", "%2a");
encodeStr = encodeStr.replace("-", "%2d");

String encodeStr = URLEncoder.encode("a a", "UTF-8");
encodeStr = encodeStr.replace("+", "%20");

http://javatechnology.net/java/url-encode/

Apacheで特定のIPアドレスからのみリクエストを受け付ける場合

Allow From xxxx.xxxx.xxxx.xxxx を使う。

<Directory /APP>

    Order Allow,Deny

    Allow from 160.120.25.65
    Allow from 127.0.0.0/8

</Directory>

http://stackoverflow.com/questions/714332/allow-request-coming-from-specific-ip-only

Apacheでサブディレクトリをリバースプロキシさせたくない場合

サブディレクトリをリバースプロキシさせたくない場合は、!を使う。

ProxyPass /mirror/foo/i !
ProxyPass /mirror/foo http://backend.example.com


http://httpd.apache.org/docs/2.2/ja/mod/mod_proxy.html#proxypass
http://serverfault.com/questions/391457/how-does-apache-merge-multiple-matching-location-sections

2015年1月24日土曜日

MySQLで複数のクエリの結果を比較する方法

2つのテーブルの違いを知りたい場合など、MySQLで複数のクエリの結果を比較したい場合がある。そういう時はこれ。

SELECT id FROM tableA
WHERE id NOT IN (
    SELECT id FROM tableB
)

http://stackoverflow.com/questions/1569990/mysql-is-it-possible-to-get-the-difference-of-two-query-results

HTML5ではobjectタグの属性値がdeprecatedになっているので注意

HTML5でのappletの挙動が特定のブラウザで変だったので、objectタグについて調べてみると、属性がdeprecated(推奨されていない)になっているので注意。

<object ..... code="..." >

</object>



<object ...... >
    <param name="code" value="..." />
</object>

に変わったことに注意。

http://www.w3.org/TR/html-markup/object.html


2015年1月13日火曜日

Hibernateで親エンティティの重複を無くすには?

SQLでJOINを使うと親エンティティが重複されてレコードが取得されてしまう場合がある。この場合、Hibernateで親エンティティの重複を無くして、ユニークなレコードを取得したい場合、Criteria#setResultTransformerを使う。


criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

http://learningviacode.blogspot.in/2013/06/why-need-for-resulttransformers.html

2015年1月9日金曜日

Linuxのgrepで特定のキーワードを含まないログファイルを標準出力に出したい場合

Linuxのgrepで特定のキーワードを含まないログファイルを標準出力に出したい場合

% tail -f some.log | grep -v --line-buffered somekeyword

http://stackoverflow.com/questions/7161821/how-to-grep-a-continuous-stream
http://stackoverflow.com/questions/10411616/grep-regex-not-containing-string

Window7でhostsファイルを管理者権限でしか書き込めないとエラーがでる場合

Window7でhostsファイルを管理者権限でしか書き込めないとエラーがでる場合

Notepadを管理者権限モードで開く。右クリックでそういうのが出てくる。

http://stackoverflow.com/questions/20906492/cant-edit-the-host-file

ちなみにhostsファイルはc:\windows\system32\drivers\etc

MySQLで複数のカラムをユニークキーにするには?

MySQLで複数のカラムをユニークキーにするには?

ALTER TABLE `sometable` ADD UNIQUE `unique_index` (`columnA`,`columnB`,`columnC`)

http://stackoverflow.com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql

MySQLでauto incrementの値をリセットするには?

MySQLでauto incrementの値をリセットするには?

ALTER TABLE sometable AUTO_INCREMENT=1

http://stackoverflow.com/questions/970597/change-auto-increment-starting-number

MySQLで複数カラムから最大値を取るには?

MySQLで複数カラムから最大値を取るには?

GREATEST(value1, value2, value3,...)

http://www.w3resource.com/mysql/comparision-functions-and-operators/greatest-function.php

でも、nullは比べたくない場合、

GREATEST(IFNULL(value1, 0), IFNULL(value2, 0), IFNULL(value3,0),...)

http://stackoverflow.com/questions/9831851/mysql-get-max-or-greatest-of-several-columns-but-with-null-fields