Category Archives: Java

「Android-NDK」JNIローカルファイルをデバックしてプリントする

Javaコード:
#include <android/log.h>
#define LOG_TAG “libibmphotophun” //locatのtagを定義
#define LOGI(…) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
//Log().i
#define LOGE(…) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
//Log().e

「Java開発」Javaでhttpsクライアント、サーバー側処理サンプルプログラム

1.クラスの定義
rivate static class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance(“TLS”);
public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

2.HttpClient側処理プログラム
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();

HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(“http”, PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme(“https”, sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,SET_SOCKET_TIMEOUT);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,SET_CONNECTION_TIMEOUT);
return client;
} catch (Exception e) {
return new DefaultHttpClient();
}
}
3.サーバーリクエスト
public static JSONObject getAccessTokenByPost(String url, JSONObject pa) {
HttpClient httpClient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(“Content-Type”, “application/x-www-form-urlencoded”);
httpPost.setHeader(“authorization”, “Basic dG91Y2hhYXBwOnNlY3JldHBhc3N3b3Jk”);
httpPost.setHeader(“connection”, “Keep-Alive”);
httpPost.setHeader(“accept”, “*/*”);
JSONObject result = null;
try {
if (pa != null) {
Map<String, String> map = (Map<String, String>) pa.get(“value”);
String parm = getRequestData(map);
httpPost.setEntity(new StringEntity(parm));
}
// httpPostフォームの送信
HttpResponse response = httpClient.execute(httpPost);
//サーバーの応答エンティティオブジェクトを取得
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == HttpStatus.SC_OK) {
String body = EntityUtils.toString(responseEntity, “utf-8″);
if (!””.equals(body)&& body !=null ) {
result = new JSONObject(body);
}else {
result = new JSONObject();
}
result.put(“statusCode”, HttpStatus.SC_OK);
} else {
result = new JSONObject();
result.put(“statusCode”, statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// リソースを解放
httpClient.getConnectionManager().shutdown();
}
return result;
}

「android開発」Parcelable直列化を実現するサンプルコード

Javaコード:
package com.mat.pocketbook.bean;

import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;

public class ProductBrandBean_Startnews24 implements Parcelable {
private int id;
private int conunt;
private String urlIcon;
private String brandName;

public static final Parcelable.Creator<ProductBrandBean_Startnews24> CREATOR = new Creator<ProductBrandBean_Startnews24>() {

@Override
public ProductBrandBean_Startnews24 createFromParcel(Parcel source) {
// TODO Auto-generated method stub
// メンバ変数宣言を順次に読み取る
ProductBrandBean_Startnews24 p = new ProductBrandBean_Startnews24();
p.setId(source.readInt());
p.setConunt(source.readInt());
p.setUrlIcon(source.readString());
p.setBrandName(source.readString());
return p;
}

@Override
public ProductBrandBean_Startnews24[] newArray(int size) {
// TODO Auto-generated method stub
return new ProductBrandBean_Startnews24[size];
}
};
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public ProductBrandBean_Startnews24() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getConunt() {
return conunt;
}
public void setConunt(int conunt) {
this.conunt = conunt;
}
public String getUrlIcon() {
return urlIcon;
}
public void setUrlIcon(String urlIcon) {
this.urlIcon = urlIcon;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
// オブジェクトのシリアライゼーション
dest.writeInt(id);
dest.writeInt(conunt);
dest.writeString(urlIcon);
dest.writeString(brandName);

}

}

「Java入門」HashMap(keysetとentryset)で要素の格納と取り出す方法のまとめ

Javaコード:
方法1 entrySet
Map map = HashMap();
Iterator iter = map.entrySet().iterator();
(iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}

方法2 keySet
Map map = HashMap();
Iterator iter = map.keySet().iterator();
(iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}

方法1をお勧めします

「Java開発」mybatisで一括データを挿入するサンプルコード

Javaコード:
<insert id=”batchInsert” parameterType=”java.util.List”>
insert into T_DT_DICT (ID, PROJECT_ID, NAME,
PARENT_ID, LEVEL, PATH,
CREATE_DATE, MODIFIER_ID, MODIFIER,
MODIFY_DATE, SEQUENCE, CODE
)
values
<foreach collection=”list” item=”item” index=”index” separator=”,” >
(#{item.id},#{item.projectId},#{item.name},#{item.parentId},#{item.level},#{item.path},#{item.createDate},
#{item.modifierId},#{item.modifier},#{item.modifyDate},#{item.sequence},#{item.code}
)
</foreach>
</insert>

Log4jの設定ファイルの設置方法

参考コード
# Global logging configuration
log4j.rootLogger=info, stdout,fileout
# Console output…
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] – %m%n
#log4j.logger.com.hhdys.dao=debug
#File output…
log4j.appender.fileout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileout.file=F:/log_startnews24/log_startnews24.txt
log4j.appender.fileout.fileName=base_startnews24.log
log4j.appender.fileout.encoding=UTF-8
log4j.appender.fileout.datePattern=’.’yyyy-MM-dd
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%5p [%t] – %m%n

「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();
}
}
}