Category Archives: Java

「Java開発」ファイルのアップロード、画像圧縮を実現する

package com.eabax.plugin.yundada.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eabax.plugin.yundada.GaContext;

public class FileUploadDownloadUtil {
private static final Logger log = LoggerFactory.getLogger(FileUploadDownloadUtil.class);
/**
* Serverにファイルをアップロード
* @param request
* @param type
* @return
* @throws Exception
*/
public static String upload(HttpServletRequest request, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String saveFileName = null;
if (isMultipart) {
String savePath = request.getSession().getServletContext()
.getRealPath(“/”)
+ “/upload/”;
String tempPath = request.getSession().getServletContext()
.getRealPath(“/”)
+ “/upload/temp/”;
File saveFile = new File(savePath);
File tempFile = new File(tempPath);
if (!saveFile.isDirectory())
saveFile.mkdirs();
if (!tempFile.isDirectory())
tempFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(tempFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {

if (item.isFormField()) {
// funName=item.getString();
} else {
// String fileName=item.getName();
// String
// fix=fileName.substring(fileName.lastIndexOf(“.”)+1);
String fix = type;
Date nowDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(
“yyyyMMddhhmmss”);
String fileName = sdf.format(nowDate);

fileName += System.currentTimeMillis();
fileName += “.” + fix;
saveFileName = “/upload/” + fileName;

File file = new File(savePath + fileName);
item.write(file);
}
}
}
return saveFileName;
}

/**
* 画像のアップロード
* @param request
* @param type
* @return
* @throws Exception
*/
public static String uploadHeadShow(HttpServletRequest request,GaContext context, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String saveFileName = null;
String imagePath = “/upload/headshow/”;
String x = request.getParameter(“length”);
String y = request.getParameter(“wide”);
if (isMultipart) {
String headShowServicePath = request.getSession().getServletContext()
.getRealPath(“/”)
+ imagePath;
Date nowDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(
“yyyyMMddhhmmss”);
String fileName = context.getUsername()+sdf.format(nowDate);
File headShowFile = new File(headShowServicePath);
if (!headShowFile.isDirectory())
headShowFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(headShowFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {

if (item.isFormField()) {
// funName=item.getString();
} else {
String fix = type;
fileName += “.” + fix;
saveFileName = imagePath + fileName;
File file = new File(headShowServicePath + fileName);
item.write(file);
}
}
//画像圧縮
if(x!=null&&!””.equals(x) && y!=null&&!””.equals(y)) {
saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
}
}
return saveFileName;
}

/**
* 写真をアップロードして共有
* @param request
* @param type
* @return
* @throws Exception
*/
public static JSONObject uploadArticleImage(HttpServletRequest request,GaContext context, String type) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
JSONObject saveFileName = new JSONObject();
String imagePath = “”;
String x = request.getParameter(“length”);
String y = request.getParameter(“wide”);
if(“4”.equals(type)) {
//写真アップロードのパス
imagePath = “/upload/articleimage/”;
}else if(“5”.equals(type)) {
//画像パスのリンク
imagePath = “/upload/linkimage/”;
} else {
//画像アップロードパス
imagePath = “/upload/headshow/”;
}
if (isMultipart) {
String headShowServicePath = request.getSession().getServletContext()
.getRealPath(“/”)
+ imagePath;
File headShowFile = new File(headShowServicePath);
if (!headShowFile.isDirectory())
headShowFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(headShowFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {
UUID uuid = UUID.randomUUID();
String fileName = uuid.toString();
if (item.isFormField()) {
// funName=item.getString();
} else {
String fix = type;
fileName += “.” + fix;
saveFileName.put( uuid.toString(),imagePath + fileName);
File file = new File(headShowServicePath + fileName);
item.write(file);
}
//画像圧縮
if(x!=null&&!””.equals(x) && y!=null&&!””.equals(y)) {
String thumbnailatorName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
saveFileName.put(“thumbnailatorImage”, thumbnailatorName);
}
}
}
return saveFileName;
}

/**
* 圧縮画像をアップロードして保存
* @param oldSavePath
* @param oldFileName 原文件名称
* @param fix ファイルタイプ
* @param x 幅
* @param y 長さ
* @return
* @throws IOException
*/
public static String thumbnailatorImage(String oldSavePath,String oldFileName,String fix,int x,int y) throws IOException {

BufferedImage waterMarkBufferedImage = Thumbnails.of(oldSavePath+oldFileName)

.size(x, y)

.asBufferedImage();

String savePath = oldSavePath+x+”-“+y+”/”;
File saveFile = new File(savePath);
if (!saveFile.isDirectory())
saveFile.mkdirs();

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(saveFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);

UUID uuid = UUID.randomUUID();
String fileName = uuid.toString();
fileName += “.” + fix;
String saveFileName = savePath+fileName;
File fileOutPut = new File(saveFileName);
ImageIO.write(waterMarkBufferedImage, fix, fileOutPut);
return saveFileName;
}

public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {

String uriSubPath = uri.substring(0, uri.lastIndexOf(“/”)+1);
String fileName = uri.substring(uri.lastIndexOf(“/”)+1,uri.length());
String getThumbnailatorPath = servicePath + uriSubPath+x+”-“+y+”/”;
String saveFileName = getThumbnailatorPath+fileName;
File downFilePath = new File(getThumbnailatorPath);
File downFile = new File(saveFileName);
if (downFilePath.isDirectory()&&downFile.exists()) {
return saveFileName;
} else {

log.error(servicePath+uri);
BufferedImage waterMarkBufferedImage = Thumbnails.of(servicePath+uri)
.size(x, y)
.asBufferedImage();
if (!downFilePath.isDirectory()) {
downFilePath.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(downFilePath);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
File fileOutPut = new File(saveFileName);
ImageIO.write(waterMarkBufferedImage, “jpg”, fileOutPut);
}
return saveFileName;
}
}

「objective-c」Javaでクラスを判定するサンプルコード

Javaコード:
f [obj isKindOfClass:[NSString class]]{
[obj …];
}else if([obj respondsToSelect:@selector(shoot:)]){ //no matter what obj is
[obj shoot]; // if obj has shoot method ,it can be excuted
}

//SEL is a type
SEl shootSelecor = @selector(shoot:); <span></span>

「Java学習」javaでbmpをjpegに変換するサンプルコード

Javaコード:
public static String saveBitmap2File(String url) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
SimpleDateFormat sf = new SimpleDateFormat(“yyyy_MM_dd_HH_mm_ss”);
String timeStamp = sf.format(new Date());
File targetFile = new File(Constants.ENVIROMENT_DIR_SAVE, timeStamp
+ “.jpg”);
File oldfile = ImageLoader.getInstance().getDiscCache().get(url);
try {
inBuff = new BufferedInputStream(new FileInputStream(oldfile));
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[BUFFER];
int length;
while ((length = inBuff.read(buffer)) != -1) {
outBuff.write(buffer, 0, length);
}
outBuff.flush();
return targetFile.getPath();
} catch (Exception e) {
} finally {
if (inBuff != null) {
inBuff.close();
}
if (outBuff != null) {
outBuff.close();
}
}
return targetFile.getPath();
}

「Java学習」Javaでファイルを削除するサンプルコード

Javaコード:
public static void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
}
}
}

「Java学習」Javaでディレクトリのファイル容量を計算するサンプルコード

Javaコード
public static long getFileSize(File f) {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;

「Java学習」Javaでディレクトリのファイル容量を検出するサンプルコード

Javaコード
public static long getFileSize(File f) {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;
}

「Java初心者」javaでストリームを読む処理サンプルコード

Javaコード
public static String readTextInputStream(InputStream is) throws IOException {
StringBuffer strbuffer = new StringBuffer();
String line;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
strbuffer.append(line).append(“\r\n”);
}
} finally {
if (reader != null) {
reader.close();
}
}
return strbuffer.toString();
}

「Java初心者」javaでテキストファイルを読み込むサンプルコード

Javaコード
public static String readTextFile(File file) throws IOException {
String text = null;
InputStream is = null;
try {
is = new FileInputStream(file);
text = readTextInputStream(is);;
} finally {
if (is != null) {
is.close();
}
}
return text;
}

WindowsとLinux環境にTomcat JVMメモリを設定する方法のまとめ

1.LinuxでTomcat JVMメモリを修正
ファイル:catalina.sh
箇所:cygwin=falseの前
追加:
# OS specific support. $var _must_ be set to either true or false.
JAVA_OPTS=”-Xms256m -Xmx512m -Xss1024K -XX:PermSize=128m -XX:MaxPermSize=256m”
cygwin=false

2.WindowsでTomcat JVMメモリを設定

2.1 解凍版でインストールしたTomcat
ファイル catalina.bat
箇所 「rem Guess CATALINA_HOME if not defined
set CURRENT_DIR=%cd%」の後ろ
追加内容
set JAVA_OPTS=-Xms256m -Xmx512m -XX:PermSize=128M -XX:MaxNewSize=256m -XX:MaxPermSize=256m -Djava.awt.headless=true

2.2 インストーラー版でインストールしたTomcat
ファイル /bin/tomcat6w.exe

「Java開発」「JBAS015052: Did not receive a response to the deployment operation 」解決方法

エラーメッセージ:
JBAS015052: Did not receive a response to the deployment operation within the allowed timeout period [60 seconds]. Check the server configuration file and the server logs to find more about the status of the deployment.

解決方法

1.standalone.xmlを修正
<subsystem xmlns=”urn:jboss:domain:deployment-scanner:1.1″>
<deployment-scanner path=”deployments” relative-to=”jboss.server.base.dir” scan-interval=”5000″ />
</subsystem>

2.「deployment-timeout=”1000″」を追加
<subsystem xmlns=”urn:jboss:domain:deployment-scanner:1.1″>
<deployment-scanner path=”deployments” relative-to=”jboss.server.base.dir” scan-interval=”5000″ deployment-timeout=”1000″/>
</subsystem>